c语言实现回调函数

本文介绍如何使用C语言实现回调函数。通过定义函数指针并传递给其他函数,实现特定功能的回调。提供了两种调用回调函数的方式,并展示了运行结果。

callback.c

/*
 * @file c语言实现回调函数
 * @detial 在java等更高级的语言中往往已经给我们封装好了回调函数的调用方式,直接用就可以了。
 * 而C语言中并没有这种直接可以操作的回调方式,我们用函数指针来实现回调原理。
 */
#include<stdio.h>

// 将函数名作为指针的格式为:int (*ptr)(char *p) 即:返回值(指针名)(参数列表)
typedef int (*callback)(char *str); // 回调函数的名称为 callback,参数是char *p

// functionA的格式符合 callback 的格式,因此可以看作是一个 callback类型
int functionA(char *str)
{
    printf("回调 functionA(char *str) 函数:%s!\n", str);
    return 0;
}

// functionB的格式符合 callback 的格式,因此也可以看作是一个 callback类型
int functionB(char *str)
{
    printf("回调 functionB(char *str) 函数:%s!\n", str);
    return 0;
}



// 调用回调函数,方式一:通过命名方式
int test1(callback p_callback, char *str)
{
    printf("test1:\n不调用回调函数打印:%s!\n", str);
    p_callback(str);
    return 0;
}

// 调用回调函数,方式二:直接通过函数指针
int test2(int (*ptr)(), char *str)
{
    printf("test2:\n不调用回调函数打印:%s!\n", str);
    (*ptr)(str);
}

int main()
{
    char *str = "hello world!";

    test1(functionA, str);
    test1(functionB, str);
    test2(functionA, str);
    test2(functionB, str);

    printf("test3:\n");
    callback test3 = functionB;
    test3(str);

    return 0;
}

运行结果
[root@centos6 data]# gcc callback.c
[root@centos6 data]# ./a.out
test1:
不调用回调函数打印:hello world!!
回调 functionA(char *str) 函数:hello world!!
test1:
不调用回调函数打印:hello world!!
回调 functionB(char *str) 函数:hello world!!
test2:
不调用回调函数打印:hello world!!
回调 functionA(char *str) 函数:hello world!!
test2:
不调用回调函数打印:hello world!!
回调 functionB(char *str) 函数:hello world!!
test3:
回调 functionB(char *str) 函数:hello world!!


始于2012-10-05,Tencent;更新至2016-06-04,杭州。

评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值