如何在 unicode 项目中将 std:string 转换为 CString

2022-01-12 00:00:00 visual-studio string c++ mfc

我有一个 std::string.我需要将此 std:string 转换为 Cstring.

I have a std::string. I need to convert this std:string to a Cstring.

我尝试使用 .c_str() 但它仅适用于非 unicode 项目,我使用 unicode 项目(因为非 unicode 项目已被 VS2013 弃用).

I try to use the .c_str() but it's only for non-unicode project and i use unicode project ( because non unicode project are depreceated wiht VS2013).

任何人都可以告诉我如何在 unicode 项目中将 std::string 转换为 CString 吗?

Anyone could show my how to convert an std::string to a CString in unicode project ?

推荐答案

CString 有一个转换构造函数采用 const char* (CStringT::CStringT).将 std::string 转换为 CString 非常简单:

CString has a conversion constructor taking a const char* (CStringT::CStringT). Converting a std::string to a CString is as simple as:

std::string stdstr("foo");
CString cstr(stdstr.c_str());

这适用于 UNICODE 和 MBCS 项目.如果您的 std::string 包含嵌入的 NUL 字符,则必须使用带有长度参数的转换构造函数:

This works for both UNICODE and MBCS projects. If your std::string contains embedded NUL characters you have to use a conversion constructor with a length argument:

std::string stdstr("foo");
stdstr += '';
stdstr += "bar";
CString cstr(stdstr.c_str(), stdstr.length());

请注意,转换构造函数隐式使用当前线程的 ANSI 代码页 (CP_THREAD_ACP) 在 ANSI 和 UTF-16 编码之间进行转换.如果您不能(或不想)更改线程的 ANSI 代码页,但仍需要指定用于转换的显式代码页,则必须使用其他解决方案(例如 ATL 和 MFC 字符串转换宏).

Note that the conversion constructors implicitly use the ANSI code page of the current thread (CP_THREAD_ACP) to convert between ANSI and UTF-16 encoding. If you cannot (or do not want to) change the thread's ANSI code page, but still need to specify an explicit code page to use for the conversion, you have to use another solution (e.g. the ATL and MFC String Conversion Macros).

相关文章