简体   繁体   English

如何在C#中从C.dll封送字节*

[英]How to marshall byte* from C.dll in C#

I have two functions that I am trying to call from C# that shares similar signatures: 我尝试从共享相似签名的C#调用两个函数:

BOOL Read (BYTE Len, BYTE* DataBuf)
BOOL Write (BYTE Len, BYTE* DataBuf)

From the Doc: DataBuf Destination of transmitted data 从文档:DataBuf传输数据的目标

What shall I use in C# call? 我应该在C#调用中使用什么?

  • byte[] 字节[]
  • myByteArr[0] myByteArr [0]
  • P/Invoke Assistant suggested System.IntPtr P /调用助手建议使用System.IntPtr

Don't have the hardware to test yet, but i am trying to get as many of calls right for when we have. 尚没有要测试的硬件,但我正在尝试尽可能多地拨打电话。

Thanks. 谢谢。

For the read function you use: 对于读取功能,请使用:

[Out] byte[] buffer

For the write function you use: 对于写功能,请使用:

[In] byte[] buffer

[In] is the default and can be omitted but it does not hurt to be explicit. [In]是默认值,可以省略,但明确表示并没有什么害处。

The functions would therefore be: 因此,这些功能将是:

[DllImport(filename, CallingConvention = CallingConvention.Cdecl)]
static extern bool Read(byte len, [Out] byte[] buffer);

[DllImport(filename, CallingConvention = CallingConvention.Cdecl)]
static extern bool Write(byte len, [In] byte[] buffer);

Obviously you'll need to allocate the array before passing it to the unmanaged functions. 显然,您需要先分配数组,然后再将其传递给非托管函数。

Because byte is blittable then the marshaller, as an optimisation, pins the array and passes the address of the pinned object. 因为byte是可蓝调的,所以作为最佳化,封送处理程序将数组固定,并传递固定对象的地址。 This means that no copying is performed and the parameter passing is efficient. 这意味着不执行复制,并且参数传递效率很高。

It'll probably be IntPtr obtained from a byte[] array. 它可能是从byte[]数组获得的IntPtr Older questions should definitely have covered that: How to get IntPtr from byte[] in C# 较老的问题肯定涵盖了: 如何从C#中的byte []获取IntPtr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM