0
我在库中有一些代码需要在内部使用wstring,这一切都很好。但是它使用了unicode和非unicode项目的TCHAR字符串参数来调用,并且我无法在两种情况下都找到一个整洁的转换。在unicode和非unicode环境中转换TCHAR * - > std :: wstring
我看到一些ATL转换等,但不能看到正确的方式,不使用#define
我在库中有一些代码需要在内部使用wstring,这一切都很好。但是它使用了unicode和非unicode项目的TCHAR字符串参数来调用,并且我无法在两种情况下都找到一个整洁的转换。在unicode和非unicode环境中转换TCHAR * - > std :: wstring
我看到一些ATL转换等,但不能看到正确的方式,不使用#define
假设TCHAR
扩展到以Unicode wchar_t
定义多个代码路径构建:
inline std::wstring convert2widestr(const wchar_t* const psz)
{
return psz;
}
inline std::wstring convert2widestr(const char* const psz)
{
std::size_t len = std::strlen(psz);
if(psz.empty()) return std::wstring();
std::vector<wchar_t> result;
const int len = WideCharToMultiByte(CP_ACP
, 0
, reinterpret_cast<LPCWSTR>(psz)
, static_cast<int>(len)
, NULL
, 0
, NULL
, NULL
);
result.resize(len);
if(result.empty()) return std::wstring();
const int cbytes = WideCharToMultiByte(CP_ACP
, 0
, reinterpret_cast<LPCWSTR>(psz)
, static_cast<int>(len)
, reinterpret_cast<LPSTR>(&result[0])
, static_cast<int>(result.size())
, NULL
, NULL
);
assert(cbytes);
return std::wstring(result.begin(), result.begin() + cbytes);
}
使用像这个:
void f(const TCHAR* psz)
{
std::wstring str = convert(psz);
// ...
}
eeeeeeeeeeeeeeew!虽然,很好的使用重载来避免'#define'。 – 2010-07-28 14:58:24
CP_UTF8在传统Windows程序中非常不可能。改用CP_ACP。或者只是使用mbstowcs()。 – 2010-07-28 15:43:45
@Hans:这是一个copy'n'paste错误。 ':(' – sbi 2010-07-28 17:15:46