调用接口说明:
MultiByteToWideChar function (stringapiset.h) - Win32 apps | Microsoft Learn
WideCharToMultiByte function (stringapiset.h) - Win32 apps | Microsoft Learn
代码示例:
#include <windows.h>
#include <string>
#include <stdio.h>
#include <iostream>
bool UTF8ToWide(std::wstring& wstr, const std::string& utf8)
{
int size = MultiByteToWideChar(CP_UTF8, NULL, utf8.c_str(), utf8.size(), NULL, NULL);
wchar_t* wide = new wchar_t[size];
wmemset(wide, L'\0', size);
size = MultiByteToWideChar(CP_UTF8, NULL, utf8.c_str(), utf8.size(), wide, size);
wstr.assign(wide, size);
delete[] wide;
wide = NULL;
return true;
}
bool ANSIToWide(std::wstring& wstr, const std::string& ansi)
{
int size = MultiByteToWideChar(CP_ACP, NULL, ansi.c_str(), ansi.size(), NULL, NULL);
wchar_t* wide = new wchar_t[size];
wmemset(wide, L'\0', size);
size = MultiByteToWideChar(CP_ACP, NULL, ansi.c_str(), ansi.size(), wide, size);
wstr.assign(wide, size);
delete[] wide;
wide = NULL;
return true;
}
bool WideToUTF8(std::string& utf8, const std::wstring& wstr)
{
int size = WideCharToMultiByte(CP_UTF8, NULL, wstr.c_str(), wstr.size(), NULL, NULL, NULL, NULL);
char* utf8_buf = new char[size];
memset(utf8_buf, '\0', size);
size = WideCharToMultiByte(CP_UTF8, NULL, wstr.c_str(), wstr.size(), utf8_buf, size, NULL, NULL);
utf8.assign(utf8_buf, size);
delete[] utf8_buf;
utf8_buf = NULL;
return true;
}
bool WideToANSI(std::string& ansi, const std::wstring& wstr)
{
int size = WideCharToMultiByte(CP_ACP, NULL, wstr.c_str(), wstr.size(), NULL, NULL, NULL, NULL);
char* ansi_buf = new char[size];
memset(ansi_buf, '\0', size);
size = WideCharToMultiByte(CP_ACP, NULL, wstr.c_str(), wstr.size(), ansi_buf, size, NULL, NULL);
ansi.assign(ansi_buf, size);
delete[] ansi_buf;
ansi_buf = NULL;
return true;
}
bool ANSIToUTF8(std::string& utf8, const std::string& ansi)
{
std::wstring wstr;
ANSIToWide(wstr, ansi);
WideToUTF8(utf8, wstr);
return true;
}
bool UTF8ToANSI(std::string& ansi, const std::string& utf8)
{
std::wstring wstr;
UTF8ToWide(wstr, utf8);
WideToUTF8(ansi, wstr);
return true;
}
int main()
{
std::string ansi = "中国"; // GB2312
std::string utf8;
std::wstring wstr_by_ansi;
std::wstring wstr_by_utf8;
ANSIToUTF8(utf8, ansi);
ANSIToWide(wstr_by_ansi, ansi);
UTF8ToWide(wstr_by_utf8, utf8);
}