Green 发表于 2021-8-7 10:47:52

c回调函数

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执行测试



文档来源:51CTO技术博客https://blog.51cto.com/u_2498536/3304168
页: [1]
查看完整版本: c回调函数