C#调用C++ 的DLL传送和接收中文字符串

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);
相关推荐
一叶之秋14123 分钟前
告别浅层调用:深入模拟实现STL Stack/Queue/Priority_Queue,知其所以然
c++·stl
弹简特5 分钟前
【Java-阔怕的JVM】JVM
java·开发语言·jvm
2301_780669866 分钟前
UDP通信(一发一收,多发多收)、TCP通信(一发一收,多发多收、同时接收多个客户端的消息)、B/S架构的原理
java·tcp/ip·udp
小冷coding9 分钟前
工作流是什么呢?
java·面试
耶耶耶耶耶~12 分钟前
关于软件开发的一些思考
c++
像少年啦飞驰点、13 分钟前
零基础入门 Redis:从缓存原理到 Spring Boot 集成实战
java·spring boot·redis·缓存·编程入门
量子炒饭大师14 分钟前
【C++入门】Cyber骇客构造器的核心六元组 —— 【类的默认成员函数】明明没写构造函数也能跑?保姆级带你掌握六大类的默认成员函数(上:函数篇)
开发语言·c++·dubbo·默认成员函数
虾说羊16 分钟前
Springboot中配置欢迎页的方式
java·spring boot·后端
qq_124987075316 分钟前
基于Spring Boot的长春美食推荐管理系统的设计与实现(源码+论文+部署+安装)
java·前端·spring boot·后端·毕业设计·美食·计算机毕业设计
charlie11451419123 分钟前
嵌入式C++开发——RAII 在驱动 / 外设管理中的应用
开发语言·c++·笔记·嵌入式开发·工程实践