简体   繁体   中英

Convert from LPWSTR to LPTSTR

我试图将参数LPWSTR转换为LPTSTR,那么我可以使用任何库来进行简单的字符串转换吗?

If _UNICODE is defined there's no conversion to do - a TCHAR is a WCHAR , and LPWSTR is LPTSTR ; otherwise, TCHAR is a CHAR , and LPTSTR is LPSTR . In this last case, you can use the WideCharToMultiByte API to convert a LPWSTR (ie a Unicode string) to a "narrow" string.

Also, you can use the wcstombs C library function, assuming that the Windows types CHAR and WCHAR map to the C types char and wchar_t (which is surely the case in VC++), and that the current C locale is the one you intend to use for the conversion.


See also Alf 's comments for more insight on the matter - the most important point being that if you can you should avoid such conversion , since your output encoding in general cannot represent faithfully the input, and, depending from what your string represents this may mean garbled text as well as not finding the required file or, even worse, operating on the wrong path.

So, set your project to use Unicode (as in @prazuber 's answer) and always try to use Unicode-aware APIs, so to avoid this kind of conversion.

Still, keep in mind that using only the Unicode version of the Windows APIs may mean losing compatibility with Windows 9x; this is not a problem for the vast majority of cases, but if it's critical to support such OSes in your application check if the APIs you are using are supported in MSLU .

LPTSTR is defined as follows:

#ifdef UNICODE
 typedef LPWSTR LPTSTR;
#else
 typedef LPSTR LPTSTR;
#endif

So all you need to do is switch your character set to Unicode. For example, in Visual Studio you go to Configuration Properties -> General -> Character Set -> Use Unicode Character Set .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM