Question

Je recherche une méthode ou un extrait de code pour convertir std :: string en LPCWSTR

Était-ce utile?

La solution

Merci pour le lien vers l'article MSDN.Ceci est exactement ce que je cherchais.

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

Autres conseils

La solution est en fait beaucoup plus simple que toutes les autres suggestions :

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

Mieux encore, il est indépendant de la plateforme.h2h :)

Si vous êtes dans un environnement ATL/MFC, vous pouvez utiliser la macro de conversion ATL :

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

. . .

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

Vous pouvez ensuite utiliser unicodeStr comme LPCWSTR.La mémoire de la chaîne Unicode est créée sur la pile et libérée, puis le destructeur d'UnicodeStr s'exécute.

Au lieu d'utiliser un std :: string, vous pouvez utiliser un std :: wstring.

MODIFIER:Désolé, ce n'est pas plus explicatif, mais je dois courir.

Utilisez 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();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top