如何将charstring转换为wchar_tstring?

我有一个char*格式的string,并希望将其转换为wchar_t* ,以传递给Windows函数。

这个小函数有帮助吗?

 #include <cstdlib> int mbstowcs(wchar_t *out, const char *in, size_t size); 

另请参阅C ++参考

如果您不想链接到C运行时库,请使用MultiByteToWideChar API调用,例如:

 const size_t WCHARBUF = 100; const char s[] = "HELLO"; wchar_t wszDest[WCHARBUF]; MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szSource, -1, wszDest, WCHARBUF); 

Windows SDK在kernel32.lib中指定了两个函数用于将字符串转换为宽字符集。 那些是MultiByteToWideChar()WideCharToMultiByte()

请注意,与函数名称不同,字符串不一定使用多字节字符集,但可以是简单的ANSI字符串。 请注意,这些函数将UTF-7和UTF-8理解为多字节字符集。 宽字符字符集始终是UTF-16。

schnaader的答案使用当前C语言环境定义的转换,这个使用C ++语言环境接口(谁说这很简单?)

 std::wstring widen(std::string const& s, std::locale loc) { std::char_traits<wchar_t>::state_type state = { 0 }; typedef std::codecvt<wchar_t, char, std::char_traits<wchar_t>::state_type > ConverterFacet; ConverterFacet const& converter(std::use_facet<ConverterFacet>(loc)); char const* nextToRead = s.data(); wchar_t buffer[BUFSIZ]; wchar_t* nextToWrite; std::codecvt_base::result result; std::wstring wresult; while ((result = converter.in (state, nextToRead, s.data()+s.size(), nextToRead, buffer, buffer+sizeof(buffer)/sizeof(*buffer), nextToWrite)) == std::codecvt_base::partial) { wresult.append(buffer, nextToWrite); } if (result == std::codecvt_base::error) { throw std::runtime_error("Encoding error"); } wresult.append(buffer, nextToWrite); return wresult; }