我正在寻找将 std::string 转换为 LPCWSTR 的方法或代码片段

有帮助吗?

解决方案

感谢您提供 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();

最重要的是,它是独立于平台的。小时2小时:)

如果你在ATL/MFC环境下,你可以使用ATL转换宏:

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

. . .

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

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

您可以使用 std::wstring,而不是使用 std::string。

编辑:抱歉,这没有更多解释,但我必须跑步。

使用 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();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top