将不同类型的参数与 va_list 分开

Separate different types of arguments from va_list

我正在尝试编写一个宏来获取信息并将该信息发送到另一个函数,方法是将原始 va_list 拆分为字符串,另一个 va_list 从原始字符串中生成。

下面是我的代码。

调用宏

/* Usage */
PRINT_LOG("Format log = %d, %f, %s", 1, 2.7, "Test");

下面是我的代码

/* my includes here */
#include <stdarg.h>

void printInfo(int level, const char *debugInfo, ...); /* defined in 3rd party API */

void formatLogs(int level, ...);

#define PRINT_LOG(...) formatLogs(0, __VA_ARGS__)

void formatLogs(int level, ...)
{
  va_list args;
  va_start(args, level);

  /* get the first argument from va_list */
  const char *debugString = va_arg(args, const char*);

  /* here I want to get the rest of the variable args received from PRINT_LOG*/
  va_list restOfArgs = ???????; /* restOfArgs should be 1, 2.7, "Test" */

  /* Below I want to send the rest of the arguments */
  printInfo(level, debugString, args);
  va_end(args);
}

是否可以将 va_list 的某些部分作为 va_list 发送到另一个函数?如果可以,我该怎么做?

非常感谢您。

根据您问题中的代码,最简单的做法是像这样重新定义宏:

#define PRINT_LOG(s, ...) printInfo(0, s, __VA_ARGS__)

并且完全跳过中间函数。因为你想做的事情不能那样做。

, ...) 变量参数省略号 不是 va_list。在调用 va_start 之前,传递给函数的可变参数不会实现为 va_list。要将 va_list 作为函数参数传递,函数必须在其签名中包含 va_list,如下所示:

int vprintf(const char *format, va_list argList);