如何从 std::wstring _TCHAR [] 转换?
我正在使用一个库,并从它的一个函数向我发送 std::wstring
,而另一个库则需要将 _TCHAR []
发送给它。我该如何转换它?
I'm using a library and sends me std::wstring
from one of its functions, and another library that requires _TCHAR []
to be sent to it. How can I convert it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您使用 Unicode 构建,则 std::wstring.c_str() 就是您所需要的。请注意,c_str() 保证它返回的字符串以 null 结尾。
例如,
如果您使用非 Unicode 版本,则需要通过 WideCharToMultiByte。
Assuming you're using Unicode build, std::wstring.c_str() is what you need. Note that c_str() guarantees that the string it returns is null-terminated.
e.g.
If you're using non-Unicode build, you'll need to convert the Unicode string to non Unicode string via WideCharToMultiByte.
正如@Zach Saw所说,如果你只为Unicode构建,你可以使用
std::wstring.c_str()
,但从概念上讲,最好定义一个< code>tstring (std::basic_string
的typedef
),因此您可以安全地在所有 Windows 和库函数中完美地使用这种字符串期望TCHAR
s1。为了获得更多乐趣,您还应该为
TCHAR
定义所有其他与字符串相关的 C++ 工具,并创建转换函数std::string
/std::wstring< /代码> <=>
tstring
。幸运的是,这项工作已经完成了;请参阅此处以及此处。
TCHAR *
,因为TCHAR
被解析为char
或wchar_t
s 在编译时,但你明白了。As @Zach Saw said, if you build only for Unicode you can get away with
std::wstring.c_str()
, but conteptually it would be better to define atstring
(atypedef
forstd::basic_string<TCHAR>
) so you can safely use this kind of string flawlessly with all the Windows and library functions which expectTCHAR
s1.For additional fun you should define also all the other string-related C++ facilities for
TCHAR
s, and create conversion functionsstd::string
/std::wstring
<=>tstring
.Fortunately, this work has already been done; see here and here.
TCHAR *
, sinceTCHAR
s are resolved aschar
s orwchar_t
s at compile time, but you got the idea.使用ATL 和 MFC 字符串转换宏。无论您是在
_UNICODE
还是 ANSI 模式下编译,这都有效。即使您不使用 MFC,也可以使用这些宏。只需包含本示例中所示的两个 ATL 标头:
Use the ATL and MFC String Conversion Macros. This works regardless of whether you are compiling in
_UNICODE
or ANSI mode.You can use these macros even if you aren’t using MFC. Just include the two ATL headers shown in this example: