【问题标题】:How do I retrive information from this array?如何从该数组中检索信息?
【发布时间】:2013-07-17 18:49:09
【问题描述】:

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

但这不起作用

【问题讨论】:

    标签: c# c++ arrays copy marshalling


    【解决方案1】:

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

    (语法可能有点不对劲,但这是大意……)

    【讨论】:

    • 第三个参数是起始索引 Marshal.Copy(IntPtr source, int[] destination, int startIndex, int length);我将如何申请取消引用?
    • 我的第一个副本是将一个 int 数组复制到一个 IntPtr,第二个是将一个 IntPtr 复制到一个 int 数组。这就是论点不同的原因。另外我不能在c#中使用指针和引用,有没有可以使用的等价物?
    • 我相信我现在的答案是正确的。我很抱歉在没有花时间更早地完全理解的情况下发帖。
    猜你喜欢
    • 2022-01-08
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 2015-01-25
    • 1970-01-01
    • 2021-09-09
    • 2019-03-02
    • 2014-02-09
    相关资源
    最近更新 更多