在可变参数函数中使用可变参数函数
Use a vararg function in a vararg function
我想在可变参数函数中调用可变参数函数。该代码没有给出错误,但结果值不正确。正确的做法是什么?
#include <stdarg.h>
void SecondFunction (int count, ...) {
va_list args;
va_start(args, count);
AddValues(count, args);
va_end(args);
};
void AddValues(int count, ...) {
va_list args;
va_start(args, count);
for(int i=count; i--; )
processItem(va_arg(args, void*));
va_end(args);
}
仔细阅读stdarg(3) or the C11 standard n1570 and documentation on variadic functions in C.
您需要使用 va_list
并且可能 va_copy
另请阅读 calling conventions of your particular C implementation. There is a detailed wikipedia page about x86 calling conventions,它激发了标准的措辞。
为了获得灵感,请查看 vprintf(3). In practice their implementation in open source C standard libraries such as musl-libc 等函数,您应该会感兴趣。
理论上(在现实生活中,在 一些 案例中 Linux 最近 GCC,作为内置函数)vprintf
可以在编译器中实现。但是既然你可以获取它的地址并将它传递给你的一些函数,它也必须是 C 标准库中的一个函数。
这行不通,但您可以创建一个使用 va_list
参数的类似函数。这正是 vsyslog
和 vprintf
等函数存在的原因。最简单的形式:
void vAddValues(int count, va_list args) {
int i;
for (i = count; i--; )
processItem(va_arg(args, void *));
}
我想在可变参数函数中调用可变参数函数。该代码没有给出错误,但结果值不正确。正确的做法是什么?
#include <stdarg.h>
void SecondFunction (int count, ...) {
va_list args;
va_start(args, count);
AddValues(count, args);
va_end(args);
};
void AddValues(int count, ...) {
va_list args;
va_start(args, count);
for(int i=count; i--; )
processItem(va_arg(args, void*));
va_end(args);
}
仔细阅读stdarg(3) or the C11 standard n1570 and documentation on variadic functions in C.
您需要使用 va_list
并且可能 va_copy
另请阅读 calling conventions of your particular C implementation. There is a detailed wikipedia page about x86 calling conventions,它激发了标准的措辞。
为了获得灵感,请查看 vprintf(3). In practice their implementation in open source C standard libraries such as musl-libc 等函数,您应该会感兴趣。
理论上(在现实生活中,在 一些 案例中 Linux 最近 GCC,作为内置函数)vprintf
可以在编译器中实现。但是既然你可以获取它的地址并将它传递给你的一些函数,它也必须是 C 标准库中的一个函数。
这行不通,但您可以创建一个使用 va_list
参数的类似函数。这正是 vsyslog
和 vprintf
等函数存在的原因。最简单的形式:
void vAddValues(int count, va_list args) {
int i;
for (i = count; i--; )
processItem(va_arg(args, void *));
}