Revealing polymorphism with boost python
I'm starting to get really frustrated trying to expose simple C ++ polymorphism for python with boost :: python.
I have the following structure in 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);
}
And in Python, I just want to have this:
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
Is there a way to do this at all? Or is it not possible, as in C ++?
Many thanks for your help!
+3
source to share
1 answer
Ok, I missed the virtual destructor in the base class. So, this is how it works:
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>());
}
But now I have a different problem. When I try to return this type in a tuple, I again lose the type information:
tuple returnSomethingDerivedFromBase(...) {
Derived *ret = new Derived;
ret->derivedProperty = 1234;
return make_tuple(ret);
}
+3
source to share