載入執行動態庫
void * dlopen(const char* filename, int flag);
開啟一個動態庫檔案,返回一個指標作為控制代碼handle.失敗返回NULL.
flag: RTLD_NOW(RunTime Load Dynamic ):表示立即載入到記憶體
RTLD_LAZY:表示在使用時才載入.
潛規則:
返回指標的函式一般用正常地址表示成功,NULL表示失敗。個別例外返回(void*)0xffffffff表示失敗.
char* dlerror(void);取得一個字串描述動態庫操作發生了什麼錯誤。
void * dlsym(void* handle, const char* symbol);查詢指定的符號名在動態庫中的地址,失敗返回NULL,(嚴格的做法是在dlsym呼叫前呼叫dlerror, dlsym之後再呼叫dlerror()判斷後一次的返回值是否非空來判斷是否失敗。)
int dlclose(void* handle);關閉動態庫,從記憶體中解除安裝。
標頭檔案:<dlfcn.h>
這些函式在動態庫libdl.so中, gcc -ldl
demo:
#include<stdio.h>
#include<dlfcn.h>
int main()
{
printf("select 1 or 2");
int sel = 0;
scanf("%d", &sel);
void * handle;
if( 1== sel)
{
handle = dlopen("./libch.so", RTLD_NOW);
}else{
handle = dlopen("./liben.so", RTLD_NOW);
}
if( NULL == handle )
{
puts( dlerror() );
return -1;
}
void (*fp)(void);
fp = dlsym(handle, "welcom");
if(NULL == fp )
{
puts( dlerror() );
return -1;
}
fp(); // (*fp)();dlclose( handle );
}
//
gcc -shared -o libch.so dlzh.c
gcc -shared -o liben.so dlen.c