日期:2014-05-18  浏览次数:21446 次

C# string 转char*
我在C#中使用了C++生成的dll,由于dll的原型函数参数 是char*,所以导致C#中的 string变量传递有误(编译正确,输出结果有误),请问怎么办?代码如下:
//C++ dll源码:
...
EXPORT void _stdcall setFeature(char* _feature); 
...

//C#调用 源码:
  [DllImport("LicenseDll.dll", CharSet = CharSet.Ansi)]//C#调用C++ dll的指令
  static extern int setFeature(string feature);
  // static extern int setFeature(char* feature);

static void Main(string[] args)
 {
......
  string kk = "f2";
  setFeature(kk);//编译正确,结果有误
  setFeature("f2");//);//编译 结果都正确
......
}

------解决方案--------------------
使用 out 或是 ref 参数 试试
------解决方案--------------------
转这个有什么用?

------解决方案--------------------
用StringBuilder试试,C++中的char*是可变长的字符串,因此到C#里就只能用StringBuilder来对应,是否要家ref,看情况,这里估计不需要。
C# code
[DllImport("LicenseDll.dll", CharSet = CharSet.Ansi)]//C#调用C++ dll的指令
static extern int setFeature(StringBuilder feature);