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);
相关推荐
4Forsee7 小时前
【Android】View 事件分发机制与源码解析
android·java·前端
画个逗号给明天"7 小时前
C++十大排序算法
数据结构·c++·排序算法
仰泳的熊猫7 小时前
LeetCode:268. 丢失的数字
数据结构·c++·算法·leetcode
葛小白17 小时前
C#数据类型:List
开发语言·c#
刘一说8 小时前
Spring Boot 主程序入口与启动流程深度解析:从 `@SpringBootApplication` 到应用就绪
java·spring boot·后端
小龙报8 小时前
《算法通关指南数据结构和算法篇(3)--- 栈和stack》
开发语言·数据结构·c++·算法·创业创新·学习方法·visual studio
eguid_18 小时前
【从零开始开发远程桌面连接控制工具】01-项目概述与架构设计
java·远程连接·远程控制·远程桌面·vnc·teamviewer
一 乐8 小时前
车辆管理|校园车辆信息|基于SprinBoot+vue的校园车辆管理系统(源码+数据库+文档)
java·前端·数据库·vue.js·论文·毕设·车辆管理
m0_748233648 小时前
C++小协程栈和临时变量及作用域的栈溢出问题分析
开发语言·c++
百锦再8 小时前
Python、Java与Go:AI大模型时代的语言抉择
java·前端·vue.js·人工智能·python·go·1024程序员节