[英]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.