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

How to convert std:string to CString in unicode project

本文关键字:string 转换 CString std unicode 项目      更新时间:2023-10-16

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

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

任何人都可以向我展示如何在 unicode 项目中将std::string转换为CString

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

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

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

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

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

Unicode CString 的构造函数接受char*,所以你可以这样做:

std::string str = "string";
CString ss(str.c_str());

使用 ATL 转换宏。当您使用 CString 时,它们在任何情况下都有效。CString 要么是 MBCS 要么是 Unicode...取决于您的编译器设置。

std::string str = "string";
CString ss(CA2T(str.c_str());

奖励:如果您经常使用转换,您可以定义一个宏:

#define STDTOCSTRING(s) CString(s.c_str())

因此,您的代码更具可读性。