tags:

views:

8832

answers:

5

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

A: 

Instead of using a std::string, you could use a std::wstring.

EDIT: Sorry this is not more explanatory, but I have to run.

Use std::wstring::c_str()

Ed Swangren
+4  A: 

A simple google search yields:

MSDN: Convert std::string to LPCWSTR (best way in c++)

aib
Bad link. The latest one is http://social.msdn.microsoft.com/Forums/en/Vsexpressvc/thread/0f749fd8-8a43-4580-b54b-fbf964d68375
dwj
A: 

If you are in an ATL/MFC environment, You can use the ATL conversion macro:

#include <atlbase.h>
#include <atlconv.h>

. . .

string myStr("My string");
CA2W unicodeStr(myStr);

You can then use unicodeStr as an LPCWSTR. The memory for the unicode string is created on the stack and released then the destructor for unicodeStr executes.

17 of 26
+9  A: 

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();
Toran Billups
(Found this question browsing randomly; it's been a long time since I did C++.) So the standard library doesn't have std::string -> std::wstring conversion? That seems weird; is there a good reason?
Domenic
If you use std::vector<wchar_t> to create storage for buf, then if anything throws an exception your temporary buffer will be freed.
Jason Harrison
+2  A: 

@Chris Fournier:

delete pszWideCharStr; // Free the buffer

Why do you regard freeing the buffer as optional (it should free the buffer even if the second call to MultiByteToWideChar fails), and why do you corrupt your free store (you should use delete[] for arrays)?

DrPizza