C/C++回掉函数

50 篇文章 2 订阅

参考:https://www.cnblogs.com/chenyuming507950417/archive/2012/01/02/2310114.html

#include <stdio.h>

typedef void (*P)(void);

void fun1(void)
{
    printf("hello world\n");
}
void fun2(void)
{
    printf("cbs\n");
}

int main(void)
{
    P p;
    p = fun1;
    p();
    p = fun2;
    p();
    return 0;
}
#include <stdio.h>
typedef void (*P)(void);


void printf_text(void)
{
    printf("hello world\n");
}

void call_printf_text(P p)
{
    p();
}

int main(void)
{
    P p = printf_text;
    call_printf_text(p);

    return 0;
}
#include <stdio.h>
typedef void (*P)(const char *);


void printf_text(const char *str)
{
    printf("%s\n",str);
}

void call_printf_text(P p,const char *str)
{
    p(str);
}

int main(void)
{
    P p = printf_text;
    call_printf_text(p,"hello cbs");

    return 0;
}
#include <stdio.h>
#include <string.h>


/************上级的代码*************/
typedef void (*P1)(const char *);
typedef void (*P2)(const char *,int);

typedef struct
{
    P1 p1;
    P2 p2;
}Fun;

void call(Fun *funs)
{
    const char *str1 = "shun";
    const char *str2 = "com";
    int len = strlen(str2);

    funs->p1(str1);//运行时call
    funs->p2(str2,len);//运行时call
}

/***********************************/






/************程序员根据上级的typedef定义并实现自己的方法****************/
void fun1(const char *str)
{
    printf("%s\n",str);
}
void fun2(const char *str,int len)
{
    printf("%s\n",str);
    printf("%d\n",len);
}


Fun funs = {fun1,fun2};
/******************最后根据上级的结构体打包函数指针*********************/










int main(void)
{
    call(&funs);    


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值