繁体   English   中英

如何编组指向int的指针?

[英]How do I marshal a pointer to a pointer to an int?

Umanaged C ++:

int  foo(int **    New_Message_Pointer);

我如何将其编组到C#?

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

您可以声明这样的函数:

[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);

你会想要它

static extern int foo(IntPtr New_Message_Pointer)

一旦你有了IntPtr,困难的部分可能就是用它做什么...

您可能希望从SO中查看此问题该问题涉及指向指针到结构的指针。 它有所不同,但可能会让你朝着正确的方向前进。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM