我希望在 C/C++ 中执行此操作。我遇到了Variable Length Arguments ,但这建议使用 Python 和 C 的解决方案 libffi .
现在,如果我想用 myprintf
包装 printf
函数。
我这样做如下:
void myprintf(char* fmt, ...)
{
va_list args;
va_start(args, fmt);
printf(fmt, args);
va_end(args);
}
int _tmain(int argc, _TCHAR* argv[])
{
int a = 9;
int b = 10;
char v = 'C';
myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n", a, v, b);
return 0;
}
但结果并不如预期!
This is a number: 1244780 and
this is a character: h and
another number: 29953463
我错过了什么?
最佳答案
问题是您不能将'printf' 与va_args 一起使用。如果您使用可变参数列表,则必须使用 vprintf。 vprint、vsprintf、vfprintf 等(Microsoft 的 C 运行时中也有“安全”版本,可以防止缓冲区溢出等)
您的示例作品如下:
void myprintf(char* fmt, ...)
{
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
}
int _tmain(int argc, _TCHAR* argv[])
{
int a = 9;
int b = 10;
char v = 'C';
myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n", a, v, b);
return 0;
}
关于c++ - 如何包装具有可变长度参数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41400/