C#回调接收UTF8字符串 我有一个C语言函数,一个回调函数,是用C++编写的Win32 DLL调用的。调用者给了我一个UTF8字符串,但我无法正确接收,所有匈牙利特殊字符都出错了 [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int func_writeLog(string s);

C#回调接收UTF8字符串 我有一个C语言函数,一个回调函数,是用C++编写的Win32 DLL调用的。调用者给了我一个UTF8字符串,但我无法正确接收,所有匈牙利特殊字符都出错了 [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int func_writeLog(string s);,c#,c++,string,utf-8,callback,C#,C++,String,Utf 8,Callback,当我将参数类型更改为IntPtr,并编写代码时,它写得很正确。但我发现这是一个非常缓慢的解决方案: byte[] bb = new byte[1000]; int i = 0; while (true) { byte b = Marshal.ReadByte(pstr, i); bb[i] = b; if (b == 0) break;

当我将参数类型更改为
IntPtr
,并编写代码时,它写得很正确。但我发现这是一个非常缓慢的解决方案:

        byte[] bb = new byte[1000];
        int i = 0;
        while (true)
        {
            byte b = Marshal.ReadByte(pstr, i);
            bb[i] = b;
            if (b == 0) break;
            i++;
        }
        System.Text.UTF8Encoding encodin = new System.Text.UTF8Encoding();
        var sd = encodin.GetString(bb, 0, i);
我尝试将一些属性写入字符串参数,如:

  [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
  public delegate int func_writeLog([In, MarshalAs(UnmanagedType.LPTStr)] string s);

没有人在工作。有什么建议吗?提前谢谢

在纯托管代码中没有合适的方法可以快速执行此操作,它总是需要复制字符串,这非常尴尬,因为您不知道所需的缓冲区大小。您将需要pinvoke一个Windows函数来完成此操作,MultiByteToWideChar()是工作马转换器函数。像这样使用它:

using System.Text;
using System.Runtime.InteropServices;
...
    public static string Utf8PtrToString(IntPtr utf8) {
        int len = MultiByteToWideChar(65001, 0, utf8, -1, null, 0);
        if (len == 0) throw new System.ComponentModel.Win32Exception();
        var buf = new StringBuilder(len);
        len = MultiByteToWideChar(65001, 0, utf8, -1, buf, len);
        return buf.ToString();
    }
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern int MultiByteToWideChar(int codepage, int flags, IntPtr utf8, int utf8len, StringBuilder buffer, int buflen);

@汉斯·帕桑:再次谢谢你,汉斯。似乎没有比这更好的方法了+1.