简体   繁体   English

将一组变量 arguments 从一个 function 传递到 C 中的宏

[英]Passing a variable set of arguments from one function to a macro in C

I see this link Passing variable arguments to another function that accepts a variable argument list .我看到这个链接将变量 arguments 传递给另一个接受变量参数列表的 function What is the syntax to pass it to a macro as well?将它传递给宏的语法是什么?

#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...
}

This is not possible.这是不可能的。 Macros are expanded at compile time, and so their arguments need to be known at compile time, at the point where the macro is used.宏在编译时被扩展,因此它们的 arguments 需要在编译时,在使用宏的地方知道。 The arguments to your function exampleB are in general not known until run time. arguments 到您的exampleB示例B 通常直到运行时才知道。 And even though in many cases the arguments may be known when the call to the function is compiled, that may be in a different source file, which does not help you with macros in this source file.即使在许多情况下 arguments 在编译对 function 的调用时可能是已知的,这可能位于不同的源文件中,这对您使用此源文件中的宏没有帮助。

You'll need to either:您需要:

  • have exampleB instead call a function like vfunction2 which is function2 rewritten to take a va_list parameterexampleB改为调用 function 就像vfunction2一样,这是function2重写以获取va_list参数

  • reimplement exampleB as a macroexampleB重新实现为宏

  • if there are a finite number of possible combinations of arguments to exampleB , then write code to handle all the cases separately:如果 arguments 到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 // ...
  • do something non-portable to call the function function2 with the same arguments as were passed to exampleB , eg with assembly language tricks, or gcc's __builtin_apply() .做一些不可移植的事情来调用 function function2 2,使用与传递给exampleB相同的 arguments ,例如使用汇编语言技巧或 gcc 的__builtin_apply()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM