How do I handle a complex struct return type from a C DLL file within C#? -


i've been trying c library (dll) working simple test code in c#. far i've been able import , use simple functions fine. issue i'm having right don't know how receive complex struct return type imported function.

here 2 function signatures:

c:

#define hid_api_export __declspec(dllexport) #define hid_api_call  struct hid_device_info hid_api_export * hid_api_call hid_enumerate(unsigned short vendor_id, unsigned short product_id); 

c#:

[dllimport("hidapi.dll")] public static extern hid_device_info hid_enumerate(ushort vendor_id, ushort product_id); 

and here 2 structs:

c:

struct hid_device_info {     char *path;     unsigned short vendor_id;     unsigned short product_id;     wchar_t *serial_number;     unsigned short release_number;     wchar_t *manufacturer_string;     wchar_t *product_string;     unsigned short usage_page;     unsigned short usage;     int interface_number;      struct hid_device_info *next; }; 

c#:

[structlayout(layoutkind.sequential)] public struct hid_device_info {     public intptr path;     public ushort vendorid;     public ushort productid;     public intptr serialnumber;     public ushort releasenumber;     public intptr manufacturer;     public intptr product;     public ushort usagepage;     public ushort usage;     public int interfacenumber;      public intptr next; } 

i'm getting error when run program:

managed debugging assistant 'pinvokestackimbalance' has detected problem in 'c:\users\tajensen\documents\hidapics\hidapitest\bin\debug\hidapitest.vshost.exe'.

additional information: call pinvoke function 'hidapics!hidapics.hidapi::hid_enumerate' has unbalanced stack. because managed pinvoke signature not match unmanaged target signature. check calling convention , parameters of pinvoke signature match target unmanaged signature.

i've done bit of digging , things i've been able find describe how receive return types of simple structs (i.e. no pointers, , basic types ints , bools). appreciate additional insight on issue, know want be, don't know enough kind of code dig deeper on own.

thanks in advance, toms

your structure looks good, baring command line flags change packing of it.

likely, it's because of line

#define hid_api_call 

this means you're using default calling convention, __cdecl. so, change p/invoke definition to:

[dllimport("hidapi.dll", callingconvention = callingconvention.cdecl)] public static extern hid_device_info hid_enumerate(ushort vendor_id, ushort product_id); 

so rules how manage stack on c side followed properly.


Comments