There are several ways to access the IntPtr that correspond to a byte array.
The first is to use unsafe blocks of code to access pointers that directly point 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 objects.
| 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 (); |
The third is to create a block of memory through LocalAlloc and marshal the data to the memory block.
| The code is 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);
} |