Last active
January 3, 2023 09:54
-
-
Save superlucky8848/893144633f189e5bc233f1a15e4610ed to your computer and use it in GitHub Desktop.
MFC Convert CString encoding between UTF-8 and UTF-16
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static CStringA UTF16_UTF8(const CStringW& utf16) | |
{ | |
if (utf16.IsEmpty()) return ""; | |
CStringA utf8; | |
int cc = 0; | |
if ((cc = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, NULL, 0, 0, 0) - 1) > 0) | |
{ | |
char * buf = utf8.GetBuffer(cc); | |
if (buf) WideCharToMultiByte(CP_UTF8, 0, utf16, -1, buf, cc, 0, 0); | |
utf8.ReleaseBuffer(); | |
} | |
return utf8; | |
} | |
static CStringW UTF8_UTF16(const CStringA& utf8) | |
{ | |
if (utf8.IsEmpty()) return L""; | |
CStringW utf16; | |
int cc = 0; | |
if ((cc = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0) - 1) > 0) | |
{ | |
wchar_t *buf = utf16.GetBuffer(cc); | |
if (buf) MultiByteToWideChar(CP_UTF8, 0, utf8, -1, buf, cc); | |
utf16.ReleaseBuffer(); | |
} | |
return utf16; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is no need to do encoding conversion, because CString uses UNICODE to represent strings internally