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

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







  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值