繁体   English   中英

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

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

我试图找出使用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)进行编码的方式。

暂无
暂无

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

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