0

I have a function log_message it takes variable arguments.

log_message(int level, char *fmt, ...)

now before calling this(log_message) function i have to add new function(_log_message), and new function will call log_message.

_log_message(int level, char *fmt, ...)

new function is also same. when _log_message will call log_message it will convert variable input to va_list. Now i have va_list, i don't wanna change the original one, is there any way to change back to variable input, so i will able to call the original one(log_message).

Arun Gupta
  • 810
  • 2
  • 9
  • 26

1 Answers1

5

No, there is no way to turn a va_list back into a list of arguments.

The usual approach is to define a base function which takes a va_list as an argument. For example, the standard C library defines printf and vprintf; the first is a varargs function and the second has exactly the same functionality but takes a va_list instead. Similarly, it defines fprintf and vfprintf. It's trivial to define printf, vprintf and fprintf in terms of vfprintf:

int fprintf(FILE* stream, const char* format, ...) {
  va_list ap;
  va_start(ap, format);
  int n = vfprintf(stream, format, ap);
  va_end(ap);
  return n;
}

int vprintf(const char* format, va_list ap) {
  return vfprintf(stdout, format, ap);
}

int printf(const char* format, ...) {
  va_list ap;
  va_start(ap, format);
  int n = vprintf(format, ap);
  va_end(ap);
  return n;
}

(Similarly for the various exec* functions, which come in both va_list and varargs varieties.)

I'd suggest you adopt a similar strategy.

rici
  • 234,347
  • 28
  • 237
  • 341
  • Why it's not possible? it looks like a Naive question but still i want to know. – Arun Gupta Jul 24 '14 at 07:21
  • It is not possible because there are no routines or syntax for handling it. c_decl requires the caller to push the items into the stack. If it is a variable number, how does it know how many to push in? At the end, the caller is responsible for unstacking - again, if it doesn't know how many there are, how will it know how many there are to unstack? – cup Jul 24 '14 at 07:43
  • 2
    @Merom Simply because the standard defines no reliable way for doing so. The stack during the call looks completely different. Under usual platforms, `...` is passed successively on the stack, and `va_list` is a kind of pointer to such a succession of `...` arguments. And they simply provided no way to put them back onto the stack. – glglgl Jul 24 '14 at 07:43