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:
LPWSTR wideStr = L"Some message";
char buffer[500];
// First arg is the pointer to destination char, second arg is
// the pointer to source wchar_t, last arg is the size of char buffer
wcstombs(buffer, wideStr, 500);
printf("%s", buffer);
Hope this helped someone! This function saved me from a lot of frustration.
Just use printf("%ls", sampleObject->a)
. The use of l
in %ls
means that you can pass a wchar_t[]
such as L"Wide String"
.
(No, I don't know why the L and w prefixes are mixed all the time)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With