How to convert from LPWSTR to 'const char *'

After getting the structure from C # to C ++ using C ++ / CLI:

public value struct SampleObject { LPWSTR a; }; 

I want to print my copy:

 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.

+4
source share
5 answers

Do not convert.

Use wprintf instead of printf :

See examples for how to use it.

Alternatively, you can use std::wcout as:

 wchar_t *wstr1= L"string"; LPWSTR wstr2= L"string"; //same as above std::wcout << wstr1 << L", " << wstr2; 

Similarly, use functions that are designed for widescreen char, and forget the idea of โ€‹โ€‹converting wchar_t to char , as this can lead to data loss.

Take a look at the functions that deal with wide char here:

+3
source

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 feature saved me a lot of disappointments.

+15
source

Just use printf("%ls", sampleObject->a) . Using l in %ls means you can pass wchar_t[] , for example L"Wide String" .

(No, I don't know why the L and w prefixes mix all the time)

+4
source
 int length = WideCharToMultiByte(cp, 0, sampleObject->a, -1, 0, 0, NULL, NULL); char* output = new char[length]; WideCharToMultiByte(cp, 0, sampleObject->a, -1, output , length, NULL, NULL); printf(output); delete[] output; 
+2
source

use the WideCharToMultiByte() method to convert a multibyte character.

Here is an example conversion from LPWSTR to char * or a wide character character.

 /*LPWSTR to char* example.c */ #include <stdio.h> #include <windows.h> void LPWSTR_2_CHAR(LPWSTR,LPSTR,size_t); int main(void) { wchar_t w_char_str[] = {L"This is wide character string test!"}; size_t w_len = wcslen(w_char_str); char char_str[w_len + 1]; memset(char_str,'\0',w_len * sizeof(char)); LPWSTR_2_CHAR(w_char_str,char_str,w_len); puts(char_str); return 0; } void LPWSTR_2_CHAR(LPWSTR in_char,LPSTR out_char,size_t str_len) { WideCharToMultiByte(CP_ACP,WC_COMPOSITECHECK,in_char,-1,out_char,str_len,NULL,NULL); } 
0
source

Source: https://habr.com/ru/post/1403082/


All Articles