[英]How do I retrive information from this array?
I have an IntPtr pointing to another IntPtr pointing to an unmanaged array. 我有一个IntPtr指向另一个指向非托管数组的IntPtr。 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. 我知道我必须使用Marshal.Copy,但是当我有一个指针指针时,我不确定如何使用它。
Here is my example code 这是我的示例代码
Unmanaged C++: 非托管C ++:
void foo(Unsigned_16_Type** Buffer_Pointer);
Managed C#: 管理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 所以现在在这一点上我有一个IntPtr到IntPtr到ppUnmanagedBuffer里面的一个数组但我不确定如何使用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: 唯一剩下的就是“撤消”以下调用以使ppUnmanagedBuffer
指向您期望的数据类型:
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: 如果C#通过这种机制设法给你等效的int**
,那么你需要取消引用它一次得到一个等价的int[]
,如下所示:
Marshal.Copy((IntPtr)(GCHandle.FromIntPtr(ppUnmanagedBuffer).target), arrayRes, 0, word_count);
(The syntax may be off a bit, but that's the general idea...) (语法可能有些偏差,但这是一般的想法...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.