c#调用c++ dll 参数对应

本文介绍如何从C#调用C++DLL中的函数,特别是针对字符串和结构体类型的参数传递技巧,包括使用string与StringBuilder的区别及注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

c++ dll 中方法:

int __stdcall Comm_Send(const data_Head struHead, const wchar_t* pTLV, const int nCount)

 

c#调用:

[DllImport("xxx.dll", EntryPoint = "xxx", CharSet = CharSet.Auto)]
public static extern int Comm_Send(data_Head struHead, string pTLV, int nCount);

 

EntryPoint 中是对应c++ dll的方法名,用vs自带的命令提示行dumpbin -exports xxx.dll可以看到

CharSet 一般可不写

这里const wchar_t* -----string ,wchar_t是unicode,可用string对应,CharSet.Auto可以;

 

 

 

但是如果

c++ dll 中方法:

int __stdcall Comm_Send(const data_Head struHead, wchar_t* pTLV, const int nCount)

 

 

c#调用必须:

[DllImport("xxx.dll", EntryPoint = "xxx")]
public static extern int Comm_Send(data_Head struHead, StringBuilder pTLV, int nCount);

 

wchar_t* -----StringBuilder  StringBuilder 初始化要设置一个合适的长度,大于收到的长度,不然会出现indexoutofrangeException;

如对应string会没有值,这里CharSet = CharSet.Auto,那么对StringBuilder取长度会发现和wchar_t* 的不一致,;

 

 

如果

c++ dll 中参数是struct*   c#是struct[]

 

 

先写到这里。。。。。。。。。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值