简体   繁体   中英

Using Boost Python with shared_ptr<const T>

Boost Python 1.63 (python 2.7.13) works well with shared_ptr<T> ; if I write this in C++:

shared_ptr<Foo> create_shared_ptr() { return shared_ptr{...}; }
void accept_shared_ptr(const shared_ptr<Foo>& p) { }

...

class_<Foo, boost::noncopyable>("Foo", no_init); //Expose abstract class

register_ptr_to_python< shared_ptr<Foo> >();
def("create_shared_ptr", create_shared_ptr);
def("accept_shared_ptr", accept_shared_ptr);

Then I can write this in Python and everything works:

accept_shared_ptr(create_shared_ptr())

The problem comes when I try and wrap shared_ptr<const Foo> . (Which I need to do because I am wrapping a library that returns this.) If I modify the C++ functions as follows:

shared_ptr<const Foo> create_shared_ptr() { return shared_ptr{...}; }
void accept_shared_ptr(const shared_ptr<const Foo>& p) { }

Then I get the error:

 Boost.Python.ArgumentError: Python argument types in mod_python.accept_shared_ptr(Foo) did not match C++ signature: accept_shared_ptr(std::shared_ptr<Foo const>) 

It seems the internals are implementing conversion from python Foo to C++ shared_ptr<Foo> , but not to C++ shared_ptr<const Foo> . Using

register_ptr_to_python< shared_ptr<const Foo> >();

doesn't help. How can I fix this?

The issue must be in the definitions of your classes/methods. This code works for me (I have boost 1.62 and python 2.7.13):

class Foo {
public:
    virtual ~Foo() = default;
    virtual std::string xxx() = 0;
};

class Bar: public Foo {
public:
    ~Bar() override = default;
    std::string xxx() override { return "xxx"; }
};

std::shared_ptr<const Foo> create_shared_ptr() {
    return std::shared_ptr<const Foo>(new Bar);
}

void accept_shared_ptr(const std::shared_ptr<const Foo>& p) 
{
    ; // do nothing
}

BOOST_PYTHON_MODULE(myLib)
{
    using namespace boost::python;
    class_<Foo, boost::noncopyable>("Foo", no_init);
    register_ptr_to_python< std::shared_ptr<const Foo> >();
    def("create_shared_ptr", create_shared_ptr);
    def("accept_shared_ptr", accept_shared_ptr);
}

Then, in python I can do:

$ python
Python 2.7.13 (default, Jan 19 2017, 14:48:08) 
[GCC 6.3.0 20170118] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import myLib
>>> ptr = myLib.create_shared_ptr()
>>> ptr
<myLib.Foo object at 0x7f8b5fde0aa0>
>>> myLib.accept_shared_ptr(ptr)

Most probably your function create_shared_ptr somehow returns a wrong value that is misunderstood by python.

Adding

implicitly_convertible<std::shared_ptr<Foo>,std::shared_ptr<const Foo>>();

solves the problem.

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