Last active
September 18, 2018 09:40
-
-
Save huihut/8f75e2332e05673ff7e1248ad5e85339 to your computer and use it in GitHub Desktop.
WinRT(C++/CX) UTF8_To_Std_Str and UTF8_To_Managed_Str
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
#include <string> | |
#include <Windows.h> | |
std::string UTF8_To_Std_Str(const std::string & str) | |
{ | |
int nwLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0); | |
wchar_t* pwBuf = new wchar_t[nwLen + 1]; | |
memset(pwBuf, 0, nwLen * 2 + 2); | |
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), pwBuf, nwLen); | |
int nLen = WideCharToMultiByte(CP_ACP, 0, pwBuf, -1, NULL, NULL, NULL, NULL); | |
char* pBuf = new char[nLen + 1]; | |
memset(pBuf, 0, nLen + 1); | |
WideCharToMultiByte(CP_ACP, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL); | |
std::string retStr = pBuf; | |
delete[] pBuf; | |
delete[] pwBuf; | |
pBuf = NULL; | |
pwBuf = NULL; | |
return retStr; | |
} | |
Platform::String^ UTF8_To_Managed_Str(const std::string & str) | |
{ | |
int nwLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0); | |
wchar_t* pwBuf = new wchar_t[nwLen + 1]; | |
memset(pwBuf, 0, nwLen * 2 + 2); | |
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), pwBuf, nwLen); | |
Platform::String^ pStr = ref new Platform::String(pwBuf); | |
delete[] pwBuf; | |
pwBuf = NULL; | |
return pStr; | |
} | |
Platform::String^ UTF8_To_Managed_Str(const std::string & str) | |
{ | |
int size = MultiByteToWideChar(CP_UTF8, MB_COMPOSITE, str.c_str(), str.length(), nullptr, 0); | |
std::wstring utf16_str(size, '\0'); | |
MultiByteToWideChar(CP_UTF8, MB_COMPOSITE, str.c_str(), str.length(), &utf16_str[0], size); | |
Platform::String^ pStr = ref new Platform::String(utf16_str.c_str()); | |
return pStr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment