gpt4 book ai didi

c - 将不同类型的参数与 va_list 分开

转载 作者:太空宇宙 更新时间:2023-11-04 03:11:16 28 4
gpt4 key购买 nike

我正在尝试编写一个宏来获取信息并将该信息发送到另一个函数,方法是将原始 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_start 之前,传递给函数的可变参数不会实现为 va_list。要将 va_list 作为函数参数传递,函数必须在其签名中包含 va_list,如下所示:

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

关于c - 将不同类型的参数与 va_list 分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56161430/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com