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 %
gcc offers an extension that can do this: __builtin_apply and relatives. See Constructing Function Calls in the gcc manual.
An example:
#include
int my_printf(const char *fmt, ...) {
void *args = __builtin_apply_args();
printf("Hello there! Format string is %s\n", fmt);
void *ret = __builtin_apply((void (*)())printf, args, 1000);
__builtin_return(ret);
}
int main(void) {
my_printf("%d %f %s\n", -37, 3.1415, "spam");
return 0;
}
Try it on godbolt
There are some cautions in the documentation that it might not work in more complicated situations. And you have to hardcode a maximum size for the arguments (here I used 1000). But it might be a reasonable alternative to the other approaches that involve dissecting the stack in either C or assembly language.