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 ", name); } int caculate(int x, int y, int (*cacauFunc)(int x, int y)) { printf("receive x = %d, y = %d ", 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 "); int x = 5, y = 1, result = 0; result = caculate(x, y, add); printf("result = %d ", result); result = caculate(x, y, sub); printf("result = %d ", 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
执行测试