The va_list extension is portable

I have a third-party function with a signature:

int secretfoo(int numargs, ...);

I can call it directly, but what I really want is to wrap it with my function, which will add additional arguments to it.

Suppose that a simple case of integers: I want to call secretfoo(2, 10, 20)have been translated as follows: when I see the argument 10, to duplicate it and make a call: secretfoo(3, 10, 10, 20). I want to do this in a wrapper:

int foowrapper(int numargs, ...);

This shell parses argumetns and calls secretfooas described above.

Can this be done with the ability to be carried with va_list/ va_argetc? Any other way?

+3
source share
2 answers

, , . .

, , foowrapper "", secretfoo.
:

int foowrapper(int numarg, ...)
{
  va_list args
  int newargs[numarg*2]; /* worst case allocation */
  int numnewargs = 0;

  /* Extract the arguments */
  va_start(numarg, args);
  for (int i=0; i<numarg; i++)
  {
    newargs[numnewargs++] = va_arg(args, int);

    /* duplicate value 10 as you encounter it */
    if (newargs[numnewargs-1] == 10)
    {
      newargs[numnewargs++] = 10;
    }
  }

  /* Forward to the secretfoo function */
  switch (numnewargs)
  {
  case 0: return secretfoo(0);
  case 1: return secretfoo(1, newargs[0]);
  case 2: return secretfoo(2, newargs[0], newargs[1]);
  /* etc... */
  }
}
+2

, . stdarg.h " " ( C): va_start, va_end, va_arg va_copy. va_list , .

vsecretfoo(int, va_list), (vprintf ..).

+1

Source: https://habr.com/ru/post/1770307/


All Articles