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

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

  • 1、背景
  • 2、实例

    1、背景

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

    2、实例

    c++:

    CPPDLL_API int Function( char*& output)
    

    c#:

    [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);
    

    错误代码:

    string dec = Marshal.PtrToStringAnsi(ptr);
    

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