????4?????c++????????ú???class??.so?????????????????????????????C++ dlopen mini HOWTO??
????1)???????????triangle.so???

// polygon.h
#ifndef __POLYGON_H__
#define __POLYGON_H__
class Polygon
{
protected:
double m_side_len;
public:
Polygon() : m_side_len(0) {}
virtual ~Polygon() {}
void set_side_len(double side_len)
{
m_side_len = side_len;
}
virtual double area() const = 0;
};
typedef Polygon* create_t();
typedef void destroy_t(Polygon*);
#endif /* __POLYGON_H__ */
// triangle.cpp
#include "polygon.h"
#include <cmath>
class Triangle: public Polygon
{
public:
virtual double area() const
{
return m_side_len * m_side_len * sqrt(3) / 2;
}
};
extern "C" Polygon* create()
{
return new Triangle;
}
extern "C" void destroy(Polygon *p)
{
delete p;
}
???????????? triangle.so
????-
????[steven@sasd c++]$ g++ -fPIC -shared -o triangle.so triangle.cpp
????-
????2) ???????????
// ex_dload_cppso.cpp
#include <iostream>
#include <string>
#include <dlfcn.h>
using namespace std;
#include "polygon.h"
int main()
{
// load triangle library
void *triangle = dlopen("./triangle.so"?? RTLD_LAZY);
if (!triangle)
{
cerr << "Can not load library: " << dlerror() << endl;
return -1;
}
// reset errors
dlerror();
// load the symbols "create"
create_t *create_triangle = (create_t*) dlsym(triangle?? "create");
const char *dlsym_err = dlerror();
if (dlsym_err)
{
cerr << "Can not load symbol create: " << dlsym_err << endl;
return -2;
}
// load the symbols "destroy"
destroy_t* destroy_triangle = (destroy_t*) dlsym(triangle?? "destroy");
dlsym_err = dlerror();
if (dlsym_err)
{
cerr << "Can not load symbol destroy: " << dlsym_err << endl;
return -2;
}
// create an instance of class <Trangle>
Polygon *poly = create_triangle();
// set side length of <Triagle>
poly->set_side_len(8);
cout << "The area is " << poly->area() << endl;
// destroy the class
destroy_triangle(poly);
// unload the triangle.so library
dlclose(triangle);
return 0;
}
???????????У?
????[steven@sasd c++]$ g++ -ldl -o ex_dload_cppso ex_dload_cppso.cpp
????[steven@sasd c++]$ ./ex_dload_cppso
????The area is 55.4256
????[steven@sasd c++]$