如何在 C# 中使用 p/invoke 传递指向数组的指针?
问题描述:
示例 C API 签名:
Example C API signature:
void Func(unsigned char* bytes);
在C中,当我想传递一个指向数组的指针时,我可以这样做:
In C, when I want to pass a pointer to an array, I can do:
unsigned char* bytes = new unsigned char[1000];
Func(bytes); // call
如何将上述 API 转换为 P/Invoke,以便我可以传递指向 C# 字节数组的指针?
How do I translate the above API to P/Invoke such that I can pass a pointer to C# byte array?
答
传递字节数组的最简单方法是将导入语句中的参数声明为字节数组.
The easiest way to pass an array of bytes is to declare the parameter in your import statement as a byte array.
[DllImport EntryPoint="func" CharSet=CharSet.Auto, SetLastError=true]
public extern static void Func(byte[]);
byte[] ar = new byte[1000];
Func(ar);
您还应该能够将参数声明为 IntPtr 并手动编组数据.
You should also be able to declare the parameter as an IntPtr and Marshal the data manually.
[DllImport EntryPoint="func" CharSet=CharSet.Auto, SetLastError=true]
public extern static void Func(IntPtr p);
byte[] ar = new byte[1000];
IntPtr p = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(byte)) * ar.Length);
Marshal.Copy(ar, 0, p, ar.Length);
Func(p);
Marshal.FreeHGlobal(p);