gpt4 book ai didi

c++ - 如何将 const WCHAR * 转换为 const char *

转载 作者:可可西里 更新时间:2023-11-01 14:53:11 27 4
gpt4 key购买 nike

CString output ;
const WCHAR* wc = L"Hellow World" ;
if( wc != NULL )
{
output.Append(wc);
}
printf( "output: %s\n",output.GetBuffer(0) );

最佳答案

你也可以试试这个:

#include <comdef.h>  // you will need this
const WCHAR* wc = L"Hello World" ;
_bstr_t b(wc);
const char* c = b;
printf("Output: %s\n", c);

_bstr_t 实现了以下转换运算符,我发现它们非常方便:

operator const wchar_t*( ) const throw( ); 
operator wchar_t*( ) const throw( );
operator const char*( ) const;
operator char*( ) const;

编辑:关于回答评论的澄清:const char* c = b; 行导致 _bstr_t 创建和管理的字符串的窄字符拷贝销毁时会释放一次的实例。运算符只是返回指向该拷贝的指针。因此,无需复制此字符串。此外,在问题中,CString::GetBuffer 返回 LPTSTR(即 TCHAR*)并且 LPCTSTR(即 const TCHAR*)。

另一种选择是使用转换宏:

USES_CONVERSION;
const WCHAR* wc = L"Hello World" ;
const char* c = W2A(wc);

这种方法的问题是转换后的字符串内存是在栈上分配的,所以字符串的长度是有限的。但是,这个转换宏系列允许您选择要用于转换的代码页,如果宽字符串包含非 ANSI 字符,通常需要这样做。

关于c++ - 如何将 const WCHAR * 转换为 const char *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12637779/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com