我正在尝试找出使用C解决以下问题的最有效方法。

让我们考虑一个通用函数

void foo(int x, int y);


通常,该函数的调用方式如下:

int a = 1;
int b = 2;
int c = foo(a, b);


但是,在我的代码中,我必须使用声明为的genericCall函数:

int genericCall(void (*func)(void *), void *args, size_t size);


因此,例如,为了执行上述代码,我必须引入一个辅助函数和一个结构:

// Define a struct to store the arguments
struct foo_args {
    int x;
    int y;
}

// Auxiliary function
void foo_aux(void *args) {
    struct foo_args *args;
    int x, y;

    // Unpack the arguments
    args = (struct foo_args *) args;
    x = args->x;
    y = args->y;

    // Invocation of the original function
    foo(x, y);
}

// ...

// Pack the arguments in the struct
struct foo_args args;
args.x = 1;
args.y = 2;

// Call the generic function
genericCall(foo_aux, &args, sizeof(struct foo_args));


如您所见,这种方法的伸缩性不是很好:每次我想调用一个不同的函数时,我都必须添加很多代码,这些代码除了处理参数外几乎没有什么作用。

有没有一种方法可以做到不复制所有代码?

谢谢!

最佳答案

不,您无法做更多的事情。通用接口不允许传递类型信息,如果您有一个要传递多个参数的函数,则必须将它们放置为可通过单个指针访问。

例如,这通常是使用线程接口(POSIX或C11)进行编码的方式。

关于c - 调用泛型函数时如何有效处理参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33023683/

10-17 02:42