Search code examples
c#cpinvokemarshalling

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:

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

From the Doc: DataBuf Destination of transmitted data

What shall I use in C# call?

  • byte[]
  • myByteArr[0]
  • P/Invoke Assistant suggested 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.


Solution

  • 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.

    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. This means that no copying is performed and the parameter passing is efficient.