【C语言】callback函数,回调函数简单例子

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

typedef void (*ota_start_fun)(int *num1,int *num2);
typedef void (*ota_stop_fun)(int *num1,int *num2);
typedef struct callback_ctl{
	ota_start_fun ota_start;
	ota_stop_fun ota_stop; 
}callback_ctl_t; 

static void ota_start(int *num1,int *num2);
static void ota_stop(int *num1,int *num2);
static void ota_start(int *num1,int *num2){
	int num3;
	num3 = *num1 + *num2;
	printf("~~~~~%d + %d = %d\n",*num1,*num2,num3);
} 
callback_ctl_t ota;
static void ota1(ota_start_fun ota_start_cb,ota_start_fun ota_stop_cb){
	ota.ota_start = ota_start_cb;
	ota.ota_stop = ota_stop_cb;
}
//回调函数体
static void ota_stop(int *num1,int *num2){
	
	int num3;
	num3 = *num1- *num2;
	printf("~~~~~%d + %d = %d\n",*num1,*num2,num3);
}

int main(int argc, char *argv[]) {
		
	int num1=5;
	int num2=3;
	ota1(ota_start,ota_stop);  //初始化回调函数,即将回调函数注册一下,放入一个全局变量。 
	ota.ota_start(&num1,&num2); //然后我就可以用这个结构体里面的这个回调函数变量来调用回调函数,并且传入参数。 
	ota.ota_stop(&num1,&num2);
	
	return 0;
}

 

在 C 语言中,callback 回调函数通常是指将一个函数指针作为参数传递给另一个函数,在该函数执行过程中会回调这个函数指针所指向的函数。这个回调函数可以用来实现一些特定的功能或者提供一些特殊的处理方式。 举个例子,假设你正在写一个网络应用程序,你需要在收到数据后对这些数据进行处理,但是你不知道具体的处理方式。这时候你可以定义一个 callback 函数,然后将这个函数指针作为参数传递给网络库中的函数。当网络库接收到数据后,就会回调这个 callback 函数,让你自由地处理这些数据。 下面是一个简单的示例代码: ```c #include <stdio.h> // 定义回调函数 void callback(int num) { printf("callback called with %d\n", num); } // 接收回调函数指针作为参数的函数 void call_with_callback(int num, void (*callback_func)(int)) { printf("call_with_callback called with %d\n", num); callback_func(num); // 调用回调函数 } int main() { // 将回调函数作为参数传递给 call_with_callback 函数 call_with_callback(100, callback); return 0; } ``` 在这个例子中,我们定义了一个名为 callback回调函数,并且定义了一个名为 call_with_callback函数,它接收一个整数和一个函数指针作为参数。在 main 函数中,我们将 callback 函数的指针作为参数传递给了 call_with_callback 函数。当 call_with_callback 函数被调用时,它会打印一些信息并且回调传递进来的函数指针,也就是执行 callback 函数。 需要注意的是,回调函数的类型必须和接收它的函数指针的类型一致,否则会导致编译错误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值