1 c#向c++传送中文字符串
设置:将 字符集 改为 使用多字节字符集
cpp代码:
cpp
extern "C"_declspec(dllexport) int input_chn_str(char in_str[])
{
cout<<in_str<<endl;
return 0;
}
c#代码:
csharp
[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代码:
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#代码:
csharp
[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);