Skip to content

Instantly share code, notes, and snippets.

@xylcbd
Created March 28, 2018 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xylcbd/41c74f1427fc5c3049966156cf6f281d to your computer and use it in GitHub Desktop.
Save xylcbd/41c74f1427fc5c3049966156cf6f281d to your computer and use it in GitHub Desktop.
std::string local_to_utf8(const std::string& src)
{
#if _WIN32
int len = MultiByteToWideChar(CP_ACP, 0, src.c_str(), -1, NULL, 0);
wchar_t* wszUTF16 = new wchar_t[len+1];
memset(wszUTF16, 0, len+1);
MultiByteToWideChar(CP_ACP, 0, src.c_str(), -1, wszUTF16, len);
len = WideCharToMultiByte(CP_UTF8, 0, wszUTF16, -1, NULL, 0, NULL, NULL);
char* szUTF8 = new char[len + 1];
memset(szUTF8, 0, len + 1);
WideCharToMultiByte(CP_UTF8, 0, wszUTF16, -1, szUTF8, len, NULL, NULL);
std::string strTemp = szUTF8;
if (wszUTF16) delete[] wszUTF16;
if (szUTF8) delete[] szUTF8;
return strTemp;
#else
return src;
#endif
}
std::string utf8_to_local(const std::string& src)
{
#if _WIN32
int len = MultiByteToWideChar(CP_UTF8, 0, src.c_str(), -1, NULL, 0);
wchar_t* wszUTF16 = new wchar_t[len+1];
memset(wszUTF16, 0, len * 2 + 2);
MultiByteToWideChar(CP_UTF8, 0, src.c_str(), -1, wszUTF16, len);
len = WideCharToMultiByte(CP_ACP, 0, wszUTF16, -1, NULL, 0, NULL, NULL);
char* szLocal = new char[len + 1];
memset(szLocal, 0, len + 1);
WideCharToMultiByte(CP_ACP, 0, wszUTF16, -1, szLocal, len, NULL, NULL);
std::string strTemp(szLocal);
if (wszUTF16) delete[] wszUTF16;
if (szLocal) delete[] szLocal;
return strTemp;
#else
return src;
#endif
}
std::string wstring_to_utf8(const std::wstring& str)
{
#if _WIN32
int len = WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, NULL, 0, NULL, NULL);
char* szGBK = new char[len + 1];
memset(szGBK, 0, len + 1);
WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, szGBK, len, NULL, NULL);
std::string strTemp(szGBK);
if (szGBK) delete[] szGBK;
return strTemp;
#else
return "[UN-IMPLEMENTED]";
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment