C/C++动态库加载

动态库

动态库又称动态链接库英文为DLL,是Dynamic Link Library 的缩写形式,DLL是一个包含可由多个程序同时使用的代码和数据的库,DLL不是可执行文件。动态链接提供了一种方法,使进程可以调用不属于其可执行代码的函数。函数的可执行代码位于一个 DLL 中,该 DLL 包含一个或多个已被编译、链接并与使用它们的进程分开存储的函数。DLL 还有助于共享数据和资源。多个应用程序可同时访问内存中单个DLL 副本的内容。DLL 是一个包含可由多个程序同时使用的代码和数据的库。Windows下动态库为.dll后缀,在linux下为.so后缀,下文以linux为例进行说明。

动态库加载方式

链接加载

在程序运行时将链接的动态库装载入进程实体(内存中)。应用程序需要包含动态库对应的头文件来调用动态库的方法,并链接动态库提供方法支持。

动态加载

使用dlopendlsymdlclosedlerror来动态地将动态库装载到当前进程实体中,头文件#include <dlfcn.h>

dlopen

将指定的动态库以特定的方式装载到当前进程实体,并返回一个可操作的句柄,用以后续获取函数地址等操作。

void *dlopen(const char *filename, int flag);

The function dlopen() loads the dynamic library file named by the null-terminated string filename and returns an opaque “handle” for the dynamic library.

dlsym

从指定的(由dlopen的返回值指定)库中获得指定的函数(即函数,第二个参数为函数名)。

void *dlsym(void *handle, const char *symbol);

The function dlsym() takes a “handle” of a dynamic library returned by dlopen() and the null-terminated symbol name, returning the address where that symbol is loaded into memory.

dlclose

可将关闭卸载动态库。注意,实际是减掉一个对动态库的引用(ref),仅当减到0时才会触发卸载动态库的操作。

int dlclose(void *handle);

The function dlclose() decrements the reference count on the dynamic library handle handle. If the reference count drops to zero and no other loaded libraries use symbols in it, then the dynamic library is unloaded.

dlerror

返回一个字符串用以描述错误。

char *dlerror(void);

The function dlerror() returns a human readable string describing the most recent error that occurred from dlopen(), dlsym() or dlclose() since the last call to dlerror().

extern ‘C’

参考

C/C++:使用dlopen、dlsym、dlclose运行时装载动态库)

end

入门快速上手贴,有问题的地方请指正。

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值