【C#】解析char型指针所指向的内容

C#解析char型指针的内存块

1、背景

在c++代码中定义了一个功能函数,这个功能函数会将计算的结果写入一个字符串型的数组中output,然后c#会调用c++导出的dll中的接口函数,然后获取这个output并解析成string类型。

2、实例

c++:

cpp 复制代码
CPPDLL_API int Function( char*& output)

c#:

csharp 复制代码
[DllImport(@"Project1.dll", EntryPoint = "Function",CharSet = CharSet.Auto)]
public static extern int Function(ref IntPtr output);

IntPtr ptr = IntPtr.Zero;
int isok = Function(ref ptr);

// -> Unicode
byte[] bytes = System.Text.Encoding.Unicode.GetBytes(Marshal.PtrToStringUni(ptr));
// -> UTF8
string dec = System.Text.Encoding.UTF8.GetString(bytes);

错误代码:

csharp 复制代码
string dec = Marshal.PtrToStringAnsi(ptr);

得到的dec是乱码,查询发现是因为内存编码是UTF8,Marshal不支持UTF转换,所以必须先转成Unicode再转成UTF8。

相关推荐
小白不白11123 分钟前
C# WinForm 与 VP 二次开发
开发语言·c#
SunnyDays10111 小时前
如何使用 C# 自动调整 Excel 行高和列宽
开发语言·c#·excel
itgather2 小时前
OfficeExcel — Word / Excel DLL 验证台功能介绍
c#·word·excel
云中小生2 小时前
Scrutor:.NET 依赖注入自动化的优雅实现
c#·.net
郝亚军2 小时前
Visual Studio 2022项目中的.sln是什么?
c++·c#·visual studio
jghhh012 小时前
C# 图片水印工具(支持9个位置)
数据库·microsoft·c#
咸鱼翻身小阿橙3 小时前
C# WinForms 控件学习项目
开发语言·学习·c#
JaydenAI3 小时前
[MAF预定义Agent中间件-03]FunctionInvocationDelegatingAgent:将AOP引入函数调用
ai·c#·agent·aop·maf
.NET修仙日记3 小时前
.NET 领域驱动设计:用户角色更新如何从应用服务落地到领域实体(代码拆解)
c#·.net·领域驱动设计·微软技术·角色设计
.NET修仙日记4 小时前
Scrutor:.NET 依赖注入自动化的优雅实现
c#·.net·.net core·微软技术·依赖注入·scrutor