C语NET调用 C++ dll 函数 时传递字符串 需要注意的问题

1:C# 调用 返回 字符串 C++ native dll 函数 的注意事项:

a:C++ DLL的返回值,安全的做法是分配一个全局 char 数组,把要返回的 char * 复制到这个 char 数组中,

1 char   buff[255];    
2 
3 const char* __stdcall ReturnString()
4 {
5   strcpy(buff,"xxxxxxxxxxxxxxx");
6   return buff;
7  }

 

b:C# 收到 字符串后,需要 Marshal

1 [DllImport("VC.dll", EntryPoint = "ReturnString", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Winapi)]
2 public static extern IntPtr ReturnString();

 

调用VCDLL的代码...

1 IntPtr intPtr = ReturnString();
2 
3 string str = Marshal.PtrToStringAnsi(intPtr);
View Code

 

因为 C++ 返回的是 char* ,是个指针,所以c# 要用 IntPtr 来接回。

Marshal.PtrToStringAnsi MSDN上的解释:将非托管 ANSI 字符串中第一个空值(空值就是\0)之前的所有字符复制到托管 String。将每个 ANSI 字符扩展为 Unicode 字符。

 

2:用参数传递,即C++dll 函数的参数 定义为 char*,而C#传递 StringBuilder 给 c++

a:c# 创建一个 StringBuilder,并初始化 capacity后传给C++

[DllImport("VC.dll", EntryPoint = "ProcessString", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Winapi)]
public static extern void ProcessString(StringBuilder str);

//调用VCDLL的代码...

StringBuilder str = new StringBuilder(255); //255 是 capacity

ProcessString(str);

MessageBox.Show(str); //不需要Marshal,直接使用

 

b:C++ DLL函数

const char* __stdcall ProcessString(char* str)
{

  //str 是 c# 创建的 StringBuilder,长度是255
  strcpy(str,"xxxxxxxxxxxxxxx");
  return buff;
}

其他的请

 

参考msdn中的c++与c#的类型转换 对应关系如下:

 C++ ---- C#

传入的char*  ----string

传出的char* ---- StringBuilder(预分配空间)

short  ----short

char ---- byte

char[n] ---- fixed byte[n]

 

结构指针  ----结构指针

函数指针 ---- 委托

转载于:https://www.cnblogs.com/mimiaisini/p/6977713.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值