#include <stdio.h> #include "api_dl.h" int main() { int a = 1, b = 5, c = 0xffff; c = add(a, b); printf("a + b = %d\n", c); c = multi(a, b); printf("a * b = %d\n", c); return 0; }
#include <stdio.h> #include <dlfcn.h> #include "api_internal.h" struct api_driver *global_driver; void __set_driver(struct api_driver *drv) { global_driver = drv; } int add(int a, int b) { return global_driver->add(a, b); } int multi(int a, int b) { return global_driver->multi(a, b); } static void __attribute__((constructor)) open_driver_dl(void) { void *driver_dl; driver_dl = dlopen("./libdriver.so", RTLD_NOW); if (!driver_dl) printf("Fail to open libdriver\n"); }
api库中针对驱动库的头文件(api_internal.h):
1 2 3 4 5 6 7 8 9 10 11 12
struct api_driver { int (*add)(int a, int b); int (*multi)(int a, int b); }; void __set_driver(struct api_driver *drv); #define SET_DRIVER(drv) \ static void __attribute__((constructor)) set_driver(void) \ { \ __set_driver(drv); \ }
一个驱动库的实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include "api_internal.h" static int add(int a, int b) { return a + b; } static int multi(int a, int b) { return a * b; } struct api_driver one_driver = { .add = add, .multi = multi, }; SET_DRIVER(&one_driver);