c - 从 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_list
直到va_start
被调用。要将 ava_list
作为函数参数传递,函数va_list
的签名中必须有 a,如下所示:
int vprintf(const char *format, va_list argList);
推荐阅读
- php - Shell_exec 不执行 php 文件
- c++ - 访问嵌套的 ROS 消息
- keras - keras-vis 可视化显着性问题
- mysql - Sensenet:是否支持Mysql
- python - 在tensorflow python中替换值或创建张量掩码
- sql - 具有任意 LAG 的字段的 Postgres 历史依赖性
- python - 如何使用 PyCharm 在 2 台不同的机器上远程开发 python
- flask - Flask url_for 无法基于工作代码构建端点。问我要不要索引?
- bash - 使用 bash 确定目录 A 中不存在于目录 B 和 C 中的文件
- python - 根据聚合计数对 Pandas DataFrame 的行进行排序并随机获取一行