C - 具有动态参数数量的调用函数

时间:2015-03-27 15:19:59

标签: c arguments

我有一个具有特定数量参数的C函数(不是varargs函数)。例如:

void testfunction(int a, int b, int c);

这个功能是一个黑盒子,所以我无法修改它。

在main函数中,我有一个数组,其中包含我想传递给“testfunction”的所有参数。例如:

void main() {
    int args[] = {1, 2, 3};
    ...
}

假设我事先不知道我的“testfunction”会接受的参数数量(因为这个函数可以改变,取决于我想测试的函数),我怎么称之为“testfunction”与数组中的参数动态定义?

我在Ruby方面有一些经验,它相当于

def test(a, b, c)
    ...
end
array = [1,2,3]
test(*array)

非常感谢你!

1 个答案:

答案 0 :(得分:0)

嗯,你无法完全达到你想要的效果,但是,如果你想要传输的参数数量有限,你可以接近。你也会失去一些类型的安全性。以下是如何做到这一点:

#include <stdio.h>
#include <stdlib.h>

typedef void (*tf_t)(); // `tf_t` can accept any number of arguments

void tf1(int a) { printf("tf1: %d\n", a); }
void tf2(int a, int b) { printf("tf2: %d, %d\n", a,b); }
void tf3(int a, int b, int c) { printf("tf3: %d, %d, %d\n", a,b,c); }

void call(tf_t tf, int args[], unsigned n)
{
    switch (n) {
    case 0: tf(); break;
    case 1: tf(args[0]); break;
    case 2: tf(args[0], args[1]); break;
    case 3: tf(args[0], args[1], args[2]); break;
    default: puts("Can't handle more than 3 arguments"); abort(); break;
    }
}

int main()
{
    int args[] = { 1, 2 };
    call(tf2, args, sizeof args / sizeof args[0]);
    return 0;
}

当然,如果您将tf3传递给call(),它会将垃圾打印为第三个数字,但这是您支付的价格。

原则上,你不应该做这样的事情,因为调用约定可能会有很多问题,但实际上,它很可能会有效。