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.