C# 调用C++问题

小枪 2016-11-22 03:36:24
不懂C++
有个东西需要用到C++

不太明白方法体转换
原型如下
enum usb_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
};
struct usb_relay_device_info
{
unsigned char *serial_number;
char *device_path;
usb_relay_device_type type;
usb_relay_device_info* next;
};

int EXPORT_API usb_relay_init(void);
struct usb_relay_device_info EXPORT_API * usb_relay_device_enumerate(void);

我改成C#程序如下
[DllImport("usb_relay_device")]
extern static int usb_relay_init();

[DllImport("usb_relay_device")]
extern static usb_relay_device_info usb_relay_device_enumerate();

public enum usb_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
};
// public static usb_relay_device_info usb=new usb_relay_device_info();
/*usb relay board info structure*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct usb_relay_device_info
{
public byte[] serial_number;
public string device_path;
public usb_relay_device_type type;
public usb_relay_device_info[] next;
};

现测试init方法可以调试通 调试正确 但返回结构体方法 usb_relay_device_enumerate 返回异常
方法的类型签名与 pinvoke 不兼容


好费解 求大神解答
...全文
130 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
xian_wwq 2016-11-23
  • 打赏
  • 举报
回复
dllimport转换时, int,float等基本类型都可以对应定义,char* 不能直接用string类对应 原因是只定义了指针,空间大小不确定,调用就有问题

[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi,Pack=1]
public struct  SMyconfig
{
     [MarshalAs(UmmanagedType.ByValTStr,SizeConst=100)]  //这个长度的定义需要去找c api提供的文档或者咨询dll提供方
     public string FilePath;
}

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧