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

标签 c# c api pinvoke

示例 C API 签名:

void Func(unsigned char* bytes);

在 C 中,当我想传递一个指向数组的指针时,我可以这样做:

unsigned char* bytes = new unsigned char[1000];
Func(bytes); // call

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

最佳答案

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

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

byte[] ar = new byte[1000];
Func(ar);

您还应该能够将参数声明为 IntPtr 并手动编码(marshal)数据。

[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);

关于c# - 如何在 C# 中使用 p/invoke 将指针传递给数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/289076/

相关文章:

c# - 计算进度百分比

c - 洪水游戏,尝试几次后崩溃

api - Binance API key

c++ - StringCbPrintf 示例不工作

rest - Elasticsearch存在对对象类型的查询返回0个结果

c# - FOR-EACH 通过 IEnumerable 与列表

c# - 发送多个 Ping 而不等待回复 Windows C#

c - C 中的数据驱动网络方法。这不是新的吗?

c# - Visual Studio 2010 文档映射扩展

c - 将字符串存储到c中的数组中