C語言從代碼中加載動(dòng)態(tài)鏈接庫過程解析
這篇文章主要介紹了C語言從代碼中加載動(dòng)態(tài)鏈接庫過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
函數(shù):void *dlopen(const char *filename, int flag);
功能:打開動(dòng)態(tài)鏈接庫文件
參數(shù):filename 動(dòng)態(tài)鏈接庫文件名
flag 打開方式,一般為RTLD_LASY
返回值:庫指針
函數(shù):char *dlerror(void);
功能:獲取錯(cuò)誤值
返回值:錯(cuò)誤值
函數(shù):void *dlsym(void *handle, const char *symbol);
功能:獲取動(dòng)態(tài)鏈接庫中指定函數(shù)的指針
參數(shù):handle 庫指針
symbol 函數(shù)名稱
返回值:與參數(shù)symbol名稱對(duì)應(yīng)的函數(shù)的指針
函數(shù):int dlclose(void *handle);
功能:關(guān)閉動(dòng)態(tài)鏈接庫文件
參數(shù):庫指針
返回值:
源碼
/*main.c*/ #include <dlfcn.h>// 相關(guān)函數(shù)頭文件 #include <stdio.h> int main(void) { const char *src = "Hello Dymatic"; int (*pStrLen)(const char *);// 函數(shù)指針 void *pHandle = NULL;// 庫指針 char *pErr = NULL;// 錯(cuò)誤指針 // 打開動(dòng)態(tài)鏈接庫并檢查是否有錯(cuò)誤發(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ù)地址并檢查是否有錯(cuò)誤發(fā)生 pStrLen = dlsym(pHandle, "StrLen"); pErr = dlerror(); if(!pStrLen || pErr == NULL){printf("%s\n", pErr);return -1;} // 調(diào)用StrLen函數(shù) printf("The string length is:%d\n", pStrLen(src)); // 關(guān)閉庫文件 dlclose(pHandle); return 0; ]
運(yùn)行以下命令編譯成可執(zhí)行文件。-L./ 當(dāng)前目錄,-lstr為StrLen函數(shù)所在庫文件,-ldl為dlopen等相關(guān)函數(shù)所在庫文件
gcc -o test main.c -L./ -lstr -ldl
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
手把手教你實(shí)現(xiàn)一個(gè)C++單鏈表
鏈表是一種數(shù)據(jù)結(jié)構(gòu),用于數(shù)據(jù)的存儲(chǔ)。這篇文章主要為大家介紹了如何實(shí)現(xiàn)一個(gè)C++單鏈表,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以嘗試一下2022-11-11Visual?Studio下Eigen庫環(huán)境配置方式
這篇文章主要介紹了Visual?Studio下Eigen庫環(huán)境配置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12