手動載入動態鏈結庫

2021-09-25 19:29:23 字數 2335 閱讀 7827

手動載入動態鏈結庫常用於外掛程式式架構開發

dlfcn.h標頭檔案提供了api

以下我們給出常用的4個函式

/* open the shared object file and map it in; return a handle that can be

passed to `dlsym' to get symbol values from it.  */

extern void *dlopen (const char *__file, int __mode) __thrownl;

/* unmap and close a shared object opened by `dlopen'.

the handle cannot be used again after calling `dlclose'.  */

extern int dlclose (void *__handle) __thrownl __nonnull ((1));

/* find the run-time address in the shared object handle refers to

of the symbol called name.  */

extern void *dlsym (void *__restrict __handle,

const char *__restrict __name) __throw __nonnull ((2));

/* when any of the above functions fails, call this function

to return a string describing the error.  each call resets

the error string so that a following call returns null.  */

extern char *dlerror (void) __throw;

一、dlopen

dlopen 通過檔名開啟so檔案並載入獲取handle

extern void *dlopen (const char *__file, int __mode) __thrownl;

(1)輸入引數:

const char *__file 為檔案路徑

mode是開啟方式,其值有多個,不同作業系統上實現的功能有所不同,在linux下,按功能可分為三類:

a、解析方式

rtld_lazy:在dlopen返回前,對於動態庫中的未定義的符號不執行解析(只對函式引用有效,對於變數引用總是立即解析)。

rtld_now: 需要在dlopen返回前,解析出所有未定義符號,如果解析不出來,在dlopen會返回null,錯誤為:: undefined symbol: ***x.......

b、作用範圍,可與解析方式通過「|」組合使用。

rtld_global:動態庫中定義的符號可被其後開啟的其它庫解析。

rtld_local: 與rtld_global作用相反,動態庫中定義的符號不能被其後開啟的其它庫重定位。如果沒有指明是rtld_global還是rtld_local,則預設為rtld_local。

c、作用方式

rtld_noload: 不載入庫。可用於測試庫是否已載入(dlopen()返回null說明未載入,否則說明已載入),也可用於改變已載入庫的flag,如:先前載入庫的flag為rtld_local,用dlopen(rtld_noload|rtld_global)後flag將變成rtld_global。這個flag不是posix-2001標準。

rtld_deepbind:在搜尋全域性符號前先搜尋庫內的符號,避免同名符號的衝突。這個flag不是posix-2001標準。

(2)返回值:

開啟失敗返回null,開啟成功返回相應庫的handle

二、extern void *dlsym (void *__restrict __handle, const char *__restrict __name) __throw __nonnull ((2));

(1)輸入引數

void *__restrict __handle 為dlopen獲取的handle

const char *__restrict __name 為需要獲取的函式名

(2)返回值

為獲取的函式指標,供程式呼叫

如果失敗會丟擲異常

三、dlclose

extern int dlclose (void *__handle) __thrownl __nonnull ((1));

關閉動態鏈結庫

四、dlerror 主要用於當動態鏈結庫操作出錯時,列印錯誤資訊,用於排查故障

extern char *dlerror (void) __throw;

linux 動態鏈結庫載入

linux 動態鏈結 linux 中的應用程式以以下兩種方式之一鏈結到外部函式 要麼在構建時與靜態庫 lib a 靜態地鏈結,並且將庫 包含在該應用程式的可執行檔案裡 要麼在執行時與共享庫 lib so 動態地鏈結。通過動態鏈結裝入器,將動態庫對映進應用程式的可執行記憶體中。在啟動應用程式之前,動態...

動態鏈結庫延遲載入

開發的時候遇到乙個問題,有乙個可執行程式需要依賴另外乙個目錄的動態庫,但是對這個dll介面的引用採用的是靜態依賴的方式。解決不難,可以通過loadlibrary動態載入,然後呼叫其介面。但是這用就沒法方便的通過靜態以依賴的方式方便的呼叫其介面了。探索後發現vs支援延遲繫結。就是呼叫的時候可以通過靜態...

linux dlopen 載入動態鏈結庫失敗

如下 g dynamichandle dlopen libcalcdistance.so rtld now if nullptr g dynamichandle 然後再執行的時候就一直提示load so failed。這裡僅以一般的原因來說明這個問題。一般而言,原因 都是預設的路徑找不到這個檔案,所...