如何在C ++(Unicode)中将std :: string转换为LPCWSTR

时间:2020-03-05 18:43:06  来源:igfitidea点击:

我正在寻找一种方法或者代码片段,用于将std :: string转换为LPCWSTR

解决方案

回答

除了使用std :: string,还可以使用std :: wstring。

编辑:对不起,这不是更多解释,但我必须运行。

使用std :: wstring :: c_str()

回答

如果我们在ATL / MFC环境中,则可以使用ATL转换宏:

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

. . .

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

然后,我们可以将unicodeStr用作LPCWSTR。 unicode字符串的内存在堆栈上创建并释放,然后执行unicodeStr的析构函数。

回答

感谢我们到MSDN文章的链接。这正是我想要的。

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

回答

实际上,该解决方案比其他任何建议都容易得多:

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

最重要的是,它是独立于平台的。 h2h :)