开发者

Is it possible to write a varargs function that sends it argument list to another varargs function? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

C Programming: Forward variable argument list.

What I'd like to do is send data to a loggi开发者_StackOverflow社区ng library (that I can't modfify) in a printf kind of way.

So I'd like a function something like this:

void log_DEBUG(const char* fmt, ...) {
   char buff[SOME_PROPER_LENGTH];
   sprintf(buff, fmt, <varargs>);
   log(DEBUG, buff);
}

Can I pass varargs to another vararg function in some manner?


You can't forward the variable argument list, since there's no way to express what's underneath the ... as a parameter(s) to another function.

However you can build a va_list from the ... parameters and send that to a function which will format it up properly. This is what vsprintf is for. Example:

void log_DEBUG(const char* fmt, ...) {
   char buff[SOME_PROPER_LENGTH];
   va_list args;
   va_start(args, fmt);
   vsprintf(buff, fmt, args);
   va_end(args);
   log(DEBUG, buff);
}


You can send it to another function that takes a va_list as an argument. There is no other way, short of resorting to hand crafted asm, or doing some kind of horrifying guessing game to figure out the 'number' of parameters.

This would work:

void log_DEBUG(const char* fmt, ...)
{
  va_list va;
  va_start(va,fmt);
  char buff[blah];
  vsprintf(buff,fmt,va);
  log(DEBUG,buff);
  va_end(va);
}

Basically, whenever you write a function that takes ..., you should write another version that takes a va_list - its the polite thing to do if you want to enable this type of chaining call.


This is why you have the vprintf family of functions.


For your specific requirement, you can use vsprintf. My C/C++ is too rusty to recall if there's a straightforward way to do it when the other function isn't designed for it (without getting into ugly stack manipulation), but I tend to think not.


Not in standard C++.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜