调用具有未知数量的参数的可变函数 [英] Calling a variadic function with an unknown number of parameters
问题描述
说我有一个函数,它接受可变数量的参数:我想从其他地方调用这个函数,构建参数列表,但不知道提前需要多少参数。
Say I have a function that takes a variable number of parameters: I want to call this function from somewhere else, building the list of parameters, but without knowing in advance how many parameters I'll need.
抱歉,解释不太清楚,希望这个程式码能让我的问题更清楚:
Sorry that's not well explained, hopefully this code makes my question clearer:
void foo(int n, ...) {
va_list vl;
va_start(vl,n);
for (int i = 0; i<n; i++) {
// Do something to each passed variable
}
}
该函数正在从这个函数调用:
That function's being called from this one:
void bar(int howManyParams) {
// Here I want to call foo() with howManyParams parameters
// (values are irrelevant for the question)
//
// I.e. for howManyParams = 1, we should call foo(0)
// for howManyParams = 2, we should call foo(0,0)
// for howManyParams = 3, we should call foo(0,0,0)
// etc.
//
}
推荐答案
实际上在运行时构建一个可变长度的参数列表 - 这是我确定你想要做的 - 是很棘手。
Actually building a variable-length argument list at run-time -- which is what I'm pretty sure you're trying to do -- is pretty tricky. There's no way to do it at all in Standard C, but there are various tricks you can try.
也许最好的是外部函数接口库在 http://sourceware.org/libffi/ 。
Perhaps the best is the "Foreign Function Interface Library" at http://sourceware.org/libffi/ .
另请参阅C常见问题列表中的问题15.13: http://c-faq.com/varargs/invvarargs .html
See also question 15.13 in the C FAQ list: http://c-faq.com/varargs/invvarargs.html
另请参阅以前的Stackoverflow问题:
使用未知参数的后期绑定
如何通过在C中传递多个参数的指针调用函数?
See also these previous Stackoverflow questions:
C late binding with unknown arguments
How to call functions by their pointers passing multiple arguments in C?
这篇关于调用具有未知数量的参数的可变函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!