C - dlopen dlsym

旧巷老猫 提交于 2019-11-28 03:57:53

 

 

-----------------------------------------------------------------------------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

执行结果:

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!