你应该这样做:
inline std::wstring convert(const std::string& as)
{
// deal with trivial case of empty string
if(as.empty()) return std::wstring();
// determine required length of new string
size_t reqLength = ::MultiByteToWideChar(CP_UTF8, 0, as.c_str(), (int)as.length(), 0, 0);
// construct new string of required length
std::wstring ret(reqLength, L'\0');
// convert old string to new string
::MultiByteToWideChar(CP_UTF8, 0, as.c_str(), (int)as.length(), &ret[0], (int)ret.length());
// return new string (compiler should optimize this away)
return ret;
}
这预计的std :: string是UTF- 8(CP_UTF8),当你有另一种编码替换代码页。
另一种方式可以是:
inline std::wstring convert(const std::string& as)
{
wchar_t* buf = new wchar_t[as.size() * 2 + 2];
swprintf(buf, L"%S", as.c_str());
std::wstring rval = buf;
delete[] buf;
return rval;
}