实现函数如下:
std::string CStringToUTF8(const CString& str)
{// Step 1: 将 MBCS (GBK) CString 转换为宽字符(WCHAR)int wideLen = MultiByteToWideChar(CP_ACP, 0, str.GetString(), -1, NULL, 0);if (wideLen <= 0)return "";std::wstring wideStr(wideLen, L'\0');MultiByteToWideChar(CP_ACP, 0, str.GetString(), -1, &wideStr[0], wideLen);// Step 2: 将宽字符字符串转换为 UTF-8 编码的 std::stringint utf8Len = WideCharToMultiByte(CP_UTF8, 0, wideStr.c_str(), -1, NULL, 0, NULL, NULL);if (utf8Len <= 0)return "";std::string utf8Str(utf8Len, '\0');WideCharToMultiByte(CP_UTF8, 0, wideStr.c_str(), -1, &utf8Str[0], utf8Len, NULL, NULL);return utf8Str;
}