C語言從代碼中加載動態(tài)鏈接庫過程解析
這篇文章主要介紹了C語言從代碼中加載動態(tài)鏈接庫過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
函數(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名稱對應(yīng)的函數(shù)的指針
函數(shù):int dlclose(void *handle);
功能:關(guān)閉動態(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;// 錯誤指針
// 打開動態(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;}
// 調(diào)用StrLen函數(shù)
printf("The string length is:%d\n", pStrLen(src));
// 關(guān)閉庫文件
dlclose(pHandle);
return 0;
]
運行以下命令編譯成可執(zhí)行文件。-L./ 當(dāng)前目錄,-lstr為StrLen函數(shù)所在庫文件,-ldl為dlopen等相關(guān)函數(shù)所在庫文件
gcc -o test main.c -L./ -lstr -ldl
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Visual?Studio下Eigen庫環(huán)境配置方式
這篇文章主要介紹了Visual?Studio下Eigen庫環(huán)境配置方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12

