如何编组指向int的指针?

use*_*127 5 c# c++ marshalling

Umanaged C++:

int  foo(int **    New_Message_Pointer);
Run Code Online (Sandbox Code Playgroud)

我如何将其编组到C#?

[DllImport("example.dll")]
static extern int foo( ???);
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以声明这样的函数:

[DllImport("example.dll")]
static extern int foo(IntPtr New_Message_Pointer)
Run Code Online (Sandbox Code Playgroud)

要调用此函数并将指针传递给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();
Run Code Online (Sandbox Code Playgroud)

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

foo(ppUnmanagedBuffer);
Run Code Online (Sandbox Code Playgroud)