【问题标题】:How do I marshal a pointer to a pointer to an int?如何编组指向 int 指针的指针?
【发布时间】:2013-07-11 06:07:54
【问题描述】:

非托管 C++:

int  foo(int **    New_Message_Pointer);

如何将其编组为 C#?

[DllImport("example.dll")]
static extern int foo( ???);

【问题讨论】:

    标签: c# c++ marshalling


    【解决方案1】:

    你会想要的

    static extern int foo(IntPtr New_Message_Pointer)
    

    一旦你拥有了 IntPtr,困难的部分可能就是如何处理它......

    您可能想看看this question from SO,它处理指向结构的指针。它是不同的,但可能会让你朝着正确的方向前进。

    【讨论】:

      【解决方案2】:

      你可以这样声明函数:

      [DllImport("example.dll")]
      static extern int foo(IntPtr New_Message_Pointer)
      

      要调用此函数并将指针传递给 int 数组,例如,您可以使用以下代码:

      Int32[] intArray = new Int32[5] { 0, 1, 2, 3, 4, 5 };
      
      // Allocate unmamaged memory
      IntPtr pUnmanagedBuffer = (IntPtr)Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(Int32)) * intArray.Length);
      
      // Copy data to unmanaged buffer
      Marshal.Copy(intArray, 0, pUnmanagedBuffer, intArray.Length);
      
      // Pin object to create fixed address
      GCHandle handle = GCHandle.Alloc(pUnmanagedBuffer, GCHandleType.Pinned);
      IntPtr ppUnmanagedBuffer = (IntPtr)handle.AddrOfPinnedObject();
      

      然后将 ppUnmanagedBuffer 传递给你的函数:

      foo(ppUnmanagedBuffer);
      

      【讨论】:

        猜你喜欢
        • 2021-02-07
        • 2017-09-03
        • 1970-01-01
        • 2015-09-10
        • 1970-01-01
        • 2011-02-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多