i am starting to get really frustrated trying to expose a simple C++ polymorphism to python with boost::python.
I do 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 the following:
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 accomplish this at all? Or isn´t this possible as it would be in C++ ?
Thanks a lot for your help!!
Ok, i missed the virtual destructor in the Base class. So here 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 info:
tuple returnSomethingDerivedFromBase(...) {
Derived *ret = new Derived;
ret->derivedProperty = 1234;
return make_tuple(ret);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.