Convert TCHAR * -> std::wstring in both unicode and non-unicode environments
I have some code in a library which has to internally work with wstring, that's all nice and fine. But it's called with a TCHAR string parameter, from both unicode and non-unicode projects, and I'm having trouble finding a neat conversion for both cases.
I see some ATL conversions and so on but can't see the right开发者_JAVA技巧 way, without defining multiple code paths using #define
Assuming TCHAR
expands to wchar_t
in Unicode builds:
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 );
}
Use like this:
void f(const TCHAR* psz)
{
std::wstring str = convert(psz);
// ...
}
精彩评论