【发布时间】:2011-03-22 04:52:28
【问题描述】:
我在一个库中有一些代码必须在内部使用 wstring,这一切都很好。但它是使用 TCHAR 字符串参数调用的,来自 unicode 和非 unicode 项目,我无法为这两种情况找到一个简洁的转换。
我看到了一些 ATL 转换等但看不到正确的方法,没有使用 #define 定义多个代码路径
【问题讨论】:
标签: c++ visual-c++ unicode atl
我在一个库中有一些代码必须在内部使用 wstring,这一切都很好。但它是使用 TCHAR 字符串参数调用的,来自 unicode 和非 unicode 项目,我无法为这两种情况找到一个简洁的转换。
我看到了一些 ATL 转换等但看不到正确的方法,没有使用 #define 定义多个代码路径
【问题讨论】:
标签: c++ visual-c++ unicode atl
假设 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);
// ...
}
【讨论】:
#define。
WideCharToMultiByte() 是为你做的。但它是一个 C API 函数,并且由于 C 无法处理资源,调用它很痛苦。但是,如果这看起来太复杂,您可以随时使用我的答案的第一个版本。 :)