字串編碼亂碼問題困擾許多 Windows 開發者。下面提供兩個可直接使用的 C++ 函式,分別處理 UTF-8 ↔ Unicode(UTF-16)轉換,基於 Windows API MultiByteToWideChar 與 WideCharToMultiByte 實作。
inline std::wstring utf8ToUnicode(const std::string& str)
{
// 先查詢所需緩衝區大小
size_t wcsLen = ::MultiByteToWideChar(CP_UTF8, 0, str.c_str(),
static_cast<int>(str.length()),
nullptr, 0);
if (wcsLen == 0) return L"";
// 配置記憶體(+1 給結尾 null)
std::vector<wchar_t> wszString(wcsLen + 1, 0);
// 實際轉換
::MultiByteToWideChar(CP_UTF8, 0, str.c_str(),
static_cast<int>(str.length()),
wszString.data(), static_cast<int>(wcsLen));
return std::wstring(wszString.data());
}
inline std::string unicodeToUtf8(const std::wstring& wstr)
{
int len = ::WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(),
static_cast<int>(wstr.length()),
nullptr, 0, nullptr, nullptr);
if (len == 0) return "";
std::vector<char> szUtf8(len + 1, 0);
::WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(),
static_cast<int>(wstr.length()),
szUtf8.data(), len, nullptr, nullptr);
return std::string(szUtf8.data());
}
std::vector 取代手動 new/delete,避免記憶體洩漏,符合 RAII 原則。nullptr 取得所需緩衝區大小,第二次實際轉換。CP_UTF8 明確指定代碼頁,避免系統預設值造成不可預期行為。delete wszString 應為 delete[] wszString,現代化寫法直接用容器更安全。來源:ccSec | cc@insight-labs.org