我有char*
格式的字符串,想将其转换为wchar_t*
,以传递给Windows函数。
答案 0 :(得分:13)
这个小功能有帮助吗?
#include <cstdlib>
int mbstowcs(wchar_t *out, const char *in, size_t size);
答案 1 :(得分:8)
如果您不想链接C运行时库,请使用MultiByteToWideChar API调用,例如:
const size_t WCHARBUF = 100;
const char szSource[] = "HELLO";
wchar_t wszDest[WCHARBUF];
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szSource, -1, wszDest, WCHARBUF);
答案 2 :(得分:2)
Windows SDK在kernel32.lib中指定了2个函数,用于将字符串转换为宽字符集。这些是MultiByteToWideChar()
和WideCharToMultiByte()
。
请注意,与函数名称建议不同,字符串不一定使用多字节字符集,但可以是简单的ANSI字符串。另请注意,这些函数将UTF-7和UTF-8理解为多字节字符集。宽字符字符集始终为UTF-16。
答案 3 :(得分:1)
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;
}