dlopen linux 实例_linux动态链接库中函数的运行时加载

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

一.  相关函数: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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值