Consider the following example:
#include "Python.h"
#include <boost/python.hpp>
#include <boost/shared_ptr.hpp>
class A {};
class B : public A{};
void foo(boost::shared_ptr<A>& aptr) { }
BOOST_PYTHON_MODULE(mypy)
{
using namespace boost::python;
class_<A, boost::shared_ptr<A> >("A", init<>());
class_<B, boost::shared_ptr<B>, bases<A> >("B", init<>());
def("foo", foo);
}
if I call the python code
import mypy
b = mypy.B()
mypy.foo(b)
I get
ArgumentError: Python argument types in
mypy.foo(B)
did not match C++ signature:
foo(boost::shared_ptr<A> {lvalue})
I have googled around quite alot, but I can’t find a good explanation / fix / workaround for this. Any help is quite welcome!
The problem is that you’re asking for a non-const reference to a
shared_ptr<A>, and yourbinstance in Python simply doesn’t contain one; it contains ashared_ptr<B>. Whileshared_ptr<B>can be implicitly converted toshared_ptr<A>,shared_ptr<B>&cannot be implicitly converted toshared_ptr<A>&.If you can modify
footo take ashared_ptr<A>, orshared_ptr<A> const &, that will solve your problem.If not, you’ll need to also wrap a version that accepts
shared_ptr<B>&.