• 回调函数用法范例


      回调函数是指 使用者自己定义一个函数,实现这个函数的程序内容,然后把这个函数(入口地址)作为参数传入别人(或系统)的函数中,由别人(或系统)的函数在运行时来调用的函数。

      函数是你实现的,但由别人(或系统)的函数在运行时通过参数传递的方式调用,这就是所谓的回调函数。简单来说,就是由别人的函数运行期间来回调你实现的函数

    范例一:

    #include <stdio.h>

    #define CALLBACK
    CALLBACK void Printnum(int num)
    {
    printf("num is %d ",num);
    }

    CALLBACK void Printstr(char *buf)
    {
    printf("%s ",buf);
    }

    void showNum(void (* ptr)(),int n)
    {
    (* ptr)(n);
    }


    void showstr(void (*ptr)(),char *buf)
    {
    (*ptr)(buf);
    }

    int main(int argc, char* argv[])
    {
    char buf[32]="hello,world!";
    showstr(Printstr,buf);
    showNum(Printnum,5);
    return 0;
    }

    范例二:

    #include <stdio.h>

    #define CALLBACK
    struct operation {
    void (*callback)();
    };

    void trigger(struct operation* ops, int ops_length) {
    int i = 0;
    while(i++ < ops_length) {
    ops->callback();
    ops++;
    }
    }

    CALLBACK void a_callback() {
    printf("I'm A ");
    }

    CALLBACK void b_callback() {
    printf("I'm B ");
    }

    int main(int argc, char* argv[])
    {
    struct operation A,B;
    A.callback = &a_callback;
    B.callback = &b_callback;
    struct operation ops[2];
    ops[0] = A;
    ops[1] = B;
    trigger(ops, 2);
    return 1;
    }

  • 相关阅读:
    Qt 学习之路 :文本文件读写
    Qt 学习之路:文本文件读写
    Qt 学习之路:二进制文件读写
    Qt 学习之路 :文件
    安全通信 QSslSocket
    Qt 学习之路:绘制设备
    Qt 学习之路:坐标系统
    Qt 学习之路 :坐标系统
    dmesg 程序崩溃调试2
    dmesg 程序崩溃调试
  • 原文地址:https://www.cnblogs.com/baiduboy/p/8405011.html
Copyright © 2020-2023  润新知