1.概念
dlopen()指定模式打開指定的動(dòng)態(tài)鏈接庫(kù)文件铃剔,并返回一個(gè)句柄給dlsym()的調(diào)用進(jìn)程,使用dlclose()來卸載打開的庫(kù)蝠检。
通俗的講就是讀取庫(kù)內(nèi)函數(shù)來使用庫(kù)里的函數(shù)沐悦。
2.流程
打開庫(kù):void* dlopen(const char* libfile,int flag);
取函數(shù):void* dlsym(void* handler, const char* symbol);
運(yùn)行函數(shù):func
關(guān)閉庫(kù):int dlclose(void* handler);
3.實(shí)例
runlib.c
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#define DLL_PATH "./libsd.so"
typedef int (*func)(int, int);
int main(){
? ? void *dlhandler;
? ? char *error;
? ? func func = NULL;
? ? dlhandler = dlopen(DLL_PATH,RTLD_LAZY);
? ? if(dlhandler == NULL){
? ? ? ? fprintf(stderr,"%s\n",dlerror());
? ? ? ? exit(-1);
? ? }
? ? dlerror();
? ? func = dlsym(dlhandler,"sumab");
? ? printf("%d\n",func(1,2));
? ? dlclose(dlhandler);
? ? return 0;
}
編譯:
gcc -rdynamic -o runlib runlib.c -ldl
運(yùn)行:
[teanee@localhost runlib]$ ./runlib
3
成功調(diào)用sumab函數(shù)。