C#调用C++封装的dll返回字符串
最近在做C#调用c++封装的dll时,我用的qt封装的,由于编码问题(Windows默认GB2312,qt默认UTF-8),所以用ref string和char*交互时,返回的字符串经过编码转换后总有一部分汉字转过来还是乱码,后来经过网上查找,测试,发现了两种返回字符串的方法,记录一下。
第一种方式:传递ref byte(ref byte和C++的char*对应)
C#端定义一个byte数组,C++用char*接收,看代码
C++代码
//打开连接,打开失败时返回error信息,为了方便查看,去掉了部分代码
bool UploadFile::OpenConn(const char* host, const char* username, const char* pwd, short port, const char* rootpath, char* error)
{
string str = "从6.6.20开始,超时时间可以自定义修改了!";
strcpy(error, str.c_str());
return true;
}
C#端代码:
//这个是和C++交互的方法
[DllImport("UploadFile.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern bool OpenCon(IntPtr ptr, string host, string username, string pwd, short port, string rootpath, ref byte error);
//这个是具体调用的方法
byte[] error = new byte[1024 * 1024];
//最后一个参数要传递byte,而不是byte数组,我也不是很明白为什么,我理解是把首地址传递过去,在C++那边赋值
bool b = OpenCon(m_uploadFileClass, host, username, pwd, port, rootpath, ref error[0]);
string errorStr= Encoding.UTF8.GetString(error);
第二种方式:采用普通的函数返回值方式,用IntPtr接收
C++代码
//打开连接,打开失败时返回error信息,为了方便查看,去掉了部分代码,和上面一样,只不过返回类型改成了char*,这个只是测试
char* UploadFile::OpenConn(const char* host, const char* username, const char* pwd, short port, const char* rootpath)
{
string str = "从6.6.20开始,超时时间可以自定义修改了!";
char *error = new char[1024];
strcpy(error, str.c_str());
return error;
}
C#端代码
//和C++交互的方法 返回类型改为IntPtr
[DllImport("UploadFile.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr OpenCon(IntPtr ptr, string host, string username, string pwd, short port, string rootpath);
//具体调用
IntPtr ptr = OpenCon(m_uploadFileClass, host, username, pwd, port, rootpath);
byte[] error = new byte[1024 * 1024];
Marshal.Copy(ptr, error, 0, 1024);
//返回字节数组,将字节数组转成字符串
string errStr = Encoding.UTF8.GetString(error);
之前做过C++(Qt)的项目,对C++了解还不深入,尤其是封装外部调用这块,研究了很长时间,感谢CSDN平台,感谢广大无私的网友,大家共同学习进步,这里我只写了具体的实现和调用方法,关于C#如果调用C++的dll在我另一篇博客里有详细介绍,这里就不详细写了。