c# - 如何将指针编码为指向 int 的指针?

标签 c# c++ marshalling

非托管 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);

关于c# - 如何将指针编码为指向 int 的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17619307/

相关文章:

c# - 什么是同步和异步方法?

c# - Xamarin.IOS MonoTouch.Dialog ExpandableDatePickerElement 无法正常工作

c++ - 在非操作系统 Arm 板上使用 'fopen'

c# - 覆盖 Windows 窗体中的标准关闭 (X) 按钮

c# - ServiceStack 完整菜鸟教程

c++ - 如何在qt中使用QStackedwidget从一个ListWidget导航到另一个ListWidget

c++ - 是否可以对 float 逼近的不同形式进行分类

c# - 如何防止 CompileAssemblyFromSource 泄漏内存?

java - Jaxb - 如何将一个 xml 元素解码到多个字段?

C# 结构到字节数组的编码方式与 Delphi 中的打包记录相同