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);
相关推荐
我命由我123451 分钟前
Android 消息机制 - Looper(Looper 静态方法、Looper 静态方法注意事项、Looper 实例方法、Looper 实例方法注意事项)
android·java·android studio·安卓·android jetpack·android-studio·android runtime
Hard but lovely4 分钟前
linux: pthread库---posix线程创建使用接口&&状态
linux·开发语言·c++
月明长歌4 分钟前
【码道初阶】Leetcode138:随机链表的复制:用 HashMap 做深拷贝的标准解法
java·数据结构·算法·leetcode·链表·哈希算法
世洋Blog5 分钟前
Unity编辑器基础
unity·c#·编辑器·游戏引擎
.简.简.单.单.7 分钟前
Design Patterns In Modern C++ 中文版翻译 第八章 组合
java·c++·设计模式
喜欢吃燃面14 分钟前
算法竞赛中的数据结构:图
开发语言·数据结构·c++·学习·算法
钰fly15 分钟前
C#索引器 接口
c#
哈市雪花16 分钟前
记录一次cmake无法正确使用vcpkg的问题
开发语言·c++
SunnyDays101118 分钟前
使用 C# 隐藏 Excel 工作表 (单表格、批量处理 与 超级隐藏)
c#·隐藏excel工作表
七夜zippoe18 分钟前
Spring MVC请求处理流程源码分析与DispatcherServlet核心逻辑
java·spring·mvc·过滤器·拦截器