【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。

相关推荐
AAA大运重卡何师傅(专跑国道)8 小时前
【无标题】
开发语言·c#
xiaoshuaishuai817 小时前
C# AvaloniaUI ProgressBar用法
开发语言·c#
wearegogog12321 小时前
基于C#的电机监控上位机(串口通信+实时波形)
开发语言·c#
△曉風殘月〆21 小时前
C#如何Hook托管函数
c#·hook
雪豹阿伟21 小时前
18.C# —— 三层结构 + 接口架构实战(UI+Model+DAL+IDAL)
c#·上位机
雪豹阿伟1 天前
17.C# —— 事件
c#·上位机
weixin_428005301 天前
C#调用 AI学习从0开始-第2阶段(Function Calling+工具调用智能体)-第9天实战
人工智能·学习·ai·c#·functioncalling
FuckPatience1 天前
C# 继承中的使用new的陷阱,和abstract /virtual 的不同
开发语言·c#
z落落1 天前
C# 索引器 this[]
开发语言·c#
csdn_aspnet1 天前
C# List 移除某个属性值中最大的值
开发语言·c#·list