Pregunta

Estoy buscando un método o un fragmento de código para convertir std::string a LPCWSTR

¿Fue útil?

Solución

Gracias por el enlace al artículo de MSDN.Esto es exactamente lo que estaba buscando.

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();

Otros consejos

En realidad, la solución es mucho más fácil que cualquiera de las otras sugerencias:

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

Lo mejor de todo es que es independiente de la plataforma.h2h :)

Si está en un entorno ATL/MFC, puede utilizar la macro de conversión ATL:

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

. . .

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

Luego puede usar unicodeStr como LPCWSTR.La memoria para la cadena Unicode se crea en la pila y se libera, luego se ejecuta el destructor de UnicodeStr.

En lugar de usar std::string, puedes usar std::wstring.

EDITAR:Lo siento, esto no es más explicativo, pero tengo que correr.

Utilice 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();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top