C#回调接收UTF8字符串

标签 c# c++ string utf-8 callback

我有一个 C# 函数,一个回调,从用 C++ 编写的 Win32 DLL 调用。来电者给了我一个UTF8字符串,但我无法正常接收,所有匈牙利语特殊字符都出错了。

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int func_writeLog(string s);

当我将参数类型更改为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);

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

最佳答案

在纯托管代码中没有像样的方法可以快速执行此操作,它总是需要复制字符串,这很尴尬,因为您不知道所需的缓冲区大小。您需要调用一个 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);

关于C#回调接收UTF8字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12194828/

相关文章:

c# - 发送聊天消息

c# - JSON反序列化——String自动转为Int

c# - 初学者角色扮演游戏高效的 ASCII map 和运动系统

c++ - 如何将尾随返回类型与模板化类成员一起使用

c++ - 如何连接两个字符串以用作初始化列表中的参数?

c++ - glDrawElements 错误 : nvoglv32. dll OpenGL

r - 如何在 R 中提取函数(写为字符串)中的参数?

string - 通过字符串发送二进制数据包有优势吗?

php - 如何在php中通过字符串将 "reference"制作成数组

c# - 如何处理System.DBNull?