当前位置:首页> 正文

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

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

How to convert std::string to LPCWSTR in C++ (Unicode)

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


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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();

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

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

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


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

1
2
3
4
5
6
7
#include
#include

. . .

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

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


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

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

使用std :: wstring :: c_str()


LPCWSTR lpcwName = std :: wstring(strname.begin(),strname.end())。c_str()


1
2
3
4
5
6
7
8
9
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();


展开全文阅读

相关内容