Forward an invocation of a variadic function in C

前端 未结 12 2640
悲哀的现实
悲哀的现实 2020-11-22 06:41

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 %         


        
12条回答
  •  爱一瞬间的悲伤
    2020-11-22 07:26

    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.

提交回复
热议问题