Linux shared library-- Loading class

来源:互联网 发布:网络基础知识培训 编辑:程序博客网 时间:2024/05/17 09:09

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;
}

原创粉丝点击