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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM