有点歪门邪道,但的确很简洁,且跨平台,需 C++ 17。
///<summary>多字节字符串转宽字节字符串 (仅 C++17, 需 #include string/filesystem)</summary>
///<param name="sText">多字节字符串</param>
///<param name="bUtf8">源多字符串是否 UTF-8 编码,否则是 ANSI 编码</param>
///<returns>宽字节字符串</returns>
std::wstring M2W(const char* sText, bool bUtf8)
{
if (sText != nullptr && *sText != '\0')
{
try
{
if (bUtf8)
return std::filesystem::u8path(sText).wstring();
else
return std::filesystem::path(sText).wstring();
}
catch (const std::exception&) {}
}
return L"";
}
///<summary>宽字节字符串转多字节字符串 (仅 C++17, 需 #include string/filesystem)</summary>
///<param name="sText">宽字节字符串</param>
///<param name="bUtf8">是否转换成 UTF-8 编码,否则转换成 ANSI 编码</param>
///<returns>UTF-8 或 ANSI 编码的多字节字符串</returns>
std::string W2M(const wchar_t* sText, bool bUtf8)
{
if (sText != nullptr && *sText != L'\0')
{
try
{
if (bUtf8)
return std::filesystem::path(sText).u8string();
else
return std::filesystem::path(sText).string();
}
catch (const std::exception&) {}
}
return "";
}