暴露多态性与boost python

时间:2014-10-23 06:10:27

标签: python c++ boost boost-python

我开始变得非常沮丧,尝试使用boost :: python将简单的C ++多态性暴露给python。

我在C ++中有以下结构:

struct Base {
    int typeID;
};

struct Derived : public Base {
    int derivedProperty;
}

//and some more from base derived types....    

Base *returnSomethingDerivedFromBase(...) {
    Derived *ret = new Derived;
    ret->derivedProperty = 1234;
    return ret;
}

BOOST_PYTHON_MODULE(foo) 
{
    class_<Base>("Base")
        .add_property("baseProperty", &Base::baseProperty);

    class_<Derived, bases<Base> >("Derived")
        .add_property("derivedProperty", &Derived::derivedProperty);

    def("returnSomethingDerivedFromBase", returnSomethingDerivedFromBase);    
}

在Python中我只想拥有以下内容:

object = returnSomethingFromDerived() #object is of type Base
if object.typeID = 1:
    #here i want to cast to Derived and access "derivedProperty"
    #but this is not working :-( :
    object.__class__ = Derived

有没有办法实现这一目标?或者这不可能像在C ++中一样吗?

非常感谢你的帮助!!

1 个答案:

答案 0 :(得分:3)

好的,我错过了Base类中的虚析构函数。所以这是它的工作原理:

struct Base {
    virtual ~Base() {}
    int typeID;
};

struct Derived : public Base {
    int derivedProperty;
}

//and some more from base derived types....    

Base *returnSomethingDerivedFromBase(...) {
    Derived *ret = new Derived;
    ret->derivedProperty = 1234;
    return ret;
}

BOOST_PYTHON_MODULE(foo) 
{
    class_<Base>("Base")
        .add_property("baseProperty", &Base::baseProperty);

    class_<Derived, bases<Base> >("Derived")
        .add_property("derivedProperty", &Derived::derivedProperty);

    def("returnSomethingDerivedFromBase", returnSomethingDerivedFromBase, return_value_policy<manage_new_object>());    
}

但现在我有一个不同的问题。当我尝试在元组中返回此类型时,我再次丢失类型信息:

tuple returnSomethingDerivedFromBase(...) {
    Derived *ret = new Derived;
    ret->derivedProperty = 1234;
    return make_tuple(ret);
}