Instantly share code, notes, and snippets.

Embed
What would you like to do?
WinRT(C++/CX) UTF8_To_Std_Str and UTF8_To_Managed_Str
#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