After getting a struct from C# to C++ using C++/CLI:
public value struct SampleObject
{
LPWSTR a;
};
I want to print its instance:
printf(sampleObject->a);
but I got this error:
Error 1 error C2664: 'printf' : cannot convert parameter 1 from 'LPWSTR' to 'const char *'
How can I convert from LPWSTR to char*
?
Thanks in advance.
Use the
wcstombs()
function, which is located in<stdlib.h>
. Here's how to use it:Hope this helped someone! This function saved me from a lot of frustration.
Just use
printf("%ls", sampleObject->a)
. The use ofl
in%ls
means that you can pass awchar_t[]
such asL"Wide String"
.(No, I don't know why the L and w prefixes are mixed all the time)
use
WideCharToMultiByte()
method to convert multi-byte character.Here is example of converting from LPWSTR to char* or wide character to character.
Don't convert.
Use
wprintf
instead ofprintf
:See the examples which explains how to use it.
Alternatively, you can use
std::wcout
as:Similarly, use functions which are designed for wide-char, and forget the idea of converting
wchar_t
tochar
, as it may loss data.Have a look at the functions which deal with wide-char here:
Here is a Simple Solution. Check wsprintf
The "%S" will implicitly convert UNICODE to ANSI.