1.环境
ubuntu 14.04
g++ 4.8.4
2.有类的情况
1)库文件
a)源码
//cppl2.h
class cal {
public:
cal();
virtual ~cal();
virtual int add(int a, int b);
};
typedef cal* (*creat_t)();
typedef void (*destroy_t)(cal*);
//cppl2.cpp
#include "cppl2.h"
cal::cal(){};
cal::~cal(){}
int cal::add(int a, int b) {
return a + b;
}
//typedef cal* create_c();
//typedef void destroy_c(cal*);
extern "C" cal* create(){
return new cal;
}
extern "C" void destroy(cal* c) {
delete c;
}
b)编译成可执行文件
cd到cppcppl2.cpp所在目录,输入命令
g++ -fPIC -shared -o libcppl2.so cppl2.cpp
会在当前目录生成文件libcppl2.so
2)主程序
a)源码
//cppcppl2.cpp
#include <stdio.h>
#include <dlfcn.h>
#include "cppl2.h"
using namespace std;
int main() {
void* handle;
handle = dlopen("./libcppl2.so", RTLD_LAZY);
creat_t createcal = (creat_t)dlsym(handle, "create");
destroy_t destroycal = (destroy_t)dlsym(handle, "destroy");
cal* _cal = createcal();
int result = _cal->add(3, 4);
printf("%d\n", result);
destroycal(_cal);
dlclose(handle);
return 0;
}
b)编译成可执行文件
cd到cppcppl2.cpp所在目录,输入命令
g++ cppcppl2.cpp -o cppcppl2 -ldl
3)执行
cd到可执行文件cppcppl1所在目录
输入命令
./cppcppl2