2017-02-28 148 views
0

a。C/C#Marshal.PtrToStringAnsi中文亂碼

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

,中國顯示器,但是字符串的長度返回。

我需要幫助!

+0

誰給你的字符串?一個C函數? 'strbuf'的內容是什麼?預期的字符串? – xanatos

+0

[UnmanagedFunctionPointer(CallingConvention.StdCall)] 公共委託無效WriteToConsoleCallback(IntPtr的STR)「」 SetRecvDataCallback setRecvDataCallback = (SetRecvDataCallback)Marshal.GetDelegateForFunctionPointer(hapi2的typeof(SetRecvDataCallback)); callback = new WriteToConsoleCallback(onMessage); setRecvDataCallback(callback); – aiwll

+0

它們是非公共圖書館的功能...嘗試給我們提供'strbuf'(十六進制)和需要的文本內容(如果你知道的話) – xanatos

回答

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