python - 使用 boost python 暴露多态性

标签 python c++ boost boost-python

尝试使用 boost::python 向 python 公开一个简单的 C++ 多态性时,我开始感到非常沮丧。

我在 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++ 中那样可能吗?

非常感谢您的帮助!

最佳答案

好的,我错过了 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);
}

关于python - 使用 boost python 暴露多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26522213/

相关文章:

Python 请求返回 200 而不是 301

Python多重继承和MRO

c++ - C++ 中的 "double free or corruption"错误

c++ - 在 Yosemite Boost 错误上安装 caffe

python - python 的更新未显示在终端上

python - Pandas 随时间绘制计数器的累计总和

c++ - 将 2 个双数组组合成一个找到它们的并集和交集的最简单方法

c++ - Visual Studio 2015 诊断工具内存使用和 C++ 调试

c++ - 访问构建 boost::thread 的可调用对象

c++ - Boost Beast 异步服务器因断言失败而失败:(id_!= T::id) 在多个 aync 调用中