如何在C#中使用p/invoke将指针传递给数组?

Ran*_*ku' 21 c c# api pinvoke

示例C API签名:

void Func(unsigned char* bytes);

在C中,当我想将指针传递给数组时,我可以这样做:

unsigned char* bytes = new unsigned char[1000];
Func(bytes); // call
Run Code Online (Sandbox Code Playgroud)

如何将上述API转换为P/Invoke,以便我可以将指针传递给C#字节数组?

asp*_*nge 34

传递字节数组的最简单方法是将import语句中的参数声明为字节数组.

[DllImport EntryPoint="func" CharSet=CharSet.Auto, SetLastError=true]
public extern static void Func(byte[]);

byte[] ar = new byte[1000];
Func(ar);
Run Code Online (Sandbox Code Playgroud)

您还应该能够将参数声明为IntPtr并手动编组数据.

[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);
Run Code Online (Sandbox Code Playgroud)


Fly*_*wat 7

您可以使用不安全的代码:

unsafe 
{
     fixed(byte* pByte = byteArray)
     IntPtr intPtr = new IntPtr((void *) pByte);
     Func(intPtr);
}
Run Code Online (Sandbox Code Playgroud)

如果您需要使用安全代码,可以使用一些技巧:

IntPtr intPtr = Marshal.AllocHGlobal(Marshal.SizeOf(byteArray));
Marshal.Copy(byteArray, 0, intPtr, Marshal.SizeOf(byteArray));

Func(intPtr);

Marshal.FreeHGlobal(intPtr);
Run Code Online (Sandbox Code Playgroud)

但是,安全代码将会很慢恕我直言.