C++ vc++ - 如何将 CString 转换为 LPCWSTR

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5271461/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:47:50  来源:igfitidea点击:

vc++ - How to convert a CString into LPCWSTR

c++visual-c++mfc

提问by prabhakaran

I tried to do this , but I didn't find any method for this. I am asking this due to the fact that I am new to windows. I tried stl-strings, but visual studio 2008- accumulates bugs in stl-wstring-handling. I will say a lot about that thing later, in other question. Now Can anybody shed light on this issue?

我试图这样做,但我没有找到任何方法。我问这个是因为我是 Windows 新手。我尝试过 stl-strings,但 Visual Studio 2008- 在 stl-wstring-handling 中积累了错误。稍后我会在其他问题中说很多关于那件事的内容。现在有人可以阐明这个问题吗?

回答by J?rgen Sigvardsson

Use the conversion class CT2CW like this FuncTakingLPCWSTR(CT2CW(cstring_var)). This is guaranteed to work in either Unicode or MBCS builds.

像这样使用转换类 CT2CW FuncTakingLPCWSTR(CT2CW(cstring_var))。这保证可以在 Unicode 或 MBCS 版本中工作。

Also, keep in mind that the string passed to the function may be a temporary, so don't store it for later use.

另外,请记住传递给函数的字符串可能是临时的,所以不要存储它以备后用。

回答by Inverse

The easiest way is to use the MFC String Conversion Macros, defined at:

最简单的方法是使用 MFC 字符串转换宏,定义在:

http://msdn.microsoft.com/en-us/library/87zae4a3%28VS.80%29.aspx

http://msdn.microsoft.com/en-us/library/87zae4a3%28VS.80%29.aspx

For example, the macro to convert CStringto LPCWSTRis CT2W(s).

例如,要转换CString为的宏LPCWSTRCT2W(s).

Another way is to use the specialized CStringAand CStringWclasses. These are the corresponding ascii and wide versions of CStringdepending on if you're compile with the UNICODEflag. So you can use:

另一种方法是使用专业化CStringACStringW类。这些是相应的 ascii 和宽版本,CString具体取决于您是否使用该UNICODE标志进行编译。所以你可以使用:

CString your_string = "blah"
CStringW wide_string = your_string;

to get a wide version of your string.

获得宽版本的字符串。

回答by DavidK

This should do it, assuming your application isn't already set to Unicode (if it is, just cast directly):

这应该可以,假设您的应用程序尚未设置为 Unicode(如果是,则直接转换):

CString str("Hello, world!");
CStringW strw(str);
LPCWSTR ptr = strw;

回答by Asha

If you have UNICODE,_UNICODEcompiler flags defined then a simple assignment should work. If you have _MBCSdefined you need to use MultiByteToWideCharmethod.

如果您UNICODE,_UNICODE定义了编译器标志,那么简单的赋值应该可以工作。如果已_MBCS定义,则需要使用MultiByteToWideChar方法。

回答by Elliot Chen

LPCWSTR pstr;
CString cstrTemp;

...

pstr = cstrTemp.AllocSysString();

AllocSysString will return a BSTR type string, that can be converted to LPCWSTR directly.

AllocSysString 将返回一个 BSTR 类型的字符串,可以直接转换为 LPCWSTR。

回答by Gautam Jain

You can also use T2W() macro to avoid writing several lines of MultiByteToWideChar code.

您还可以使用 T2W() 宏来避免编写多行 MultiByteToWideChar 代码。