首页 > 其他 > 详细

c回调函数

时间:2019-11-20 10:29:26      阅读:93      评论:0      收藏:0      [点我收藏+]

1. 准备三个文件test.c, test.h, main.c

2. 编译生成so文件

3. 编译生成main

通过函数指针回调函数

test.h

#include <stdio.h>

void say_hello();

int caculate(int x, int y, int (*cacauFunc)(int x, int y));

test.c

#include "test.h"

void say_hello(char *name){
    printf("hello %s\n", name);
}

int caculate(int x, int y, int (*cacauFunc)(int x, int y)) {
    printf("receive x = %d, y = %d\n", x, y);
    return cacauFunc(x, y);
}

main.c

#include "test.h"

int add (int x, int y) {
    return x + y;
}

int sub (int x, int y) {
    return x - y;
}

void testSo() {
    say_hello("guanxianseng");
}

void test_call_func_pointer(){
    printf("start\n");
    int x = 5, y = 1, result = 0;
    result = caculate(x, y, add);
    printf("result = %d\n", result);
    result = caculate(x, y, sub);
    printf("result = %d\n", result);
}

int main(){
    test_call_func_pointer();

    return 0;
}

编译test.so

gcc test.c -fPIC -shared -o libtest.so

编译main

gcc main.c  -L. -ltest -o main

执行测试

技术分享图片

 

c回调函数

原文:https://www.cnblogs.com/luckygxf/p/11894870.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!