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