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
2008-08-26 01:52:42
Bad link. The latest one is http://social.msdn.microsoft.com/Forums/en/Vsexpressvc/thread/0f749fd8-8a43-4580-b54b-fbf964d68375
dwj
2009-11-16 19:52:46
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
2008-08-26 02:30:25
+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
2008-08-26 02:36:58
(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
2009-07-29 08:41:11
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
2010-01-06 19:01:51
+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
2008-08-26 16:42:45