how to convert from LPWSTR to 'const char*'

2020-03-25 03:50发布

问题:

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.

回答1:

Don't convert.

Use wprintf instead of printf:

  • wprintf

See the examples which explains 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 which are designed for wide-char, and forget the idea of converting wchar_t to char, as it may loss data.

Have a look at the functions which deal with wide-char here:

  • Unicode in Visual C++


回答2:

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.



回答3:

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)



回答4:

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;


回答5:

Here is a Simple Solution. Check wsprintf

LPWSTR wideStr = "some text";
char* resultStr = new char [wcslen(wideStr) + 1];
wsprintfA ( resultStr, "%S", wideStr);

The "%S" will implicitly convert UNICODE to ANSI.



回答6:

use WideCharToMultiByte() method to convert multi-byte character.

Here is example of converting from LPWSTR to char* or wide character to 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);
}


标签: c++ c++-cli