這篇文章主要介紹了C語言從代碼中加載動態鏈接庫過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
函數:void *dlopen(const char *filename, int flag);
功能:打開動態鏈接庫文件
參數:filename 動態鏈接庫文件名
flag 打開方式,一般為RTLD_LASY
返回值:庫指針
函數:char *dlerror(void);
功能:獲取錯誤值
返回值:錯誤值
函數:void *dlsym(void *handle, const char *symbol);
功能:獲取動態鏈接庫中指定函數的指針
參數:handle 庫指針
symbol 函數名稱
返回值:與參數symbol名稱對應的函數的指針
函數:int dlclose(void *handle);
功能:關閉動態鏈接庫文件
參數:庫指針
返回值:
源碼
/*main.c*/#include <dlfcn.h>// 相關函數頭文件#include <stdio.h> int main(void){ const char *src = "Hello Dymatic"; int (*pStrLen)(const char *);// 函數指針 void *pHandle = NULL;// 庫指針 char *pErr = NULL;// 錯誤指針 // 打開動態鏈接庫并檢查是否有錯誤發生 pHandle = dlopen("./libstr.so“, RTLD_LASY); pErr = dlerror(); if(!pHandle || pErr != NULL){printf("Failed load library!/n%s/n", pErr);return -1;} // 獲取StrLen函數地址并檢查是否有錯誤發生 pStrLen = dlsym(pHandle, "StrLen"); pErr = dlerror(); if(!pStrLen || pErr == NULL){printf("%s/n", pErr);return -1;} // 調用StrLen函數 printf("The string length is:%d/n", pStrLen(src)); // 關閉庫文件 dlclose(pHandle); return 0;]
運行以下命令編譯成可執行文件。-L./ 當前目錄,-lstr為StrLen函數所在庫文件,-ldl為dlopen等相關函數所在庫文件
gcc -o test main.c -L./ -lstr -ldl
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答
圖片精選