简体   繁体   English

调用泛型函数时如何有效处理参数

[英]How to effectively handle the arguments when calling a generic function

I am trying to figure out what's the most efficient way to solve the following problem using C. 我试图找出使用C解决以下问题的最有效方法是什么。

Let's consider a generic function 让我们考虑一个通用函数

void foo(int x, int y);

Normally, the function would be called as follow: 通常,该函数的调用方式如下:

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

However, in my code I must use a genericCall function declared as: 然而,在我的代码我必须使用genericCall声明为函数:

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

So for example, in order to execute the code above I must introduce an auxiliary function and a struct: 因此,例如,为了执行上面的代码,我必须引入一个辅助函数和一个结构:

// 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));

As you can imagine this approach does not scale very well: every time I want to call a different function I must add a lot of code that does very little apart from handling the arguments. 如您所见,这种方法的伸缩性不是很好:每次我想调用一个不同的函数时,我都必须添加很多代码,这些代码除了处理参数外几乎没有什么作用。

Is there a way to do the same without replicating all the code? 有没有一种方法可以做到不复制所有代码?

Thanks! 谢谢!

No, there is not much more that you can do. 不,您无法做更多的事情。 Your generic interface doesn't permit to pass type information, and if you have a function with multiple arguments that you want to pass, you have to place them to be accessible through a single pointer. 通用接口不允许传递类型信息,并且如果您有一个要传递多个参数的函数,则必须将它们放置为可通过单个指针访问。

This is eg how coding with thread interfaces (POSIX or C11) usually works. 例如,这就是通常使用线程接口(POSIX或C11)进行编码的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM