Chinaunix首页 | 论坛 | 博客
  • 博客访问: 91816
  • 博文数量: 20
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 211
  • 用 户 组: 普通用户
  • 注册时间: 2013-03-25 16:14
个人简介

呃 会的不多

文章分类
文章存档

2015年(3)

2014年(6)

2013年(11)

我的朋友

分类: LINUX

2014-11-19 23:20:03

原文地址:dlopen与dlsym用法 作者:fpseustar

dlopen和dlsym是用于打开动态链接库中的函数,将动态链接库中的函数或类导入到本程序中:
dlopen函数:
功能:打开一个动态链接库
  包含头文件:
  #include
  函数定义:
  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)
  该函数在文件中。
  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);


阅读(1183) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~