在代码中使用动态加载库函数调用动态库

函数原型:dlopen() ; dlsym(); dlerror(); dlclose()

void *dlopen(const *char filename, int flag)

自定义打开动态库,flag 通常为RTLD_LAZY

返回值为null时打开失败

void *dlsym(void *handle, char *symbol)

获取动态库的函数指针,handle为dlopen的返回库句柄, symbol为动态库中存在的函数名, 返回的是一个函数指针, 所以定义时也需注意,通常用dlerror来判断

//test 
#include <dlfcn.h> /*动态库头文件*/

int main(void)
{
    /*随便以libstr.so为例*/
    char *str = "hello world!";
    int (*pstrfunction)(char *str);   /*注意,定义时得知道动态库的函数定义原型,然后以函数指针的形式去定义,不然无法调用*/
    void *phandle = NULL;   /*dlopen 的返回库句柄*/
   void *perr = NULL;     /*dlerror的返回的错误信息句柄*/
   phandle = dlopen("./libstr.so", RTLD_LAZY);
   if(!phandle) {
       printf("dlopen error \n");
   }
   /*这里也可以用dlerror来判断*/
   perr = dlerror();
   if(perr != NULL) {
       printf(" error %s \n", perr); /*可以获取错误码*/
       return -1;
   }
   pstrfunction = dlsym(phandle , "my_strlen");
   perr = dlerror();
   if(perr != NULL) {
       printf(" error %s \n", perr); /*可以获取错误码*/
       return -1;
   }
   /*调用函数指针*/
   int len = pstrfunction(str);
   printf(" the str len = [%d] \n", len);           
    return 0;
}

注意:编译的时候需要链接上 -ldl库

ps:这里为什么不在编译的时候-l进行动态链接,直接在程序中调用,而是要在代码中去调用库取出其中的函数指针进行调用呢?这个大部分是-l动态链接直接调用的,但是有的情况下,在代码中用dlxxx相关调用会有奇用!!

 

Guess you like

Origin blog.csdn.net/huang422600/article/details/120934489