如何使一个函数接受其他函数作为参数(没有已知参数) [英] How to make a function which receive other function as param (with no known parameters)
问题描述
以前,我问过如何用C语言编写一个将函数作为参数接收的函数.我得到了一个答案链接到问题,但是此解决方案基于参数函数的参数.我的意思是:
Previously I asked How to make a function which receive a function as param in C language. I get an answer Link to the question but this solution is based on the parameters of argument's function. I mean:
int functionToPassAsParameter (int arg1, int arg2){
// do something
}
int functionWhichReceiveFunction (int (*f)(), int arg1, int arg2){
// do something
f(arg1, arg2);
// do something
}
// How to call the function
functionWhichReceiveFunction (&functionToPassAsParameter, 1, 2);
我想要类似的东西
int functionToPassAsParameter (int arg1, int arg2){
// do something
}
int functionWhichReceiveFunction ( f() ){
// do something
f();
// do something
}
// How to call the function
functionWhichReceiveFunction ( functionToPassAsParameter(arg1, arg2) );
因此,当我调用函数时,我传递了正确的参数,但是当我定义接收其他函数的函数时,我没有指定要发送给它的参数.这有可能吗?
So, when I call the function, I pass the correctly params but when I define the function which receive the other function I do not specify which params I will send to it. Is that possible to make?
我想实现将任何功能传递给
functionWhichReceiveFunction
.像这样:
EDIT 1: I wanna achieve pass any function to
functionWhichReceiveFunction
. Something like:
int function_a (int param1, int param2) { /* Do something */ };
void function_b (char *arg1) { /* Do something */ };
// Call the function with two differents functions regardless return type nor params
int x = functionWhichReceiveFunction ( function_a(param1, param2) );
functionWhichReceiveFunction ( function_b(arg1) );
推荐答案
定义要传递的函数,以使用void *
作为参数.这样,调用给定函数的函数就不需要了解有关参数的任何特定信息:
Define the function to be passed to take a void *
as a parameter. That way the function that calls the given function doesn't need to know anything specific about the parameters:
struct params1 {
int arg1;
int arg2;
};
struct params2 {
char *arg1;
char *arg2;
};
int functionToPassAsParameter (void *param){
struct params1 *args = params;
// do something
}
int otherFunctionToPassAsParameter (void *param){
struct params2 *args = params;
// do something
}
int functionWhichReceiveFunction (int (*f)(void *), void *args) {
// do something
f(args);
// do something
}
struct params1 p1 = { 1, 2 };
functionWhichReceiveFunction (&functionToPassAsParameter, &p1);
struct params2 p2 = { "abc", "def" };
functionWhichReceiveFunction (&otherFunctionToPassAsParameter, &p2);
这篇关于如何使一个函数接受其他函数作为参数(没有已知参数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!