Lui*_*BOL 1 c pointers function-pointers function
我需要创建一个"函数调用者"函数:它接收泛型函数指针(void *)和可变数量的参数作为参数,它必须调用此函数,传递参数,并返回返回值的泛型指针.但是,这个入口函数指针可能指向任何类型的函数(具有任何返回类型),甚至指向具有常量参数的函数.它会是这样的:
void * function_caller(void * function_pointer, ...) {
void * returning_value;
// Call the function and get the returning value
return returning_value; // this returning value will be properly casted outside
}
Run Code Online (Sandbox Code Playgroud)
这样,以下代码将起作用:
int function1(int a, char b) {
// ...
}
void function2(float c) {
// ...
}
float function3() {
// ...
}
int main() {
int v1;
float v3;
v1 = *(int *) function_caller((void *) &function1, 10, 'a'); // Which would be equivalent to v1 = function1(10, 'a');
function_caller((void *) &function2, 3.0); // Which would be equivalent to function2(3.0);
v3 = *(float *) function_caller((void *) &function3); // Which would be equivalent to v3 = function3();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我知道我将不得不使用a va_list,但我不知道如何通过传递参数的指针调用该函数.
伙计们,任何想法?
坏消息是,这在C中是不可能的,即使在不可移植的C中也是如此.(GCC的扩展听起来像是在完成这项工作,但它们在一般情况下不起作用.)有必要编写汇编语言垫片.
好消息是,其他人已经为你写了垫片:看看libffi.(此处为手动.如果可以避免,请不要使用"闭包"API.)