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);
相关推荐
努力学习的小廉几秒前
【C++】 —— 笔试刷题day_21
开发语言·c++·算法
YuforiaCode1 分钟前
第十四届蓝桥杯 2023 C/C++组 冶炼金属
c语言·c++·蓝桥杯
写bug写bug12 分钟前
Java并发编程:什么是线程组?它有什么作用?
java·后端
Andya_net19 分钟前
SpringBoot | 构建客户树及其关联关系的设计思路和实践Demo
java·spring boot·后端
申城异乡人21 分钟前
【踩坑系列】使用Comparator.comparing对中文字符串排序结果不对
java
风,停下22 分钟前
C#基于Sunnyui框架和MVC模式实现用户登录管理
设计模式·c#·mvc
Brian_Lucky23 分钟前
在 macOS 上合并 IntelliJ IDEA 的项目窗口
java·macos·intellij-idea
钢铁男儿23 分钟前
C# 实战_RichTextBox选中某一行条目高亮,离开恢复
开发语言·c#
周杰伦_Jay25 分钟前
continue插件实现IDEA接入本地离线部署的deepseek等大模型
java·数据结构·ide·人工智能·算法·数据挖掘·intellij-idea