Last active
June 15, 2024 10:48
MFC Convert CString encoding between UTF-8 and UTF-16
This file contains hidden or 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; | |
} |
Thanks you! This helped me toconvert libmaxminddb's utf8 std::string to proper CString.
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