您的位置:首页 > 运维架构 > Linux

Linux shared library-- Loading class

2010-04-26 16:58 218 查看
Linked from: http://www.faqs.org/docs/Linux-mini/C++-dlopen.html
//1.==== main.cpp =============================================================

// How to build?

// g++ main.cpp -ldl

//=============================================================================

#include "polygon.h"

#include <iostream>

#include <dlfcn.h>

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;

}

// load the symbols

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

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

if (!create_triangle || !destroy_triangle) {

cerr << "Cannot load symbols: " << dlerror() << '/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);

}

//2.=====polygon.h======================================

#ifndef POLYGON_HPP

#define POLYGON_HPP

class polygon {

protected:

double side_length_;

public:

polygon()

: side_length_(0) {}

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

//3.=====triangle.cpp=================================

// How to build?

// g++ -c -fPIC triangle.cpp

// g++ -shared -o triangle.so
-fPIC
triangle.o

//=================================================

#include "polygon.h"

#include <cmath>

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐