首页 > 编程 > C++ > 正文

c++调用c++的so动态库2

2019-11-10 18:15:19
字体:
来源:转载
供稿:网友

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 -ldl

3)执行

cd到可执行文件cppcppl1所在目录

输入命令

./cppcppl2
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选