c语言 - 动态函数调用



如何在 C 中编写运行时动态函数调用,该函数调用在运行时需要可变数量的参数?

例如,考虑long sum(int count, ...);,它返回传递给它的(整数)参数的值的总和。

$./a.out 1 2 3 4
10
$./a.out 1 2 3 4 -5
5

你就是不能。唉,您只能使用给定数量的参数调用可变参数函数,而不能使用数组调用。

根据体系结构的不同,您可以将函数"在"可变参数函数"后面"调用 - 采用va_list的函数,前提是有一个,例如vprintf()"后面"printf()- 带有数组的地址,但这将是非常不可移植的。最好不要这样做。

最好是创建第三个函数,例如:

long asum(int count, long * arr)
{
long s = 0;
for (int i=0; i < count, i++) {
s += arr[i];
}
return s;
}
long vsum(int count, va_list ap)
{
long s = 0;
for (int i=0; i < count, i++) {
s += va_arg(ap, long);
}
return s;
}
long sum(int count, ...)
{
va_list ap;
va_start(ap, count);
long ret = vsum(count, ap);
va_end(ap);
return ret;
}

这个asum()将是你要打电话的那个。但这仅适用于将命令行参数转换为的中间数组。

也许额外的ssum()会有所帮助:

long ssum(int count, char ** arr)
{
long s = 0;
for (int i=0; i < count, i++) {
s += atol(arr[i]); // I am not sure if this is very portable; if not, choose another way.
}
return s;
}

main 的签名是

int main(int argc, char *argv[])

然后,您可以访问程序时提供的参数。

只需解析这些。做数学。吐出答案

是的,你可以!哦,堆栈溢出如何充满了这样的反对者。

看看这个库:http://www.dyncall.org

您可以构建动态参数列表,然后执行任意函数。