dlopen和dlsym是用于打开动态链接库中的函数,将动态链接库中的函数或类导入到本程序中:
dlopen函数:
功能:打开一个动态链接库
  包含头文件:
  #include <dlfcn.h>
  函数定义:
  void * dlopen( const char * pathname, int mode );
  函数描述:
  在dlopen的()函数以指定模式打开指定的动态连接库文件,并返回一个句柄给调用进程。通过这个句柄来使用库中的函数和类。使用dlclose  
   ()来卸载打开的库。
  mode:分为这两种
  RTLD_LAZY 暂缓决定,等有需要时再解出符号
  RTLD_NOW 立即决定,返回前解除所有未决定的符号。
  RTLD_LOCAL
  RTLD_GLOBAL 允许导出符号
  RTLD_GROUP
  RTLD_WORLD
  返回值:
  打开错误返回NULL
  成功,返回库引用
  编译时候要加入 -ldl (指定dl库)
dlsym函数:
 
函数原型是
 
void* dlsym(void* handle,const char* symbol)
 
该函数在<dlfcn.h>文件中。
  handle是由dlopen打开动态链接库后返回的指针,symbol就是要求获取的函数的名称,函数  返回值是void*,指向函数的地址,供调用使用。
 
导入库函数用法:
 

#include<dlfcn.h>
void* handle= dlopen("./hello.so", RTLD_LAZY);
typedef void(*hello_t)();
hello_t hello = (hello_t) dlsym(handle,"hello");

hello();
dlclose(handle);

注意库函数在库中的定义要用extern“c”来申明,这样在主函数中才能通过“hello”来查找函数。申明的方式有以下两种:

extern"C"
int foo;
extern "C"
void bar();
            
and

extern "C"
{
     extern int foo;
     extern void bar();
}

导入类库方法:

#include"polygon.hpp"
//类定义处

#include
<dlfcn.h>

void* triangle= dlopen("./triangle.so", RTLD_LAZY);
create_t* create_triangle
= (create_t*) dlsym(triangle,"create");

destroy_t* destroy_triangle
= (destroy_t*) dlsym(triangle,"destroy");
polygon* poly = create_triangle();
// use the class

poly->set_side_length(7);
        cout <<"The area is: "
<< poly->area()<<
'\n';
// destroy the class

destroy_triangle(poly);

// unload the triangle library

dlclose(triangle);

最新文章

  1. nginx下搭建CodeIgniter问题集锦
  2. HDFS Federation (读书笔记)
  3. php 图片添加文字水印 以及 图片合成(微信快码传播)
  4. Socket常见错误
  5. ruby学习总结04
  6. shell编程之数学运算
  7. iostat详解
  8. IO库 8.1
  9. PHP控制连接打印机
  10. python基础教程(四)
  11. Android 软键盘的显示和隐藏,这样操作就对了
  12. MySQL升级-5.6升级到5.7版本&amp;切换GTID模式
  13. 我的第三篇博客(激动激动真激动!!!)A-B Problem
  14. Jenkins结合.net平台工具之Msbuild
  15. amoeba读写分离
  16. Xtreme8.0 - Kabloom 动态规划
  17. JavaScript部分兼容性函数
  18. php各种主流框架的优缺点
  19. js模块化的总结
  20. 【Android】5.5 状态切换(Switch)和评级条(RatingBar)

热门文章

  1. 用Merge存储引擎中间件实现MySQL分表
  2. Kefa and Watch
  3. 2 pyspark学习----基本操作
  4. java 关于getProperty()方法中反斜杠问题
  5. GIL 已经被杀死了么?
  6. 451. Sort Characters By Frequency (sort map)
  7. [Xcode 实际操作]二、视图与手势-(5)给图像视图添加圆角效果
  8. Luogu P1074靶形数独【搜索/剪枝】By cellur925
  9. 【MySQL】全量+增量的备份/恢复
  10. luoguP4242树上的毒瘤