参考:http://blog.csdn.net/kingkong1024/article/details/8474210
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库),例如gcc test.c -o test -ldl
dlsym函数:
函数原型是
void* dlsym(void* handle,const char* symbol)
该函数在<dlfcn.h>文件中。
handle是由dlopen打开动态链接库后返回的指针;
symbol就是要求获取的函数的名称,函数返回值是void*,指向函数的地址,供调用使用。
实例一 导入方法:
dl_test.h
#include <stdio.h>
void test();
dl_test.c
#include "dl_test.h"
void test(){
printf("test");
}
cygwin下编译:gcc dl_test.c -shared -o libtest.so
dl_exe.c
#include <dlfcn.h>
int main(){
void* handle = dlopen("./libtest.so", RTLD_LAZY);
typedef void (*test_t)();
test_t test = (test_t) dlsym(handle, "test");
test();
dlclose(handle);
}
cygwin下编译:gcc dl_exe.c -o dl_exe
运行:dl_exe
实例二 导入类:
dl_cpp.h
#include<iostream>
using std::cout;
using std::endl;
class Dl_cpp {
public:
Dl_cpp();
~Dl_cpp();
void set(int i);
private:
int i;
};
Dl_cpp::Dl_cpp()
{
cout<<"Dl_cpp()"<<endl;
}
Dl_cpp::~Dl_cpp()
{
cout<<"~Dl_cpp()"<<endl;
}
void Dl_cpp::set(int input)
{
i=input;
cout<<"set i="<<i<<endl;
}
dl_cpp.cpp
#include<iostream>
#include"dl_cpp.h"
using std::cout;
using std::endl;
extern "C" Dl_cpp* create() {
cout<<"new"<<endl;
return new Dl_cpp();
}
extern "C" void destroy(Dl_cpp* plugIn) {
cout<<"delete"<<endl;
delete plugIn;
}
cygwin下编译:g++ dl_cpp.cpp -shared -o libdl_cpp.so
dl_exe.cpp
#include <dlfcn.h>
#include"dl_cpp.h"
int main(){
void* handle = dlopen("./libdl_cpp.so", RTLD_LAZY);
typedef Dl_cpp* create_t(void);
typedef void destroy_t(Dl_cpp*);
typedef create_t* FPCREATE;
typedef destroy_t* FPDESTORY;
FPCREATE create = (FPCREATE) dlsym(handle, "create");
FPDESTORY destroy = (FPDESTORY) dlsym(handle, "destroy");
Dl_cpp* pDl_cpp = (Dl_cpp*)create();
pDl_cpp->set(1);
destroy(pDl_cpp);
dlclose(handle);
}
cygwin下编译: g++ dl_exe.cpp -o dl_exe
运行:dl_exe