Wrapping Printf

Hey Folks, I’m trying to wrap the printf function using variadic functions. However, it doesn’t seem to be passing the format parameters along. Wondering if anyone has forwarded printf?

void PeripheralAccess::UsbSerialIO::printf(const char* format, ...)
{
    va_list argptr;
    va_start(argptr, format);
    Serial.printf(format, argptr);
    va_end(argptr);
}

When I call it with UsbSerialIO.printf("%d:", some_int) it will print “:” without formatting the integer.
I’ve looked at the DeviceOS codebase, and it doesn’t look like there is a vprintf available. Please correct me if I’m wrong, my look was hasty.

I can’t use a variadic template, because the function definition cannot be placed in an H file. Wracking my brain for a way to wrap printf in a generic way and coming up with nothing.

Cheers!

There is no Print::vprintf() function, as you noted. What I would do is duplicate most of what’s in the implementation of printf_impl. You’ll see that it calls vsnprintf internally, so just modify the code to take a va_list as a parameter instead of using va_start and va_end.

size_t Print::printf_impl(bool newline, const char* format, ...)
{
    const int bufsize = 20;
    char test[bufsize];
    va_list marker;
    va_start(marker, format);
    size_t n = vsnprintf(test, bufsize, format, marker);
    va_end(marker);

    if (n<bufsize)
    {
        n = print(test);
    }
    else
    {
        char bigger[n+1];
        va_start(marker, format);
        n = vsnprintf(bigger, n+1, format, marker);
        va_end(marker);
        n = print(bigger);
    }
    if (newline)
        n += println();
    return n;
}
1 Like

Beware of a stack overflow with this implementation.

Right, generally I size buffers at 256 bytes, and chunk output if the input buffer is longer.
Thanks! I’ll see what I can do with this! My current workaround is to break the print functions up from printf into two print calls. Not the greatest, but should work while I make sure I can write a decent implementation of your suggestions rickkas!

Thanks folks, this is very helpful.