這篇早早就打算放上來的說…終於說服我自己別那麼墮落了O_O"
參考來源一樣在最底下^^
OK~
先看看兩者差別,第三項為代表編碼
短字元、8bit、ANSI
寬字元、16bit、UNICODE
先準備寬窄字元字串
char cStr[] = "這是窄字元字串!";
wchar_t wStr[] = L"寬字元、寬字元!";
在轉換之前,需要一個緩衝區去接受結果
首先要知道字串轉換後所需的長度,API提供了一個簡單的函式來查詢
int iLen = MultiByteToWideChar( CP_ACP, 0, cStr, -1, NULL, 0 );
int iLen = WideCharToMultiByte( CP_ACP, 0, wStr, -1, NULL, 0, NULL, FALSE );
如同字面上所表示的,這就是用來轉換用的函式
只要將第4個參數設為 -1 ,就會回傳轉換後的寬窄字元長度
所以,可以向系統索取記憶體來用啦!
wchar_t* lpwStr = new wchar_t[iLen];
char* lpcStr = new char[iLen];
接著就可以開始轉換了!
MultiByteToWideChar( CP_ACP, 0, cStr, -1, lpwStr, iLen );
WideCharToMultiByte( CP_ACP, 0, wStr, -1, NULL, 0, lpcStr, iLen );
OK!這樣緩衝區的東西就可以用了!
順便看一下MSDN裡兩個函式的說明
int MultiByteToWideChar(
UINT CodePage, // code page
DWORD dwFlags, // character-type options
LPCSTR lpMultiByteStr, // string to map
int cbMultiByte, // number of bytes in string
LPWSTR lpWideCharStr, // wide-character buffer
int cchWideChar // size of buffer
);
int WideCharToMultiByte(
UINT CodePage, // code page
DWORD dwFlags, // performance and mapping flags
LPCWSTR lpWideCharStr, // wide-character string
int cchWideChar, // number of chars in string.
LPSTR lpMultiByteStr, // buffer for new string
int cbMultiByte, // size of buffer
LPCSTR lpDefaultChar, // default for unmappable chars
LPBOOL lpUsedDefaultChar // set when default char used
);
其中共有的 CodePage 是個很重要的東西…
目前看到的文章,有的直接指定代碼(例如:936→簡中、950→繁中之類的)
或者都只用 CP_ACP ,也就是 ANSI code page …
總之…
我不知道怎麼用 囧
不過目前都還沒出問題…就請高人來為我解釋了
有錯誤記得說一下嘿!!