在Linux中可以動(dòng)態(tài)加載庫(kù),其使用方法如下:
1. 先生成一個(gè)動(dòng)態(tài)庫(kù)libtest.so
/* test.c
*/
#include <stdio.h>
#include <stdio.h>
void test1(int
no)
{
printf("*****************************************\n");
printf("This is test1, the number is %d.\n", no);
printf("*****************************************\n");
}
void test2(char
*str)
{
printf("=========================================\n");
printf("This is test2, the string is %s.\n", str);
printf("=========================================\n");
}
編譯庫(kù):
gcc -fPIC -shared -o libtest.so
test.c
這樣就可以生成libtest.so動(dòng)態(tài)庫(kù)。
在這個(gè)庫(kù)里,定義個(gè)兩個(gè)函數(shù)test1,test2,下面將在程序中加載libtest.so,然后調(diào)用test1,test2。
2. 動(dòng)態(tài)加載libtest.so
/*
main.c */
#include <unistd.h>
#include <stdio.h>
#include
<stdlib.h>
#include <sys/types.h>
#include <dlfcn.h> /*
必須加這個(gè)頭文件 */
#include <assert.h>
int main()
{
void *handler = dlopen("./libtest.so", RTLD_NOW);
assert(handler !=
NULL);
void (*test1)(int) = dlsym(handler, "test1");
assert(test1 != NULL);
void (*test2)(char *) = dlsym(handler,
"test2");
assert(test2 != NULL);
(*test1)(10);
(*test2)("hello");
dlclose(handler);
return 0;
}
/* end
*/
在這個(gè)程序中,dlopen函數(shù)用來(lái)打開一個(gè)動(dòng)態(tài)庫(kù),其返回一個(gè)void
*的指針,如果失敗,返回NULL。
dlsym返回一個(gè)動(dòng)態(tài)庫(kù)中的一個(gè)函數(shù)指針,如果失敗,返回NULL。
dlclose關(guān)閉指向動(dòng)態(tài)庫(kù)的指針。
編譯的時(shí)候需要加上
-ldl
gcc -o main main.c -ldl(編譯時(shí)要使用共享庫(kù)dl 其中有dlopen dlsynm dlerror dlclose 函數(shù))
運(yùn)行main,將會(huì)看到調(diào)用test1,和test2的結(jié)果