首页 > 解决方案 > 将一组变量参数从一个函数传递给 C 中的宏

问题描述

我看到这个链接将变量参数传递给另一个接受变量参数列表的函数。将它传递给宏的语法是什么?

#include <stdarg.h>
#define exampleW(int b, args...) function2(b, va_args)
static void exampleV(int b, va_list args);

void exampleB(int b, ...)
{
    va_list args;
    va_start(args, b);
    exampleV(b, args);
    //also pass args to a macro which takes multiple args after this step
    ??? [Is it exampleW(b, ##args)]
    va_end(args);
}

static void exampleV(int b, va_list args)
{
    ...whatever you planned to have exampleB do...
    ...except it calls neither va_start nor va_end...
}

标签: c

解决方案


这是不可能的。宏在编译时扩展,因此它们的参数需要在编译时,在使用宏的地方知道。函数的参数exampleB通常在运行时才知道。即使在许多情况下,在编译函数调用时参数可能是已知的,但它可能位于不同的源文件中,这对您使用该源文件中的宏没有帮助。

您需要:

  • 而是exampleB调用一个类似的函数vfunction2,该函数被 function2重写以获取va_list参数

  • 重新实现exampleB为宏

  • 如果 的参数的可能组合数量有限exampleB,则编写代码分别处理所有情况:

if (b == TWO_INTS) {
    int i1 = va_arg(args, int);
    int i2 = va_arg(args, int);
    exampleW(i1, i2);
} else if (b == STRING_AND_DOUBLE) {
    char *s = va_arg(args, char *);
    double d = va_arg(args, double);
    exampleW(s,d);
} else // ...
  • 做一些不可移植的事情来调用function2与传递给相同的参数的函数exampleB,例如使用汇编语言技巧或 gcc 的__builtin_apply()

推荐阅读