Skip to content

Instantly share code, notes, and snippets.

Revisions

  1. @deurell deurell created this gist May 10, 2015.
    45 changes: 45 additions & 0 deletions gistfile1.cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    std::wstring StringConverter::StringToWideString(const std::string& s) {
    int len = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), s.length(), NULL, 0);
    std::wstring ws(L"", len);
    wchar_t* pWSBuf = const_cast<wchar_t*>(ws.c_str());
    MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, pWSBuf, len);
    return ws;
    }

    std::string StringConverter::WideStringToString(const std::wstring& ws) {
    int len = WideCharToMultiByte(CP_UTF8, 0, ws.c_str(), ws.length(), 0, 0, NULL, NULL);
    std::string r("", len);
    char* pRBuf = const_cast<char*>(r.c_str());
    WideCharToMultiByte(CP_UTF8, 0, ws.c_str(), ws.length(), pRBuf, len, NULL, NULL);
    return r;
    }

    Platform::String^ StringConverter::LPSTRToPlatformString(const char* lpstr) {
    if (lpstr == nullptr || strlen(lpstr) == 0)
    return ref new Platform::String();

    int len = MultiByteToWideChar(CP_UTF8, 0, lpstr, strlen(lpstr), NULL, 0);
    auto ps = ref new Platform::String(L"", len);
    wchar_t* pPSBuf = const_cast<wchar_t*>(ps->Data());
    MultiByteToWideChar(CP_UTF8, 0, lpstr, -1, pPSBuf, len);
    return ps;
    }

    Platform::String^ StringConverter::StringToPlatformString(const std::string& s) {
    if (s.empty())
    return ref new Platform::String();

    int len = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), s.length(), NULL, 0);
    auto ps = ref new Platform::String(L"", len);
    wchar_t* pPSBuf = const_cast<wchar_t*>(ps->Data());
    MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, pPSBuf, len);
    return ps;
    }

    std::string StringConverter::PlatformStringToString(Platform::String^ ps) {
    int len = WideCharToMultiByte(CP_UTF8, 0, ps->Data(), ps->Length(), 0, 0, NULL, NULL);
    std::string r("", len);
    char* pRBuf = const_cast<char*>(r.c_str());
    WideCharToMultiByte(CP_UTF8, 0, ps->Data(), ps->Length(), pRBuf, len, NULL, NULL);
    return r;
    }