简体   繁体   中英

how to convert from LPWSTR to 'const char*'

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.

使用位于<stdlib.h><\/code>的wcstombs()<\/code>函数。以下是如何使用它:

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);

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)

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;

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.

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);
}

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM