zoukankan      html  css  js  c++  java
  • c语言回调函数

    C/C++之回调函数

    C语言中的回调函数(Callback Function)

    函数指针的概念:指针是一个变量,是用来指向内存地址的。一个程序运行时,所有和运行相关的物件都是需要加载到内存中,这就决定了程序运行时的任何物件都可以用指针来指向它。函数是存放在内存代码区域内的,它们同样有地址,因此同样可以用指针来存取函数,把这种指向函数入口地址的指针称为函数指针。

    用指针实现的hello word程序

     1   typedef void (*FP)(char* s); //函数指针声明
     2   void Invoke(char* s);//函数声明
     3   
     4   int main(int argc,char* argv[])
     5   {
     6       FP fp;      //通常是用宏FP来声明一个函数指针fp
     7       fp=Invoke;  //将函数入口地址赋值给fp
     8       fp("Hello World!
    ");
     9       return 0;
    10  }
    11  
    12  void Invoke(char* s)
    13  {
    14      printf(s);
    15  }
    View Code

    回调函数的概念:回调函数,顾名思义,就是使用者自己定义一个函数,使用者自己实现这个函数的程序内容,然后把这个函数作为参数传入别人(或系统)的函数中,由别人(或系统)的函数在运行时来调用的函数。函数是你实现的,但由别人(或系统)的函数在运行时通过参数传递的方式调用,这就是所谓的回调函数。简单来说,就是由别人的函数运行期间来回调你实现的函数。

     1 //定义回调函数
     2 void PrintfText() 
     3 {
     4     printf("Hello World!
    ");
     5 }
     6 
     7 //定义实现回调函数的"调用函数"
     8 void CallPrintfText(void (*callfuct)())
     9 {
    10     callfuct();
    11 }
    12 
    13 //实现函数回调
    14 int main(int argc,char* argv[])
    15 {
    16     CallPrintfText(PrintfText);
    17     return 0;
    18 }
    View Code

     PrintfText()和main函数由A用户实现,CallPrintfText由B用户实现,这样A可以根据自己的需求设计具体的函数处理方式,而保证内部接口不变。

     1 //定义带参回调函数
     2 void PrintfText(char* s) 
     3 {
     4     printf(s);
     5 }
     6 
     7 //定义实现带参回调函数的"调用函数"
     8 void CallPrintfText(void (*callfuct)(char*),char* s)
     9 {
    10     callfuct(s);
    11 }
    12 
    13 //在main函数中实现带参的函数回调
    14 int main(int argc,char* argv[])
    15 {
    16     CallPrintfText(PrintfText,"Hello World!
    ");
    17     return 0;
    18 }
    View Code

    上面是带参的回调函数,其实就是在main函数中使用CallPrintfText接口,将用户自己定义的PrintfText函数入口地址作为参数赋值给callfuct函数指针。 在CallPrintfText中用callfuct函数指针来实现PrintfText函数调用功能。

  • 相关阅读:
    json字符串数组判断其中
    json字符串数组判断其中
    jquery select chosen禁用某一项option
    数据库培训知识
    人员管理模块代码总结2015/8/12整理
    正则表达式在STARLIMS中的应用总结
    控件属性表
    Form-公共代码
    Server-Script公共代码
    Celient-Script公共代码
  • 原文地址:https://www.cnblogs.com/SuzanneHuang/p/9483113.html
Copyright © 2011-2022 走看看