如何在 C++ (Unicode) 中将 std::string 转换为 LPCWSTR
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert std::string to LPCWSTR in C++ (Unicode)
提问by Toran Billups
I'm looking for a method, or a code snippet for converting std::string to LPCWSTR
我正在寻找将 std::string 转换为 LPCWSTR 的方法或代码片段
回答by Toran Billups
Thanks for the link to the MSDN article. This is exactly what I was looking for.
感谢您提供 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();
回答by Benny Hilfiger
The solution is actually a lot easier than any of the other suggestions:
该解决方案实际上比任何其他建议都容易得多:
std::wstring stemp = std::wstring(s.begin(), s.end());
LPCWSTR sw = stemp.c_str();
Best of all, it's platform independent. h2h :)
最重要的是,它是独立于平台的。小时 :)
回答by 17 of 26
If you are in an ATL/MFC environment, You can use the ATL conversion macro:
如果您在 ATL/MFC 环境中,您可以使用 ATL 转换宏:
#include <atlbase.h>
#include <atlconv.h>
. . .
string myStr("My string");
CA2W unicodeStr(myStr);
You can then use unicodeStr as an LPCWSTR. The memory for the unicode string is created on the stack and released then the destructor for unicodeStr executes.
然后,您可以将 unicodeStr 用作 LPCWSTR。unicode 字符串的内存在堆栈上创建并释放,然后执行 unicodeStr 的析构函数。
回答by Ed S.
Instead of using a std::string, you could use a std::wstring.
您可以使用 std::wstring 代替 std::string。
EDIT: Sorry this is not more explanatory, but I have to run.
编辑:对不起,这不是更具解释性,但我必须运行。
Use std::wstring::c_str()
使用 std::wstring::c_str()
回答by Milind Morey
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();
回答by Milind Morey
LPCWSTR lpcwName=std::wstring(strname.begin(), strname.end()).c_str()
LPCWSTR lpcwName=std::wstring(strname.begin(), strname.end()).c_str()