Boost.Python:使用继承

An example

#include <boost/python.hpp>
#include <memory>
#include <iostream>

using namespace std;
using namespace boost::python;

#define show(x) cout << x << endl

struct Base{
    Base() { show("Base+"); }
    virtual ~Base() { show("Base-"); }

    virtual const char* name() const {
        return "Base";
    }
};

struct Derived : Base{
    int x;
    Derived() : x(123) { show("Derived+"); }
    ~Derived() { show("Derived-"); }

    virtual const char* name() const {
        return "Derived";
    }
};


shared_ptr<Base> derived_as_base(){
    return shared_ptr<Base>(new Derived);
}

const char* get_name(const Base& b){
    return b.name();
}

int get_derived_x(const Derived& d){
    return d.x;
}

BOOST_PYTHON_MODULE(foo_ext){
    class_<Base, shared_ptr<Base>>("Base"); // should provide HeldType
    class_<Derived, bases<Base>>("Derived");

    def("derived_as_base", derived_as_base);
    def("get_name", get_name);
    def("get_derived_x", get_derived_x);
}

Reference

posted @ 2014-12-19 01:38  n0p  阅读(385)  评论(0编辑  收藏  举报