Boost.Python and polymorphic behavior with std :: shared_ptr

I would like to know how classes Aand Bbelow can work polymorphically in python when used std::shared_ptrinstead boost::shared_ptr?

struct A
{
    virtual ~A() {}
};

struct B : A
{
    B() {}
    virtual ~B() {}
};

void f(const std::shared_ptr<A>& ptr)
{}

BOOST_PYTHON_MODULE(test)
{
    class_<A, boost::noncopyable>("A", no_init);

    class_<B, std::shared_ptr<B>, bases<A>>("B")
        .def(init<>());

    def("f", f);
}

I know that a method boost::get_pointermust be defined for std::shared_ptr, so I have to make sure that the following lines exist before #include <boost/python.hpp>:

namespace boost {
template<class T> const T* get_pointer(const std::shared_ptr<T>& p)
{
    return p.get();
}

template<class T> T* get_pointer(std::shared_ptr<T>& p)
{
    return p.get();
}
} // namespace boost

Now, in python, I'm trying:

>>> from test import *
>>> b = B()
>>> f(b)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
ArgumentError: Python argument types in
    test.f(B)
did not match C++ signature:
    f(std::shared_ptr<A>)

Note. The code above works fine for boost::shared_ptr, but instead, I want to stick with C ++ 11 types.

Thank.

+3
source share
2 answers

Boost.Python , boost:: shared_ptr. std:: shared_ptr. boost:: shared_ptr.

0

std::shared_ptr boost:: python IIRC, get_pointer . ( ). , class_<A,std::shared_ptr<A>,...>, , .

0

All Articles