Several ways to convert C # byte[] to IntPtr in ASP.

Source: Internet
Author: User

There are several ways to access the IntPtr corresponding to the byte array.

First, use unsafe blocks of code to access pointers directly to byte arrays.

The code is as follows Copy Code

Unsafe
{
byte[] test = new BYTE[5];
Fixed (byte* p = &test[0])
{
*p = 0xFF;
}
}


Second, you can use GCHandle to get the object.

The code is as follows Copy Code


Using System.Runtime.InteropServices;

byte[] test = new BYTE[5];
GCHandle hobject = GCHandle.Alloc (test, gchandletype.pinned);
IntPtr pobject = Hobject.addrofpinnedobject ();

if (hobject.isallocated)
Hobject.free ();


Third, create a block of memory through LocalAlloc and marshal the data to that memory block.

  code as follows copy code

[DllImport (" Coredll.dll ", Setlasterror=true)]
public static extern IntPtr LocalAlloc (UINT Uflags, uint ubytes);
[DllImport ("Coredll.dll", Setlasterror=true)]
public static extern IntPtr LocalFree (IntPtr hmem);
[DllImport ("Coredll.dll", Setlasterror=true)]
public static extern IntPtr Localrealloc (IntPtr hmem, uint ubytes, uint fuflags);

Public const UINT LMEM_FIXED = 0;
Public const UINT LMEM_MOVEABLE = 2;
Public const UINT LMEM_ZEROINIT = 0x0040;

Byte[] test = new BYTE[5];
IntPtr p = LocalAlloc (lmem_fixed | Lmem_zeroinit, (UINT) test. Length);

if (p = = IntPtr.Zero)
{
    throw new OutOfMemoryException ();
}
Else
{
    marshal.copy (test, 0, p, test. Length);
}

originally from: Http://www.111cn.net/net/160/66646.htm

Several ways to convert C # byte[] to IntPtr in ASP.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.