Search code examples
c#cwinapisyntaxdllimport

How to define dllimport of c++ function with void *buffer in C#


I am trying to integrate with photo printer CHC-S6145 using C++ DLL S6145usb.dll. There is a function defined there as below. I want to know what is the mapping c# DLL import for that.

Function name - chcusb_getPrinterInfo

Format

BOOL APIENTRY chcusb_getPrinterInfo (WORD tagNumber, void *rBuffer, DWORD *rLen); 

Function details Obtain the information of the specified printer based on tag identifier.


Solution

  • BOOL is a 32bit integer in Win32. PInvoke has a Boolean type, which can be marshaled as a 32bit integer via MarshalAs.

    WORD is a 16bit unsigned integer. C# has a Uint16 type for that.

    void* is a raw pointer. C# uses the (U)IntPtr type for that.

    DWORD is a 32bit unsigned integer. C# has a UInt32 type for that.

    DWORD*, on the other hand, is a pointer to a DWORD. C# has ref and out specifiers for passing a parameter variable by reference. Which one you need to use depends on whether the parameter is input/output (ref) or output-only (out).

    Try something like this:

    [DLLImport("S6145usb.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern Boolean chcusb_getPrinterInfo(UInt16 tagNumber, IntPtr rBuffer, ref UInt32 rLen);
    
    ...
    
    UInt32 bufLen = ...;
    IntPtr buffer = Marshal.AllocHGlobal((int)bufLen);
    chcusb_getPrinterInfo(..., buffer, ref bufLen);
    // use buffer as needed...
    Marshal.FreeHGlobal(buffer);