回调函数学习1

Posted on   KobeBLN  阅读(12)  评论(0编辑  收藏  举报

//test.h  头文件

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#include <sys/types.h>

typedef void (*pf_callbakck)(int a);

typedef struct Compute_ST

{

       int index;

       pf_callbakck function;

}Compute_ST;

 

int Registe_Callback_Fun(Compute_ST *registed_fun);

 

void mgmtb_fun(int num);

 

 

/*A Module*/

/*TestA.c 文件

实现回调函数*/

#include "test.h"

 

void callback_fun(int event)

{

       switch(event)

       {

              case 1:

                     {

                            printf("ABCDEFG.\n");                       

                     }     

                     break;

              default:

                     {

                            printf("New event, %d.\n",event);

                     }

       }

}

 

void main()

{

       int event = 0;

       Compute_ST ptr_compute;

      

       ptr_compute.index = 1;

       ptr_compute.function = callback_fun;

       //注册回调函数

       if(-1 == Registe_Callback_Fun(&ptr_compute))

       {

              printf("Registe failed.\n");

       }

      

       for(;;)

       {

              printf("Enter number:");

              scanf("%d", &event);

             

              if(event == 0)

              {

                     return;

              }

              //触发事件

              mgmtb_fun(event);

       }

       return;

}

 

 

/*B Module

testB.c文件

实现注册函数

实现事件触发回调*/

#include "test.h"

pf_callbakck g_ptrfun;

 

int Registe_Callback_Fun(Compute_ST *registed_fun)

{

       if(1 != registed_fun->index)

       {

              printf("Registe failed.\n");

              return -1;

       }

       g_ptrfun = registed_fun->function;

}

 

void mgmtb_fun(int event)

{

       g_ptrfun(event);

}

点击右上角即可分享
微信分享提示