How to convert std::string to LPCWSTR in C++ (Unicode)


I'm looking for a method, or a code snippet for converting std::string to LPCWSTR

8/27/2008 2:32:44 PM

Accepted Answer

Thanks for the link to the MSDN article. This is exactly what I was looking for.

std::wstring s2ws(const std::string& s)
    int len;
    int slength = (int)s.length() + 1;
    len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); 
    wchar_t* buf = new wchar_t[len];
    MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
    std::wstring r(buf);
    delete[] buf;
    return r;

std::wstring stemp = s2ws(myString);
LPCWSTR result = stemp.c_str();
8/26/2008 2:36:58 AM

The solution is actually a lot easier than any of the other suggestions:

std::wstring stemp = std::wstring(s.begin(), s.end());
LPCWSTR sw = stemp.c_str();

Best of all, it's platform independent. h2h :)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow