vc++ - How to convert a CString into LPCWSTR

匿名 (未验证) 提交于 2019-12-03 02:27:02

问题:

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?

回答1:

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

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



回答2:

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

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

For example, the macro to convert CString to LPCWSTR is CT2W(s).

Another way is to use the specialized CStringA and CStringW classes. These are the corresponding ascii and wide versions of CString depending on if you're compile with the UNICODE flag. So you can use:

CString your_string = "blah" CStringW wide_string = your_string; 

to get a wide version of your string.



回答3:

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

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


回答4:

If you have UNICODE,_UNICODE compiler flags defined then a simple assignment should work. If you have _MBCS defined you need to use MultiByteToWideChar method.



回答5:

LPCWSTR pstr; CString cstrTemp;  ...  pstr = cstrTemp.AllocSysString(); 

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



回答6:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!