Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from LPWSTR to LPTSTR

Tags:

c++

Im trying to convert arguments LPWSTR to LPTSTR, it there any library I can user for easy string convertion?

like image 320
Darkmage Avatar asked Jan 15 '23 18:01

Darkmage


2 Answers

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 (i.e. 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.

like image 174
Matteo Italia Avatar answered Jan 25 '23 16:01

Matteo Italia


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.

like image 26
prazuber Avatar answered Jan 25 '23 16:01

prazuber