问题描述
C++代码:构造体:enumusb_relay_device_type{USB_RELAY_DEVICE_ONE_CHANNEL=1,USB_RELAY_DEVICE_TWO_CHANNEL=2,USB_RELAY_DEVICE_FOUR_CHANNEL=4,USB_RELAY_DEVICE_EIGHT_CHANNEL=8};/*usbrelayboardinfostructure*/structusb_relay_device_info{unsignedchar*serial_number;char*device_path;usb_relay_device_typetype;};C++调用方法名称:structusb_relay_device_infoEXPORT_API*usb_relay_device_enumerate(void);============================================C#构造体代码:publicclassCstruct{publicenumusb_relay_device_type{USB_RELAY_DEVICE_ONE_CHANNEL=1,USB_RELAY_DEVICE_TWO_CHANNEL=2,USB_RELAY_DEVICE_FOUR_CHANNEL=4,USB_RELAY_DEVICE_EIGHT_CHANNEL=8};[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]publicstructusb_relay_device_info{publicIntPtrserial_number;publicIntPtrdevice_path;publicusb_relay_device_typetype;}}C#调用C++DLL方法privatevoidbutton1_Click(objectsender,EventArgse){//查找设备[DllImport("usb_relay_device.dll",EntryPoint="usb_relay_device_enumerate",CharSet=CharSet.Ansi,CallingConvention=CallingConvention.Cdecl)]publicstaticexternCstruct.usb_relay_device_infousb_relay_device_enumerate();//查找设备Cstruct.usb_relay_device_infocs1=usb_relay_device_enumerate();}问:1我现在的问题是cs1取到的值都为0,不会报错2是不是我C#的构造体返回类型不应该是IntPtr。因为在C++中是指针的形式,所以在C#不知道如何定义
解决方案
解决方案二:
char*,unsignedchar*直接使用byte或者string。
解决方案三:
大神数据结构改成byte返回类型后[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)]publicstructRESULT{publicbyteserial_number;publicbytedevice_path;publicRESULT_typetype;}得到的值为:serial_number=39device_path=160type=一个随机的9位数字如:127598964问:serial_number和device_path的值是固定的,现在不知道怎么操作这个BYTE了,