最近在研究用QT调用C#类库的方法,在C#类库中分别编写int,char,string返回值的函数
通过实验,int、char返回值的函数可以在C++中正常调用
而string返回值的函数调用时出现了问题。
原因是当用C++读取C#返回值string类型是,读到的类型为String^类型,C++/CLR中使用gcnew关键字表示托管上分配内存,为了与以前的指针区分开,用^来代替*,解决的方法就是将String^转换成通用类型。
在百度一下午后,我发现了好几种转换方法,我认为只要掌握了String^转换为char*类型便可解决。
具体转换方法:
.cpp头文件中需包括
using namespace System; //String^库文件
using namespace System::Runtime::InteropServices; //Marchal库文件
函数内容
char* c = "adsfdasf";
String^ strd = gcnew String(c);
char* d = (char*)(void*)Marshal::StringToHGlobalAnsi(strd);
cout << d << endl;
转换为char*之后便可以进行后续的处理
Ps: using namespace System; 出现问题须在
项目-属性-配置属性-常规-公共语言运行时支持
改为 ” 公共语言运行时支持(/clr)“