views:

157

answers:

1

I based these two conversion functions and an answer on StackOverflow, but converting back-and-forth doesn't work:

std::wstring    MultiByteToWideString(const char* szSrc)  
{
 unsigned int iSizeOfStr = MultiByteToWideChar(CP_ACP, 0, szSrc, -1, NULL, 0);  
 wchar_t* wszTgt = new wchar_t[iSizeOfStr];  
 if(!wszTgt)    assert(0);  
  MultiByteToWideChar(CP_ACP, 0, szSrc, -1, wszTgt, iSizeOfStr);  
 std::wstring wstr(wszTgt);  
delete(wszTgt);  
return(wstr);  
}

std::string WideStringToMultiByte(const wchar_t* wszSrc)  
{  
    int iSizeOfStr = WideCharToMultiByte(CP_ACP, 0, wszSrc, -1, NULL, 0, NULL, NULL);  
    char* szTgt = new char[iSizeOfStr];  
    if(!szTgt)  return(NULL);  
    WideCharToMultiByte(CP_ACP, 0, wszSrc, -1, szTgt, iSizeOfStr, NULL, NULL);  
    std::string str(szTgt);  
    delete(szTgt);  
    return(str);  
}  

[...]   

// はてなブ in utf-16
wchar_t wTestUTF16[] = L"\u306f\u3066\u306a\u30d6\u306f\u306f";

// shows the text correctly  
::MessageBoxW(NULL, wTestUTF16, L"Message", MB_OK);  

// convert to UTF8, and back to UTF-16  
std::string strUTF8 = WideStringToMultiByte(wTestUTF16);  
std::wstring wstrUTF16 = MultiByteToWideString(strUTF8.c_str());  

// this doesn't show the proper text.  Should be same as first message box  
::MessageBoxW(NULL, wstrUTF16.c_str(), L"Message", MB_OK);
+2  A: 

Check the docs for WideCharToMultiByte(). CP_ACP converts using the current system code page. That's a very lossy one. You want CP_UTF8.

Hans Passant
Works fine if I change all four CP_ACP to CP_UTF8... Thanks!
Martin
That only works if the char* data is always UTF-8. If you need to convert data to/from other Ansi languages, then you have to use the correct codepage each time.
Remy Lebeau - TeamB