how to convert from LPWSTR to 'const char*'

2020-03-25 03:33发布

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.

标签: c++ c++-cli
6条回答
做个烂人
2楼-- · 2020-03-25 04:00

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楼-- · 2020-03-25 04:02

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)

查看更多
你好瞎i
4楼-- · 2020-03-25 04:04

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);
}
查看更多
何必那么认真
5楼-- · 2020-03-25 04:08

Don't convert.

Use wprintf instead of printf:

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:

查看更多
在下西门庆
6楼-- · 2020-03-25 04:10
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;
查看更多
霸刀☆藐视天下
7楼-- · 2020-03-25 04:17

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.

查看更多
登录 后发表回答