• 和菜鸟一起学c之回调函数简单实例


            回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用为调用它所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。

           上面是百度百科的定义,下面还是看个简单的例子吧。

     

    #ifdef __cplusplus
    extern "C" {
    #endif
    /*******************************************************************************/
    typedef int (*TEST_CALLBACK_FUNC)(int handle);/*定义函数指针,指向函数入口地址*/
    /*******************************************************************************/
    #ifdef __cplusplus
    }
    #endif
     
     
    #include <stdio.h>
     
    static TEST_CALLBACK_FUNC Notify = NULL;
     
    typedef struct 
    {
           int a;
           int b;
    }addnum; //加法运算中的两个数
     
    int flag = 0; //通知事件
     
    static int test_callback(TEST_CALLBACK_FUNC add, int handle)
    {
           int ret = -1;
           
           printf("\n{test_callback} start\n"); 
           
           if(add != NULL)
                  ret = 0;
           
           if(flag)  //这里如果flag为真,那么就说明有通知事件,让其做加法运算
           {
                  flag = 0; 
                  Notify = add;
                  (Notify)(handle); //调用函数
           }
           
           printf("{test_callback} end\n\n");  
           
           return ret;
    }
     
    static int myadd(int handle)//加法运算,被回调的函数
    {
           addnum *num;
           
           num = (addnum*)handle; //获取要做加法的两个数
           
           printf("\n{myadd} start\n");
           
           printf("%d+%d=%d\n",num->a, num->b, num->a+num->b);    
           
           printf("{myadd} end\n\n");
           
           return 0;
    }
     
    int main(void)
    {
           addnum num;
           int handle;
           
           printf("{main} start\n");
           
           scanf("%d%d", &num.a, &num.b);
           handle = (int)(&num); //获取数据地址
           
           if(test_callback(myadd, handle) != 0)//假设这个callback是一个线程在跑
                  return -1;
           
           flag = 1;  //假设这里的flag置1是其他线程设置的
           
           if(test_callback(myadd, handle) != 0)
    
                  return -1;
           printf("{main} end\n"); 
           
           return 0;  
    }
    
    


    运行结果若如下所示

    /*
    {main} start
    5 6
     
    {test_callback} start
    {test_callback} end
     
     
    {test_callback} start
     
    {myadd} start
    5+6=11
    {myadd} end
     
    {test_callback} end
    
     
    {main} end
    */
    
    

            首先进入main函数,输入了要做加法的两个数,把这个结构体指针传入callback函数中,然后判断有没有事件,即flag是否为1,第一次是0,所以没有回调,第二次flag置为1了,所以调用了加法运算。

    这个是简单的例子,以前看到android中有好多的回调,不是很明白,现在反过来去看看,顿时觉得清晰多了。

  • 相关阅读:
    区块链基础语言(十二)——Go语言跳转语句
    区块链基础语言(十一)——Go语言循环语句
    区块链基础语言(十)——Go语言选择语句
    区块链基础语言(九)——Go语言运算符
    区块链技术语言(八)——Go语言常量
    区块链基础语言(七)——Go语言变量
    区块链基础语言(六)——Go语言数据类型
    区块链基础语言(五)——Go语言结构
    区块链基础语言(四)——Go语言工程管理
    人生苦短,我用 Python
  • 原文地址:https://www.cnblogs.com/wuyida/p/6300045.html
Copyright © 2020-2023  润新知