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