Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert from LPWSTR to 'const char*'

Tags:

c++

c++-cli

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.

like image 970
olidev Avatar asked Mar 23 '12 13:03

olidev


2 Answers

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.

like image 57
Ivan Gozali Avatar answered Oct 21 '22 20:10

Ivan Gozali


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)

like image 5
MSalters Avatar answered Oct 21 '22 20:10

MSalters