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); 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 <</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);
|