Boost Python: How To Call A C++ Virtual Function
Solution 1:
The problem here is that Boost.Python is deep-copying your derived-class object and slicing it into a base object when it converts it to Python; there's no need to tell Boost.Python about a function being virtual at all unless you need to override it in Python (and it sounds like you don't).
It's doing that copy to be safe: it's making certain that the object Python is given won't be deleted by C++ while Python still has a reference to it. And it's slicing it to Base
- I think - because it doesn't know anything about Derived
.
I can think of two ways to fix this:
Provide a trivial wrapper for
Derived
. Boost.Python will still copy it when converting it to Python, but it won't slice it into aBase
anymore when it does so.Register a
shared_ptr
conversion forBase
(viaregister_ptr_to_python< boost::shared_ptr<Base> >()
), create yourDerived
instance in ashared_ptr
, and pass that as the argument to your Python function. Now Boost.Python knows the C++ object can't get deleted while the Python object exists, because the Python wrapper holds ashared_ptr
reference to it.
Post a Comment for "Boost Python: How To Call A C++ Virtual Function"