1.环境
Ubuntu 14.04
g++ 4.8.4
2.有类的情况
1)库文件
a)源码
//cppl2.hclass 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.so2)主程序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 -ldl3)执行
cd到可执行文件cppcppl1所在目录
输入命令
./cppcppl2
新闻热点
疑难解答
图片精选