首页 > 解决方案 > 从 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 发送到另一个函数?如果是这样,我该怎么做?

非常感谢您提前。

标签: cvariadic-functions

解决方案


根据您问题中的代码,最简单的方法是重新定义宏,如下所示:

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

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

, ...)变量参数省略号不是. va_list传递给函数的变量参数不会被实现为va_list直到va_start被调用。要将 ava_list作为函数参数传递,函数va_list的签名中必须有 a,如下所示:

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

推荐阅读