C / C#Marshal.PtrToStringAnsi中文乱码

时间:2017-02-28 08:07:39

标签: c# c

一个。

static void onMessage(IntPtr str)
{
   string message = Marshal.PtrToStringAnsi(str);
    Console.Write(message);
} 

,它的返回中文乱码。

public static void onMessage(IntPtr str)

    {
        int nAnsiLength = Marshal.PtrToStringAnsi(str).Length;
        int nUniLength = Marshal.PtrToStringUni(str).Length;
        int nMaxLength = (nAnsiLength > nUniLength) ? nAnsiLength : nUniLength;
        int length = 0;//循环查找字符串的长度
        for (int i = 0; i < nAnsiLength; i++)
        {
            byte[] strbuf1 = new byte[1];
            Marshal.Copy(str + i, strbuf1, 0, 1);
            if (strbuf1[0] == 0)
            {
                break;
            }
            length++;
        }

        byte[] strbuf = new byte[length];
        Marshal.Copy(str, strbuf, 0, length);

       string message = System.Text.UTF8Encoding.UTF8.GetString(strbuf);
} 

,中文显示,但返回的字符串长度。

我需要帮助!

1 个答案:

答案 0 :(得分:0)

这里有各种中文代码页...尝试一下看起来符合您的期望。我甚至简化了将IntPtr缓冲区复制到byte[]缓冲区的代码。

public static void onMessage(IntPtr str) {
    int length = 0;//循环查找字符串的长度

    while (Marshal.ReadByte(str + length) != 0) {
        length++;
    }

    byte[] strbuf = new byte[length];
    Marshal.Copy(str, strbuf, 0, length);

    // Taken from https://msdn.microsoft.com/it-it/library/system.text.encodinginfo.getencoding(v=vs.110).aspx
    string message1 = Encoding.UTF8.GetString(strbuf);
    string message2 = Encoding.GetEncoding(54936).GetString(strbuf);
    string message3 = Encoding.GetEncoding(936).GetString(strbuf);
    string message4 = Encoding.GetEncoding(950).GetString(strbuf);
    string message5 = Encoding.GetEncoding(10002).GetString(strbuf);
    string message6 = Encoding.GetEncoding(10008).GetString(strbuf);
    string message7 = Encoding.GetEncoding(20000).GetString(strbuf);
    string message8 = Encoding.GetEncoding(20002).GetString(strbuf);
    string message9 = Encoding.GetEncoding(20936).GetString(strbuf);
    string message10 = Encoding.GetEncoding(50227).GetString(strbuf);
    string message11 = Encoding.GetEncoding(51936).GetString(strbuf);
    string message12 = Encoding.GetEncoding(52936).GetString(strbuf);
}