4

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!

2
  • What happens if you have foo take a boost::python::object argument, and then extract the shared_ptr from that? Commented May 18, 2012 at 17:55
  • Sure, that would work, but I was hoping there would be a way without writing any additional wrappers for foo (there are quite a lot of those that I would need ) Commented May 18, 2012 at 23:27

1 Answer 1

4

The problem is that you're asking for a non-const reference to a shared_ptr<A>, and your b instance in Python simply doesn't contain one; it contains a shared_ptr<B>. While shared_ptr<B> can be implicitly converted to shared_ptr<A>, shared_ptr<B>& cannot be implicitly converted to shared_ptr<A>&.

If you can modify foo to take a shared_ptr<A>, or shared_ptr<A> const &, that will solve your problem.

If not, you'll need to also wrap a version that accepts shared_ptr<B>&.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.