1.函数集合
#include <dlfcn.h> void *dlopen(const char *filename, int flag); char *dlerror(void); void *dlsym(void *handle, const char *symbol); int dlclose(void *handle);
Link with -ldl.
2.Demo例子
caculate.c用于编译成一个库
int add(int a,int b) { return (a + b); } int sub(int a, int b) { return (a - b); } int mul(int a, int b) { return (a * b); } int div(int a, int b) { return (a / b); }View Code
main.c调用这个库里面的函数
#include <stdio.h> #include <stdlib.h> #include <dlfcn.h> #define LIB_CACULATE_PATH "./libcaculate.so" typedef int (*CAC_FUNC)(int, int); int main() { void *handle; char *error; CAC_FUNC cac_func = NULL; handle = dlopen(LIB_CACULATE_PATH, RTLD_LAZY); if (!handle) { fprintf(stderr, "%s\n", dlerror()); return -1; } //获取一个函数 cac_func = dlsym(handle, "add"); if ((error = dlerror()) != NULL) { fprintf(stderr, "%s\n", error); return -1; } printf("add: 2+7=%d\n", cac_func(2,7)); cac_func = dlsym(handle, "sub"); printf("sub: 9-2=%d\n", cac_func(9,2)); cac_func = dlsym(handle, "mul"); printf("mul: 3*2=%d\n", cac_func(3,2)); cac_func = dlsym(handle, "div"); printf("div: 8/2=%d\n", cac_func(8,2)); dlclose(handle); return 0; }View Code
编译执行:
编译: $ gcc -rdynamic -o main main.c -ldl $ gcc -shared -fPIC caculate.c -o libcaculate.so 执行: $ ./main add: 2+7=9 sub: 9-2=7 mul: 3*2=6 div: 8/2=4View Code
3.详细信息:# man dlopen