How to import a DLL function that returns this structure?

I have a DLL and its header file that were written in Visual C ++. I need to use the following function in a C # project:

LIBSPEC int
CprFindDevices(
  PCprDeviceInfo *ppDevInfo,
  int *pNumDevices,
  DWORD timeout
  );

I can import it using DllImport, but I cannot figure out how to implement the following structure in C #:

typedef struct _CprDeviceInfo
{
  unsigned char id[ID_LEN];
  unsigned char macAddr[MAC_LEN];
  in_addr       inAddr;
  char          ipAddr[IP_LEN];
  char          devName[INFO_NAME_LEN];
  char          port1Name[INFO_NAME_LEN];
  char          port2Name[INFO_NAME_LEN];
  int           tcpPort1;
  int           tcpPort2;
  char          interfaceIpAddr[IP_LEN];
} CprDeviceInfo, *PCprDeviceInfo;

All uppercase variables are all known constants that I can use in my C # project.

I know what I should use [StructLayout(LayoutKind.Sequential)], but I'm not sure what equivalent types are for each member of the structure, and what is the function signature when importing. Some time has passed since my C ++ days.

+3
source share
1 answer

This should do the job for you:

struct CprDeviceInfo
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = ID_LEN)]
    string id;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAC_LEN)]
    string macAddr;
    uint inAddr;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = IP_LEN)]
    string ipAddr;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = INFO_NAME_LEN)]
    string devName;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = INFO_NAME_LEN)]
    string port1Name;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = INFO_NAME_LEN)]
    string port2Name;
    int tcpPort1;
    int tcpPort2;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = IP_LEN)]
    string interfaceIpAddr;
}

, Charset.ASCII DLLImport, .

+2

All Articles