簡體   English   中英

如何從該陣列中檢索信息?

[英]How do I retrive information from this array?

我有一個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);

但這不起作用

唯一剩下的就是“撤消”以下調用以使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);

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM