简体   繁体   中英

conversion of boost::shared_ptr in boost::python function call

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 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>& .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM