public static extern void editstring2(IntPtr ptr);
[DllImport("dllfordebugdemo.dll", EntryPoint = "ansiunicode", CallingConvention = CallingConvention.Cdecl)]
public static extern void ansiunicode(string ptr);
[DllImport("dllfordebugdemo.dll", EntryPoint = "ansiunicode", CallingConvention = CallingConvention.Cdecl)]
public static extern void ansiunicode2(byte[] ptr);
//上面是同一相C++中函数,只不过在C#中被映射到不同的函数而已
string msg2 = "张三zsw";
ansiunicode(msg2);
Console.WriteLine("张三zsw的utf8字节长度=" + Encoding.UTF8.GetBytes(msg2).Length);
byte[] bs = Encoding.UTF8.GetBytes(msg2);
foreach (byte b in bs)
Console.Write(b + " ");
Console.WriteLine("转换成byte[]之后");
ansiunicode2(Encoding.UTF8.GetBytes(msg2));
void ansiunicode(char* ptr)
{
wchar_t* pc = (wchar_t*)ptr;
int index = 0;
int len = _tcslen((wchar_t*)ptr);
int ansilen = strlen(ptr);
cout << "wchar len=" << len << " ansi len=" << ansilen << endl;
}
wchar len=4 ansi len=7
张三zsw的utf8字节长度=9
229 188 160 228 184 137 122 115 119 转换成byte[]之后
wchar len=5 ansi len=9
本实验的现象:同一个c#字符串"张三zsw",直接以string-->char*转入c++,wcharlen=4而ansilen=7,而在C#中先转成byte[],再以byte[]-->char*,wcharlen=5,andilen=9。通过我们人眼可看到确实是有5个“字符”,通过转换出来的byte可知有9个(229 188 160对应字符'张',228 184 137对应字符'三',
122 115 119分别对应z s w,那这么可以知道将string转成byte[]之后传入c++才是正确的(这么说只能说是因为在C++中将字符串当作宽字符来处理是错误的,如果用 mbsrtowcs (见使用例子)(还有一个例子)将多字节unicode转换成宽字符,则应该与转成byte[]之后再计算字符数的结果是一样的).。
总结:
在c#中将字符串传给C++,如果C++中只是用wchar_t或其指针进行处理,那么最好在c#中将字符串转成byte[]。