首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> .NET 實例教學

WideCharToMultiByte 與 MultiByteToWideChar 正確用法詳解

     編輯:.NET 實例教學

Windows 核心 API 提供的兩個字串轉換函數,常因代碼頁參數設定錯誤導致亂碼。本文依據《Windows 核心程式設計》整理正確用法,並提供可直接使用的 C++ 封裝函數。

核心概念

  • WideCharToMultiByte 的 CodePage 參數:指定轉換後多位元組字串所屬的代碼頁。
  • MultiByteToWideChar 的 CodePage 參數:指定來源多位元組字串所屬的代碼頁。
  • 常用代碼頁:CP_ACP (系統預設 ANSI)、CP_UTF8 (UTF-8)。

四種常見轉換場景

1. ANSI → Unicode (UTF-16)

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

2. Unicode → ANSI

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

3. UTF-8 → Unicode

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

4. Unicode → UTF-8

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 結尾字串處理。
  • 記得釋放動態配置的緩衝區,避免記憶體洩漏。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved