Search code examples
cdynamicargumentswrappervxworks

how do I correctly wrap a function with dynamic number of args up?


I want to wrap a function that looks like: void dbgLog (tDbgLog *dbg, const char *mod, const char *func, const char *format,...) and makes use of vsnprintf() to make it accessible by calling another function, I've tried the following but that doesn't seem to work correctly:

void pMonDbgLog(const char *mod, const char *func, char* fmt, ...)
{
    va_list args;
    va_start(args,fmt);
    dbgLog(g_pdbg,mod,func,fmt,args);
    va_end(args);
}

and I again make this accessible through the following macro:#define gDbgLog(fmt,...) pMonDbgLog(MODULE_NAME,__FUNCTION__,fmt, ##__VA_ARGS__) but turns out that my arguments get messed up. Why is this, I'm wondering?


Solution

  • There is no portable way to pass the arguments of a vararg function to another vararg function. You can implement dbgLog by calling a function vdbgLog defined as:

    void vdbgLog(tDbgLog *dbg, const char *mod, const char *func,
                 const char *format, va_list ap) {
        /* your implementation goes here */
    }
    
    void dbgLog(tDbgLog *dbg, const char *mod, const char *func, const char *fmt, ...) {
        va_list args;
        va_start(args, fmt);
        vdbgLog(dbg, mod, func, fmt, args);
        va_end(args);
    }
    

    And you can call this function vdbgLog directly from pMonDbgLog as well:

    void pMonDbgLog(const char *mod, const char *func, char *fmt, ...) {
        va_list args;
        va_start(args, fmt);
        vdbgLog(g_pdbg, mod, func, fmt, args);
        va_end(args);
    }