windows 如何将 char 字符串转换为 wchar_t 字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1791578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert a char string to a wchar_t string?
提问by justinhj
I have a string in char*
format and would like to convert it to wchar_t*
, to pass to a Windows function.
我有一个char*
格式的字符串,想将其转换为wchar_t*
, 以传递给 Windows 函数。
回答by schnaader
Does this little function help?
这个小功能有用吗?
#include <cstdlib>
int mbstowcs(wchar_t *out, const char *in, size_t size);
Also see the C++ reference
另请参阅C++ 参考
回答by Hernán
If you don't want to link against the C runtime library, use the MultiByteToWideChar API call, e.g:
如果您不想链接 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);
回答by Adrien Plisson
the Windows SDK specifies 2 functions in kernel32.lib for converting strings from and to a wide character set. those are MultiByteToWideChar()
and WideCharToMultiByte()
.
Windows SDK 在 kernel32.lib 中指定了 2 个函数,用于将字符串从宽字符集转换为宽字符集。那些是MultiByteToWideChar()
和WideCharToMultiByte()
。
please note that, unlike the function name suggest, the string does not necessarily use a multi-byte character set, but can be a simple ANSI string. alse note that those functions understand UTF-7 and UTF-8 as a multi-byte character set. the wide char character set is always UTF-16.
请注意,与函数名称所暗示的不同,字符串不一定使用多字节字符集,但可以是简单的 ANSI 字符串。另请注意,这些函数将 UTF-7 和 UTF-8 理解为多字节字符集。宽字符集始终为 UTF-16。
回答by AProgrammer
schnaader's answer use the conversion defined by the current C locale, this one uses the C++ locale interface (who said that it was simple?)
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;
}