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<</span>dlfcn.h> void*handle=dlopen("./hello.so",RTLD_LAZY); typedefvoid(*hello_t)();
hello_t hello=(hello_t)dlsym(handle,"hello");
hello();
dlclose(handle);
|
注意库函数在库中的定义要用extern“c”来申明,这样在主函数中才能通过“hello”来查找函数。申明的方式有以下两种:
|
extern"C"intfoo; extern"C"voidbar();
and
extern"C"{
externintfoo;
externvoidbar(); }
|
导入类库方法:
|
#include"polygon.hpp"//类定义处
#include<</span>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<</span><</span>"The
area is: "<</span><</span>poly->area()<</span><</span>'\n'; // destroy the class
destroy_triangle(poly);
// unload the triangle library
dlclose(triangle);
|