gpt4 book ai didi

c - 如何制作一个接收其他函数作为参数的函数(没有已知参数)

转载 作者:行者123 更新时间:2023-12-01 22:03:57 25 4
gpt4 key购买 nike

之前我问过如何在 C 语言中制作一个接收函数作为参数的函数。我得到一个答案Link to the question但是这个解决方案是基于参数函数的参数。我的意思是:

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

因此,当我调用该函数时,我传递了正确的参数,但是当我定义接收另一个函数的函数时,我没有指定我将发送给它的参数。可以做吗?


编辑 1:我想实现将任何函数传递给 functionWhichReceiveFunction。类似于:

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 * 作为参数。这样调用给定函数的函数就不需要知道任何关于参数的具体信息:

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

关于c - 如何制作一个接收其他函数作为参数的函数(没有已知参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52817011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com