1 Star 0 Fork 0

2144/engine_sub

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
XUtil.cpp 2.41 KB
一键复制 编辑 原始数据 按行查看 历史
2144 提交于 2023-11-28 09:15 . ssss
#include "XUtil.h"
#ifdef WIN32
#pragma warning(push)
#pragma warning(disable: 28251)
extern "C" __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char* str, int cbmb, wchar_t* widestr, int cchwide);
extern "C" __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t* widestr, int cchwide, char* str, int cbmb, const char* defchar, int* used_default);
#pragma warning(pop)
std::wstring XUtil::UTF8ToWString(const std::string& utf8str)
{
if (utf8str.empty())
return std::wstring();
int cbMultiByte = static_cast<int>(utf8str.size());
int req = MultiByteToWideChar(65001, 0, utf8str.data(), cbMultiByte, nullptr, 0);
std::wstring res(req, 0);
MultiByteToWideChar(65001, 0, utf8str.data(), cbMultiByte, &res[0], req);
return res;
}
std::string XUtil::WStringToUTF8(const std::wstring &wstr)
{
if (wstr.empty())
return std::string();
int cbMultiByte = static_cast<int>(wstr.size());
int req = WideCharToMultiByte(65001, 0, wstr.data(), cbMultiByte, nullptr, 0, nullptr, nullptr);
std::string res(req, 0);
WideCharToMultiByte(65001, 0, wstr.data(), cbMultiByte, &res[0], req, nullptr, nullptr);
return res;
}
#endif // DEBUG
#ifdef __linux__
std::wstring XUtil::UTF8ToWString(const std::string &mbstr)
{
std::wstring wstr;
if (mbstr.empty())
return wstr;
// Get the required size for the wide string
size_t size = mbstowcs(nullptr, mbstr.c_str(), 0);
if (size == static_cast<size_t>(-1))
{
// Error handling
return wstr;
}
wstr.resize(size);
// Perform the conversion
size = mbstowcs(&wstr[0], mbstr.c_str(), size);
if (size == static_cast<size_t>(-1))
{
// Error handling
return std::wstring();
}
return wstr;
}
std::string XUtil::WStringToUTF8(const std::wstring &wstr)
{
std::string mbstr;
if (wstr.empty())
return mbstr;
// Get the required size for the multi-byte string
size_t size = wcstombs(nullptr, wstr.c_str(), 0);
if (size == static_cast<size_t>(-1))
{
// Error handling
return mbstr;
}
mbstr.resize(size);
// Perform the conversion
size = wcstombs(&mbstr[0], wstr.c_str(), size);
if (size == static_cast<size_t>(-1))
{
// Error handling
return std::string();
}
return mbstr;
}
#endif
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/iamherer/engine_sub.git
git@gitee.com:iamherer/engine_sub.git
iamherer
engine_sub
engine_sub
master

搜索帮助