C#回调接收UTF8字符串
C# callback receiving UTF8 string
我有一个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);
相关文章:
- MSVC UTF8字符串编码使用了不正确的代码点
- 在 C++ 中将 utf8 wstring 转换为窗口中的字符串
- C++ 检查 UTF8 字符串包含指定的字符
- 将STD :: U8String复制到一个UTF8字符的C风格字符串中
- 使用REGEX以UTF8格式过滤字符串
- 如何使用std :: codecvt_utf8_utf16在没有任何字符串类的情况下转换为UTF8
- 转换一个带有UTF8 WSTRING控制台的装饰的字符串
- 如何转换为C 中的UTF8字符串
- C#回调接收UTF8字符串
- C++将ASII转义的unicode字符串转换为utf8字符串
- 作为utf8字符串的utf16字符串的长度
- UTF8 字符串到整数
- 从服务器响应中解析 UTF8 字符串
- 是一个C++字符串类,我可以用来处理 UTF8 字符串
- 火鸟在“UTF8 字符串转换为 wstring”时崩溃
- 在android NDK jni中加密和解密utf8字符串
- Boost Spirit(X3)符号表产生UTF8字符串
- 在窗口中用UTF8字符串打开文件名
- 用c++将UTF8字符串转换为UTF16字符串
- c++字符串擦除不适用于UTF8字符串,我可以使用什么库