[英]how to convert from LPWSTR to 'const char*'
After getting a struct from C# to C++ using C++/CLI:使用 C++/CLI 将结构从 C# 获取到 C++ 后:
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 *'
错误 1 错误 C2664:“printf”:无法将参数 1 从“LPWSTR”转换为“const char *”
How can I convert from LPWSTR to char*
?如何从
LPWSTR to char*
转换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)
.只需使用
printf("%ls", sampleObject->a)
。 The use of l
in %ls
means that you can pass a wchar_t[]
such as L"Wide String"
.在
%ls
使用l
意味着您可以传递wchar_t[]
例如L"Wide String"
。
(No, I don't know why the L and w prefixes are mixed all the time) (不,我不知道为什么 L 和 w 前缀总是混合在一起)
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;
use WideCharToMultiByte()
method to convert multi-byte character.使用
WideCharToMultiByte()
方法转换多字节字符。
Here is example of converting from LPWSTR to char* or wide character to character.这是从 LPWSTR 转换为 char* 或从宽字符转换为字符的示例。
/*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
:使用
wprintf
而不是printf
:
See the examples which explains how to use it.请参阅说明如何使用它的示例。
Alternatively, you can use std::wcout
as:或者,您可以将
std::wcout
用作:
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.同样,使用为宽字符设计的函数,忘记将
wchar_t
转换为char
的想法,因为它可能会丢失数据。
Have a look at the functions which deal with wide-char here:在这里查看处理宽字符的函数:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.