gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:25:12 25 4
gpt4 key购买 nike

非托管 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com