回调函数(一)

回调函数,C语言编程中很常见,下面呈现一种常用的编程方式

头文件

/*
  @ File Name: calc.h
  @ Author: hw
  @ Mail: feiyelove@163.com
  @ Created Time: 2015-07-01 14:42:00
*/

#ifndef _CALC_H_
#define _CALC_H_

#ifdef __cplusplus
extern "C"
{
#endif

struct _CALC_FUNCLIST {
        int (*add)(int a, int b);
        int (*sub)(int a, int b);
};
typedef struct _CALC_FUNCLIST CALC_FUNCLIST;

int dowork(CALC_FUNCLIST *pFuncList, int a, int b);

#ifdef __cplusplus
}
#endif

#endif

源文件

/*
  @ File Name: calc.c
  @ Author: hw
  @ Mail: feiyelove@163.com
  @ Created Time: 2015-07-01 14:39:26
*/

#include "calc.h"

int dowork(CALC_FUNCLIST *pFuncList, int a, int b)
{
        pFuncList->add(a, b);
        pFuncList->sub(a, b);

        return 0;
}

测试程序

/*
  @ File Name: test.c
  @ Author: hw
  @ Mail: feiyelove@163.com
  @ Created Time: 2015-07-01 17:50:16
*/

#include <stdio.h>
#include <stdlib.h>
#include "calc.h"

int add(int a, int b)
{
        printf("%d + %d = %d \n", a, b, a+b);
        return a + b;
}

int sub(int a, int b)
{
        printf("%d - %d = %d \n", a, b, a-b);
        return a - b;
}

static CALC_FUNCLIST s_funcList =
{
        add,
        sub,
};

int main()
{
        dowork(&s_funcList, 1, 2);
        return 0;
}

Makefile

CC      = gcc
CFLAGS  =
LDFLAGS = -shared -fPIC
INC     = -I.
LIBS    =
DLL     = libcalc.so
TESTOBJS        = test.o
OBJS    = $(filter-out $(TESTOBJS),$(patsubst %.c,%.o,$(wildcard *.c)))

$(DLL):$(OBJS)
        $(CC) $(LDFLAGS) -o $(DLL) $(OBJS)

$(OBJS):%.o:%.c
        $(CC) $(CFLAGS) $(INC) -c $< -o $@

$(TESTOBJS):%.o:%.c
        $(CC) $(CFLAGS) $(INC) -c $< -o $@

test:$(TESTOBJS)
        $(CC) -o test $(TESTOBJS) $(DLL)
clean:
        rm -f *.o
        rm -f $(DLL) test

编译动态库

$ make

编译测试程序

$ make test

执行测试程序

$ ./test
1 + 2 = 3 
1 - 2 = -1 

可以看到,test程序调用到了动态库中的dowork接口,dowrok接口回调了test程序中的add sub接口

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值