Domanda

Sto cercando un metodo, o un frammento di codice per la conversione di std::string per LPCWSTR

È stato utile?

Soluzione

Grazie per il link all'articolo di MSDN.Questo è esattamente quello che stavo cercando.

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

Altri suggerimenti

La soluzione è in realtà molto più semplice rispetto a qualsiasi altri suggerimenti:

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

Migliore di tutti, è indipendente dalla piattaforma.h2h :)

Se siete in un ATL/MFC ambiente, È possibile utilizzare l'ATL di conversione macro:

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

. . .

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

È quindi possibile utilizzare unicodeStr come LPCWSTR.La memoria per la stringa unicode è creata in pila e rilasciato poi il distruttore per unicodeStr esegue.

Invece di usare std::string, si potrebbe utilizzare un std::wstring.

EDIT:Ci dispiace, questo non è più esplicativo, ma devo scappare.

Usare std::wstring::c_str()

LPCWSTR lpcwName=std::wstring(strname.begin(), strname.fine()).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();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top