-----------------------------------------------------------------------------dlsym-----------------------------------------------------------------------------
测试dlsym打开的函数指针能不能多次调用
#include <stdio.h> #include <dlfcn.h> #include <unistd.h> #include <time.h> int main(){ int (*func)(int a, int b); void *handle = NULL; int c; char *myso = "./mylib.so"; if((handle = dlopen(myso, RTLD_NOW)) != NULL) { printf("success\n"); func = (void(*)())dlsym(handle, "add"); if(func != NULL){c=(*func)(1,2);} printf("1--%d",c); if(func != NULL){c=(*func)(2,2);} printf("\n2--%d",c); dlclose(handle); } else printf("dlopen - %s\n", dlerror()); }
gcc main.c -ldl -rdynamic
#include <stdlib.h> #include <stdio.h> int add(int a,int b){ return a+b; }
gcc -fPIC -shared -o mylib.so add.c
调用:
./a.out
执行结果: