Windows 核心 API 提供的兩個字串轉換函數,常因代碼頁參數設定錯誤導致亂碼。本文依據《Windows 核心程式設計》整理正確用法,並提供可直接使用的 C++ 封裝函數。
CodePage 參數:指定轉換後多位元組字串所屬的代碼頁。CodePage 參數:指定來源多位元組字串所屬的代碼頁。CP_ACP (系統預設 ANSI)、CP_UTF8 (UTF-8)。wstring ANSIToUnicode(const string& str) {
int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);
wchar_t* buf = new wchar_t[len + 1];
memset(buf, 0, (len + 1) * sizeof(wchar_t));
MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, buf, len);
wstring ret(buf);
delete[] buf;
return ret;
}
string UnicodeToANSI(const wstring& str) {
int len = WideCharToMultiByte(CP_ACP, 0, str.c_str(), -1, NULL, 0, NULL, NULL);
char* buf = new char[len + 1];
memset(buf, 0, len + 1);
WideCharToMultiByte(CP_ACP, 0, str.c_str(), -1, buf, len, NULL, NULL);
string ret(buf);
delete[] buf;
return ret;
}
wstring UTF8ToUnicode(const string& str) {
int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
wchar_t* buf = new wchar_t[len + 1];
memset(buf, 0, (len + 1) * sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, buf, len);
wstring ret(buf);
delete[] buf;
return ret;
}
string UnicodeToUTF8(const wstring& str) {
int len = WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, NULL, 0, NULL, NULL);
char* buf = new char[len + 1];
memset(buf, 0, len + 1);
WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, buf, len, NULL, NULL);
string ret(buf);
delete[] buf;
return ret;
}
lpWideCharStr / lpMultiByteStr 傳 -1 表示以 null 結尾字串處理。