1 c#向c++传送中文字符串
设置:将 字符集 改为 使用多字节字符集
cpp代码:
extern "C"_declspec(dllexport) int input_chn_str(char in_str[])
{cout<<in_str<<endl;return 0;
}
c#代码:
[DllImport("Demo.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
public static extern bool input_chn_str(byte[] in_str);string str = "中国chn123";
int rst = input_chn_str(Encoding.Default.GetBytes(str));
2 C#接收c++返回的中文字符串
cpp代码:
extern "C"_declspec(dllexport) int ProcessChineseString(const char* input, char* output)
{std::string inputString(input);std::string outputString = "输入内容为:" + inputString;strcpy(output, outputString.c_str());return 0;
}
c#代码:
[DllImport("ocr_cpu.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
extern static int ProcessChineseString(IntPtr input1, IntPtr output1);string chineseInput = "你好123abc不不不";
byte[] inputBytes = Encoding.Default.GetBytes(chineseInput);
IntPtr inputPtr = Marshal.AllocHGlobal(inputBytes.Length + 1);
Marshal.Copy(inputBytes, 0, inputPtr, inputBytes.Length);
Marshal.WriteByte(inputPtr, inputBytes.Length, 0); // 添加字符串结束符IntPtr outputPtr = Marshal.AllocHGlobal(1000);
ProcessChineseString(inputPtr, outputPtr);
string outputString = Marshal.PtrToStringAnsi(outputPtr);Console.WriteLine(outputString);Marshal.FreeHGlobal(inputPtr);
Marshal.FreeHGlobal(outputPtr);
如果遇到乱码:
[DllImport("ocr_cpu.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]extern static int infer(IntPtr output);IntPtr outputPtr = Marshal.AllocHGlobal(1000);rst = infer(outputPtr);{int length = 0;//循环查找字符串的长度 while (Marshal.ReadByte(outputPtr + length) != 0){length++;}byte[] strbuf = new byte[length];Marshal.Copy(outputPtr, strbuf, 0, length);// Taken from https://msdn.microsoft.com/it-it/library/system.text.encodinginfo.getencoding(v=vs.110).aspx string message1 = Encoding.UTF8.GetString(strbuf);Console.WriteLine(message1);}