如何包装长度可变参数的函数? [英] How to wrap a function with variable length arguments?
问题描述
我希望做这在C / C ++。
I am looking to do this in C/C++.
我遇到 可变长度参数 但是这表明了一个解决方案蟒蛇和放大器;下使用 libffi 。
现在,如果我想换行的printf
函数 myprintf
Now, if I want to wrap printf
function with myprintf
我要做的就是象下面这样:
What I do is like below:
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;
}
但结果并不如预期!
But the results are not as expected!
This is a number: 1244780 and
this is a character: h and
another number: 29953463
任意点在哪里我想念??
Any point where did I miss??
推荐答案
的问题是,你不能用'的printf'与va_args。您必须使用 vprintf 如果您使用的是可变的参数列表。 vprint,vsprintf中,vfprintf等(也有安全的版本在微软的C运行时,将prevent缓冲区溢出等)
the problem is that you cannot use 'printf' with va_args. You must use vprintf if you are using variable argument lists. vprint, vsprintf, vfprintf, etc. (there are also 'safe' versions in Microsoft's C runtime that will prevent buffer overruns, etc.)
您样品的工作原理如下:
You sample works as follows:
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;
}
这篇关于如何包装长度可变参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!