I have an IntPtr pointing to another IntPtr pointing to an unmanaged array. I was wondering how can I copy this unmanaged array to a managed one? I know I would have to use Marshal.Copy but I'm unsure of how to use it when I have a pointer to a pointer.
Here is my example code
Unmanaged C++:
void foo(Unsigned_16_Type** Buffer_Pointer);
Managed C#:
[DllImport("example.dll")]
public static extern void foo(IntPtr Buffer_Pointer);
//...
//...
int[] bufferArray = new int[32];
IntPtr p_Buffer = (IntPtr)Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(int)) * bufferArray.Length);
Marshal.Copy(bufferArray, 0, p_Buffer, bufferArray.Length);
GCHandle handle = GCHandle.Alloc(p_Buffer, GCHandleType.Pinned);
IntPtr ppUnmanagedBuffer = (IntPtr)handle.AddrOfPinnedObject();
//Call to foo
foo(ppUnmanagedBuffer);
So now at this point I have a IntPtr to an IntPtr to an array inside ppUnmanagedBuffer but I'm unsure of how to copy that array over to a new managed one using Marshal.Copy
I tried something like
int[] arrayRes = new int[word_count];
Marshal.Copy(ppUnmanagedBuffer, arrayRes, 0, word_count);
But that does not work
The only thing remaining is to "undo" the following calls to get ppUnmanagedBuffer
to point to the type of data you are expecting:
GCHandle handle = GCHandle.Alloc(p_Buffer, GCHandleType.Pinned);
IntPtr ppUnmanagedBuffer = (IntPtr)handle.AddrOfPinnedObject();
If C# has managed to give you the equivalent of int**
by this mechanism, then you need to dereference it once to get an equivalent to int[]
, like so:
Marshal.Copy((IntPtr)(GCHandle.FromIntPtr(ppUnmanagedBuffer).target), arrayRes, 0, word_count);
(The syntax may be off a bit, but that's the general idea...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.