dlopen dlsym dlclose的应用
在写程序时,我们经常使用动态库,其实,上面提供的三个函数也可以调用动态库。
- 创建动态库
#include <stdio.h>
void test()
{
printf("test hello!\n");
}
command : # gcc -shared -o test.so test.c -fPIC
-callback
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main(int argc,char *argv[])
{
void *handle;
void (*callfun)();
char *error;
handle = dlopen("./test.so",RTLD_LAZY);
if(!handle)
{
printf("%s\n",dlerror());
exit(1);
}
dlerror();
callfun = dlsym(handle,"test");
if((error = dlerror()) != NULL)
{
printf("%s\n",error);
exit(1);
}
callfun();
dlclose(handle);
return 0;
}
command: # gcc -o a.out main.c -ldl
idea from: 海王