如何从此阵列中检索信息?

时间:2013-07-18 17:11:31

标签: c# c++ arrays copy marshalling

我有一个IntPtr指向另一个指向非托管数组的IntPtr。我想知道如何将这个非托管阵列复制到托管阵列?我知道我必须使用Marshal.Copy,但是当我有一个指针指针时,我不确定如何使用它。

这是我的示例代码

非托管C ++:

void foo(Unsigned_16_Type**  Buffer_Pointer);

托管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);

所以现在在这一点上我有一个IntPtr到IntPtr到ppUnmanagedBuffer里面的一个数组但是我不确定如何使用Marshal.Copy将该数组复制到一个新的托管数据

我试过像

这样的东西
int[] arrayRes = new int[word_count];
Marshal.Copy(ppUnmanagedBuffer, arrayRes, 0, word_count);

但这不起作用

1 个答案:

答案 0 :(得分:0)

唯一剩下的就是“撤消”以下调用,让ppUnmanagedBuffer指向您期望的数据类型:

GCHandle handle = GCHandle.Alloc(p_Buffer, GCHandleType.Pinned);

IntPtr ppUnmanagedBuffer = (IntPtr)handle.AddrOfPinnedObject();

如果C#通过此机制设法为您提供等效的int**,那么您需要取消引用一次以获得等效于int[],如下所示:

Marshal.Copy((IntPtr)(GCHandle.FromIntPtr(ppUnmanagedBuffer).target), arrayRes, 0, word_count);

(语法可能有些偏差,但这是一般的想法......)