Como converter std::string para LPCWSTR em C++ (Unicode)
Pergunta
Estou procurando um método ou um trecho de código para converter std::string em LPCWSTR
Solução
Obrigado pelo link para o artigo do MSDN.Isso é exatamente o que eu estava procurando.
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();
Outras dicas
A solução é na verdade muito mais fácil do que qualquer uma das outras sugestões:
std::wstring stemp = std::wstring(s.begin(), s.end());
LPCWSTR sw = stemp.c_str();
O melhor de tudo é que é independente de plataforma.h2h :)
Se você estiver em um ambiente ATL/MFC, poderá usar a macro de conversão ATL:
#include <atlbase.h>
#include <atlconv.h>
. . .
string myStr("My string");
CA2W unicodeStr(myStr);
Você pode então usar unicodeStr como LPCWSTR.A memória para a string unicode é criada na pilha e liberada, em seguida, o destruidor de unicodeStr é executado.
Em vez de usar std::string, você pode usar std::wstring.
EDITAR:Desculpe, isso não é mais explicativo, mas tenho que correr.
Usar std::wstring::c_str()
LPCWSTR lpcwName=std::wstring(strname.begin(), strname.end()).c_str()
string myMessage="helloworld";
int len;
int slength = (int)myMessage.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, myMessage.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, myMessage.c_str(), slength, buf, len);
std::wstring r(buf);
std::wstring stemp = r.C_str();
LPCWSTR result = stemp.c_str();