How do I convert from _TCHAR * to char * when using C++ variable-length args?(使用 C++ 可变长度参数时,如何从 _TCHAR * 转换为 char *?)
问题描述
我们需要将一个格式 _TCHAR * 字符串和多个 char * 字符串传递给一个可变长度参数的函数:
We need to pass a format _TCHAR * string, and a number of char * strings into a function with variable-length args:
inline void FooBar(const _TCHAR *szFmt, const char *cArgs, ...) {
//...
}
所以可以这样调用:
char *foo = "foo";
char *bar = "bar";
LogToFileA(_T("Test %s %s"), foo, bar);
显然,一个简单的解决方法是使用 _TCHAR 代替 char,但不幸的是,我们没有这种奢侈.
Obviously a simple fix would be to use _TCHAR instead of char, but we don't have that luxury unfortunately.
我们需要将它与 va_start 等一起使用,以便我们可以格式化字符串:
We need to use this with va_start, etc so we can format a string:
va_list args;
_TCHAR szBuf[BUFFER_MED_SIZE];
va_start(args, cArgs);
_vstprintf_s(szBuf, BUFFER_MED_SIZE, szFmt, args);
va_end(args);
不幸的是我们不能使用它,因为它给了我们这个错误:
Unfortunately we cannot use this because it give us this error:
Unhandled exception at 0x6a0d7f4f (msvcr90d.dll) in foobar.exe:
0xC0000005: Access violation reading location 0x2d86fead.
我认为我们需要将 char * 转换为 _TCHAR * - 但是如何?
I'm thinking we need to convert our char * to _TCHAR * - but how?
推荐答案
使用 %hs 或 %hS 代替 %s.这将强制在 Ansi 和 Unicode 版本的 printf() 样式函数中将参数解释为 char*,即:
Use %hs or %hS instead of %s. That will force the parameters to be interpretted as char* in both Ansi and Unicode versions of printf()-style functions, ie:
inline void LogToFile(const _TCHAR *szFmt, ...)
{
va_list args;
TCHAR szBuf[BUFFER_MED_SIZE];
va_start(args, szFmt);
_vstprintf_s(szBuf, BUFFER_MED_SIZE, szFmt, args);
va_end(args);
}
{
char *foo = "foo";
char *bar = "bar";
LogToFile(_T("Test %hs %hs"), foo, bar);
}
这篇关于使用 C++ 可变长度参数时,如何从 _TCHAR * 转换为 char *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 C++ 可变长度参数时,如何从 _TCHAR * 转换为 char *?
基础教程推荐
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
