一. 相关函数: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
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
#include
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
本文介绍了Linux动态链接库中的dlopen函数,用于运行时加载共享库。通过实例展示了如何使用dlopen、dlsym、dlerror和dlclose进行动态链接操作。在示例中,创建了一个动态库lib.so和主程序main.c,成功调用并执行了库中的output函数。

1428

被折叠的 条评论
为什么被折叠?



