5

There is a function:

void some_function(int id,...);

question: is there a way to wrap this function? It means to get something like this:

void wrapped_some_function(int id,...)
{
   //do smth
   some_function(id,...);
}
2r2w
  • 1,384
  • 1
  • 12
  • 29
  • http://stackoverflow.com/questions/9329440/process-va-args-in-c – BoBTFish Feb 22 '12 at 11:30
  • possible duplicate of [Forward an invocation of a variadic function in C](http://stackoverflow.com/questions/150543/forward-an-invocation-of-a-variadic-function-in-c) – sth Feb 22 '12 at 11:58
  • @sth little difference: I need to wrap a function so I can't modify source function. And i got my answer – 2r2w Feb 22 '12 at 13:42

5 Answers5

5

With gcc, __builtin_apply_args and __builtin_apply, documented here, can do it.
For standard C, there's no way (what other answers suggest can work, but it isn't 100% what you ask for).
But if there's a variation of some_function that gets va_list (like vprintf is a variation of printf), you can use it.

ugoren
  • 16,023
  • 3
  • 35
  • 65
5

Since this is also tagged C++: C++11 ftw.

#include <utility> // forward

template<class... Args>
void wrapped_some_function(int id, Args&&... args)
{
   //do smth
   some_function(id, std::forward<Args>(args)...);
}
Xeo
  • 129,499
  • 52
  • 291
  • 397
1

If your compiler supports variadic macros maybe you could use that?

#define wrapped_some_function(id, ...)    \
    do {                                  \
        /* Do something here... */        \
        some_function(id, __VA_ARGS__);   \
    } while (0)
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

I assume your wrapper function doesn't "know" the actual number of arguments passed (and their types) at compile-time, otherwise you could just retrieve them and call the wrapped function.

Then this is solvable only by using inline assembler (hence - platform-dependent solution). This also depends on how exactly do you want to wrap your function, do you need to reserve the stack for your wrapper (i.e. you don't need local function variables) and etc.

valdo
  • 12,632
  • 2
  • 37
  • 67
0

In general case there is no way to do it, and because there is no way the creator of some_function should have provided similar function vsome_function that does not take ..., but a va_list. Function with variable argument list must have its counter part, a function with va_list. Consider pairs of functions (printf, vprintf), (sprintf, vsprintf), (CString::Format, CString::FormatV).

Dialecticus
  • 16,400
  • 7
  • 43
  • 103