在 C 中转发可变参数函数的调用 [英] Forward an invocation of a variadic function in C
问题描述
在 C 中,是否可以转发可变参数函数的调用?如,
In C, is it possible to forward the invocation of a variadic function? As in,
int my_printf(char *fmt, ...) {
fprintf(stderr, "Calling printf with fmt %s", fmt);
return SOMEHOW_INVOKE_LIBC_PRINTF;
}
在这种情况下,以上述方式转发调用显然不是绝对必要的(因为您可以以其他方式记录调用,或使用 vfprintf),但我正在处理的代码库需要包装器做一些实际工作,并且没有(也不能添加)类似于 vfprintf 的辅助函数.
Forwarding the invocation in the manner above obviously isn't strictly necessary in this case (since you could log invocations in other ways, or use vfprintf), but the codebase I'm working on requires the wrapper to do some actual work, and doesn't have (and can't have added) a helper function akin to vfprintf.
[更新:根据迄今为止提供的答案,似乎有些混乱.用另一种方式来表达这个问题:一般来说,你可以包装一些任意可变参数函数而不修改该函数的定义.]
[Update: there seems to be some confusion based on the answers that have been supplied so far. To phrase the question another way: in general, can you wrap some arbitrary variadic function without modifying that function's definition.]
推荐答案
如果你没有类似于 vfprintf
的函数,它接受 va_list
而不是变量参数的数量,你做不到.请参阅 http://c-faq.com/varargs/handoff.html.
If you don't have a function analogous to vfprintf
that takes a va_list
instead of a variable number of arguments, you can't do it. See http://c-faq.com/varargs/handoff.html.
例子:
void myfun(const char *fmt, va_list argp) {
vfprintf(stderr, fmt, argp);
}
这篇关于在 C 中转发可变参数函数的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!