c - 将一组变量参数从一个函数传递给 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...
}
解决方案
这是不可能的。宏在编译时扩展,因此它们的参数需要在编译时,在使用宏的地方知道。函数的参数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()
。
推荐阅读
- vue.js - Vue 单元测试:“您正在开发模式下运行 Vue。”?
- c++ - 向量引用运算符 [] 是否可以编写线程安全?
- asp.net-core - Infinispan .NET Core 客户端支持
- flutter - 如何将自定义文本复制到剪贴板?
- c# - 中间服务提供商的缺点
- php - PHP 执行命令“ng --version”
- sql - 将 HH:MM:SS 的 varchar 转换为分钟值
- anaconda - 在名为 sudo 的 bash 脚本中安装和使用 conda
- android - 编辑 ImageView 布局以围绕可绘制对象
- interface - Haxe:与接口匹配的函数参数