Reputation: 2586
I am calling a C++ method which returns LPWSTR
(the string contains a filepath), but I need to convert this to a LPSTR
to continue.
I never used C++ before and even though the different string types are explained in detail here: http://www.codeproject.com/Articles/76252/What-are-TCHAR-WCHAR-LPSTR-LPWSTR-LPCTSTR-etc, I got confused.
When I cast LPWSTR
to LPTSTR
(which should equal LPSTR
in my app), I get exactly one Unicode Symbol. While I guess that casting isn't appropriate in this case, I don't understand why it returns only one character instead of interpreting all the 2-byte-characters of the LPWSTR
somehow as 1-byte-characters. I found references to the WideCharToMultiByte
function, which apparently can convert LPWSTR
to std::string
, which I in turn can not cast to LPSTR
either.
So is there an somewhat easy way to obtain an LPSTR
from the LPWSTR
?
Upvotes: 1
Views: 6570
Reputation: 20671
Casting a pointer to another type of pointer will not alter or convert what the original pointer points at.
You should be able to call c_str()
on a std::string
, and cast that to LPSTR
, I think. So, use WideCharToMultiByte
(if it does indeed, as you say, convert to a std::string
) and call c_str
on the result. This will give you a constant string pointer (LPCSTR
). You can copy it (eg via strdup
) and cast the result to LPSTR
.
The returned pointer will then refer to a character string allocated using strdup
, so should be passed to free
at some point when the string is no longer needed.
The WideCharToMultiByte
function that I am familiar with from the Windows API (see documentation) converts directly from a wide-character string to a multi-byte encoded string without going via std::string
, although it still requires allocation of a buffer to hold the output string. You may be able to use it instead.
Upvotes: 1