在Linux中可以動態加載庫,其使用方法如下:
1. 先生成一個動態庫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");
}
編譯庫:
gcc -fPIC -shared -o libtest.so
test.c
這樣就可以生成libtest.so動態庫。
在這個庫里,定義個兩個函數test1,test2,下面將在程序中加載libtest.so,然后調用test1,test2。
2. 動態加載libtest.so
/*
main.c */
#include <unistd.h>
#include <stdio.h>
#include
<stdlib.h>
#include <sys/types.h>
#include <dlfcn.h> /*
必須加這個頭文件 */
#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
*/
在這個程序中,dlopen函數用來打開一個動態庫,其返回一個void
*的指針,如果失敗,返回NULL。
dlsym返回一個動態庫中的一個函數指針,如果失敗,返回NULL。
dlclose關閉指向動態庫的指針。
編譯的時候需要加上
-ldl
gcc -o main main.c -ldl(編譯時要使用共享庫dl 其中有dlopen dlsynm dlerror dlclose 函數)
運行main,將會看到調用test1,和test2的結果