您的位置:首页 > 运维架构 > Linux

linux动态链接库中函数的运行时加载

2013-07-16 20:21 435 查看
一. 相关函数:dlopen(打开共享库),dlsym(查找符号),dlerror(错误信息),dlclose(关闭共享库) 1. dlopen()
原型:void* dlopen(const char *filename, int flag);
2. dlsym() 3. dlerror() 4. dlclose()二. 源码实例 1. 动态库文件:lib.c,lib.h

#include <stdio.h>
void output(int index)
{
printf("Printing from lib.so. Called by program %d\n", index);
}


#file:lib.h
#ifndef LIB_H
#define LIB_H
void output(int index);
#endif
2. main.c
#include <stdio.h>
#include <dlfcn.h>
int main()
{
void *handle;
void (*fun)(int);
char* error;
handle = dlopen("/home/hotpatch/dynamic_lib/lib.so", RTLD_NOW);
if(NULL == handle)
{
printf("Open library error.error:%s\n",dlerror());
return -1;
}
fun = dlsym(handle,"output");
if(NULL != (error = dlerror()))
{
printf("Symbol output is not found:%s\n",error);
goto exit_runso;
}
fun(10);
printf("Function address is: 0x%016x\n",fun);
exit_runso:
dlclose(handle);
return 0;
}


3.编译运行

编译:
gcc -fPIC -shared -o lib.so lib.c
gcc -o test main.c -ldl
运行:
Printing from lib.so. Called by program 10
Function address is: 0x00000000e67ba604
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐