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);
相关推荐
Re.不晚3 分钟前
JAVA进阶之路——无奖问答挑战3
java·开发语言
代码游侠4 分钟前
C语言核心概念复习——C语言基础阶段
linux·开发语言·c++·学习
㓗冽13 分钟前
60题之内难题分析
开发语言·c++·算法
bugcome_com15 分钟前
C# 程序结构详解:从 Hello World 开始
c#
rainbow688922 分钟前
C++开源库dxflib解析DXF文件实战
开发语言·c++·开源
不倒翁玩偶22 分钟前
IDEA导入新的SpringBoot项目没有启动按钮
java·spring boot·intellij-idea
John_ToDebug25 分钟前
Chromium安全架构深度解析:从悬空指针检测到内存安全防御体系
c++·chrome
D_evil__33 分钟前
【Effective Modern C++】第五章 右值引用、移动语义和完美转发:24. 区分万能引用和右值引用
c++
小小小米粒37 分钟前
Maven Tools
java
蜡笔小马1 小时前
10.Boost.Geometry R-tree 空间索引详解
开发语言·c++·算法·r-tree