问题描述
CString output ;
const WCHAR* wc = L"Hellow World" ;
if( wc != NULL )
{
output.Append(wc);
}
printf( "output: %s\n",output.GetBuffer(0) );
推荐答案
您也可以尝试以下方法:
you can also try this:
#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
实现以下转换运算符,我觉得很方便:
_bstr_t
implements following conversion operators, which I find quite handy:
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 *
).
clarification with regard to answer comments: line const char* c = b;
results in a narrow character copy of the string being created and managed by the _bstr_t
instance which will release it once when it is destroyed. The operator just returns a pointer to this copy. Therefore, there is no need to copy this string. Besides, in the question, CString::GetBuffer
returns LPTSTR
(i.e. TCHAR*
) and not LPCTSTR
(i.e. const TCHAR*
).
另一种选择是使用转换宏:
Another option is to use conversion macros:
USES_CONVERSION;
const WCHAR* wc = L"Hello World" ;
const char* c = W2A(wc);
此方法的问题在于,转换后的字符串的内存是在堆栈上分配的,因此字符串的长度受到限制.但是,此转换宏系列允许您选择用于转换的代码页,如果宽字符串包含非ANSI字符,则通常需要使用该代码页.
The problem with this approach is that the memory for converted string is allocated on stack, so the length of the string is limited. However, this family of conversion macros allow you to select the code page which is to be used for the conversion, which is often needed if wide string contains non-ANSI characters.
这篇关于如何将const WCHAR *转换为const char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!