C语言回调函数使用

什么是回调函数?

两个模块(.c)之间通过函数指针的形式调用彼此的内部函数的方式,叫做回调

例子

a.c中定义一个打印helloworld!的函数

#include <stdio.h>

void print_hello(void)
{
    printf("hello world!\n");
    return ;
}

a.h中是对a.c中的打印函数的声明

#ifndef __TEST_A_H__
#define __TEST_A_H__

/**
 * @name print_hello
 * @brief 打印hello_world!
 */
void print_hello(void);

#endif //__TEST_A_H__

b.c中有一个全局变量,可以保存一个对应类型的函数指针

#include <stdio.h>
#include "b.h"

cb_reg_t m_fun = NULL;

void cb_reg_fun(cb_reg_t fun)
{
    m_fun = fun;  /// b.c里面保存a中的一个函数指针
    return;
}


void print_3_hello(void)
{
    if (m_fun != NULL)
    {
        m_fun();
        m_fun();
        m_fun();
    }
    return;
}

b.h

#ifndef TEST_B_H
#define TEST_B_H


/**
 * @brief 声明一个返回值为void,参数为void的函数指针类型
 */
typedef void(*cb_reg_t)(void);

/**
 * @name cb_reg_fun
 * @brief 函数指针注册函数
 * @param fun
 */
void cb_reg_fun(cb_reg_t fun);


/**
 * @name print_3_hello
 * @brief 说3次hello
 */
void print_3_hello(void);

#endif //TEST_B_H

main.c的作用是将a.c中的函数指针注册到c里面去,在调用print_3_hello的时候就可以实现打印3次helloworld了。

#include "a.h"
#include "b.h"

int main(void)
{
    cb_reg_fun(print_hello);  /// 把a.c中的函数指针注册到b.c中去

    print_3_hello();
}

回调函数的作用

解耦

a.c中打印内容可以更自由化,b.c只是做了打印3次的操作,并不能对打印的内容进行修改,或者是b.c只能控制是否打印,打印次数等。

同步

如果b.c中的某一个函数fun_a有使用m_fun,在main.c中调用fun_a,也会调用m_fun。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值