[英]Convert TCHAR * -> std::wstring in both unicode and non-unicode environments
我在一個必須在內部使用wstring的庫中有一些代碼,一切都很好。 但是在unicode和non-unicode項目中都使用TCHAR字符串參數調用它,在這兩種情況下我都很難找到一個整潔的轉換。
我看到了一些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);
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.