creating va_list dynamically in GCC - can it be done?

后端 未结 5 2094
暖寄归人
暖寄归人 2021-01-12 03:28

my problem with vsprintf is that I can not obtain input arguments directly, I have to first get inputs one by one and save them in void**, then pas

5条回答
  •  滥情空心
    2021-01-12 04:07

    If the problem you're trying to solve is inserting passing arbitrary types to a function in va_list style, then, consider using union:

    #include 
    #include 
    
    union ARG
    {
        int d;
        char* s;
        double f;
    };
    
    int main()
    {
        printf("%d %s %f \n", 1, "two", 3.1415 );
        // Output: 1 two 3.141500
    
        char format[ 1024 ] = "%d %s %f\n";
        ARG args[ 5 ] = { };
        args[ 0 ].d = 1;
        args[ 1 ].s = "two";
        args[ 2 ].f = 3.1415;
        printf( format, args[ 0 ], args[ 1 ], args[ 2 ], args[ 3 ], args[ 4 ] );
        // Output: 1 two 3.141500
    
        return 0;
    }
    

    Some things you'll note about my solution:

    • No attempt is made to produce the correct number of arguments. i.e. I oversupply the arguments, but, most functions will look at the first parameter to determine how to handle the rest (i.e. format)
    • I didn't bother dynamically create the format, but, it is a trivial exercise to build a routine that dynamically populates format and args.

    Tested this on: - Ubuntu, g++ - Android NDK

    I did some more testing, and, confirmed @PeterCoordes comments about this answer not working for double precision.

提交回复
热议问题