linux dlopen函数,dlopen 和 dlsym 动态调用函数

Linux/unix 提供了使用 dlopen 和 dlsym 方法动态加载库和调用函数,这套方法在 macOS 和 iOS 上也支持。

dlopen 打开一个库,获取句柄。

dlsym 在打开的库中查找符号的值。

dlclose 关闭句柄。

dlerror 返回一个描述最后一次调用dlopen、dlsym,或 dlclose 的错误信息的字符串。

动态调用 printf 函数,编写测试代码如下:#import 

typedef int (*printf_func_pointer) (const char * __restrict, ...);

void dynamic_call_function(){

//动态库路径

char *dylib_path = "/usr/lib/libSystem.dylib";

//打开动态库

void *handle = dlopen(dylib_path, RTLD_GLOBAL | RTLD_NOW);

if (handle == NULL) {

//打开动态库出错

fprintf(stderr, "%s\n", dlerror());

} else {

//获取 printf 地址

printf_func_pointer printf_func = dlsym(handle, "printf");

//地址获取成功则调用

if (printf_func) {

int num = 100;

printf_func("Hello exchen.net %d\n", num);

printf_func("printf function address 0x%lx\n", printf_func);

}

dlclose(handle); //关闭句柄

}

}

int main(int argc, char * argv[]) {

@autoreleasepool {

dynamic_call_function();

return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));

}

}

在手机上运行的输出结果如下:Hello exchen.net 100

printf function address 0x189f0da78

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值