c语言 dlsym 用法,使用dlopen和dlsym来使用C++中的类

#include int main() {

using std::cout;

using std::cerr;

// load the triangle library

void* triangle = dlopen("./triangle.so", RTLD_LAZY);

if (!triangle) {

cerr << "Cannot load library: " << dlerror() << '\n';

return 1;

}

// reset errors

dlerror();

// load the symbols

create_t* create_triangle = (create_t*) dlsym(triangle, "create");

const char* dlsym_error = dlerror();

if (dlsym_error) {

cerr << "Cannot load symbol create: " << dlsym_error << '\n';

return 1;

}

destroy_t* destroy_triangle = (destroy_t*) dlsym(triangle, "destroy");

dlsym_error = dlerror();

if (dlsym_error) {

cerr << "Cannot load symbol destroy: " << dlsym_error << '\n';

return 1;

}

// create an instance of the class

polygon* poly = create_triangle();

// use the class

poly->set_side_length(7);

cout << "The area is: " << poly->area() << '\n';

// destroy the class

destroy_triangle(poly);

// unload the triangle library

dlclose(triangle);

}

//----------

//polygon.hpp:

//----------

#ifndef POLYGON_HPP

#define POLYGON_HPP

class polygon {

protected:

double side_length_;

public:

polygon()

: side_length_(0) {}

virtual ~polygon() {}

void set_side_length(double side_length) {

side_length_ = side_length;

}

virtual double area() const = 0;

};

// the types of the class factories

typedef polygon* create_t();

typedef void destroy_t(polygon*);

#endif

//----------

//triangle.cpp:

//----------

#include "polygon.hpp"

#include class triangle : public polygon {

public:

virtual double area() const {

return side_length_ * side_length_ * sqrt(3) / 2;

}

};

// the class factories

extern "C" polygon* create() {

return new triangle;

}

extern "C" void destroy(polygon* p) {

delete p;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值