Reputation: 10894
Recently I wanted to implement a printf
wrapper. After some search I found the vprintf
is good for this need:
void my_printf(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
}
But is it possible to implement such a wrapper for printf
or any other similar functions with variable arguments instead of va_list
?
(I mean, what if they don't provide a v
version?)
Since some commenter didn't fully capture my idea, I'd better elaborate it.
Suppose you have a plain printf
function as in the C library.
Some one gives you a fmt
string "%d %u %f"
, and corresponding inputs.
Now you want to write a function similar to printf
, but with all %f
replaced by %.2f
.
Of course you can use two statements to finish the task:
replace(fmt, "%f", "%.2f");
printf(fmt, inputs);
But if you use this function many times, probably you want to have a wrapper to save some time.
A macro can finish this task, of course. But is it possible without a macro, like:
void myprintf(fmt, ...)
{
replace(fmt, "%f", "%.2f");
printf(fmt, inputs);
}
The problem here is that you don't know how to feed the inner printf
with the arguments ...
of myprintf
.
Hope this clarifies.
Upvotes: 2
Views: 5365
Reputation: 148
If the variadic function was created by you and you need the wrapper to be a function as well (as in my case; I needed a pointer to the wrapper), then you can move the implementation of that function into a macro that takes (fmt, args) where args is va_list
.
You can then use this macro to implement wrapper functions.
Upvotes: 0
Reputation: 78903
If you just want to use this to prepend an string to the output or so, you could use a variadic macro.
#define MYPRINT(...) printf("toto has: " __VA_ARGS__)
in that simple example this suppposes that format that you pass in is a string literal, so this is a bit restricted. But I hope you see the pattern how to use such simple macro wrappers.
Upvotes: 3
Reputation: 1
There is no portable way to construct a call to a variadic function when the API don't offer you functions with va_list
parameter.
However, you could [ab]use the libffi for that purpose, by constructing the variadic call and doing it.
Upvotes: 2