使用Boost Python和std :: shared_ptr

Lia*_*m M 15 c++ boost boost-python c++11

我试图让Boost Python与std :: shared_ptr很好地配合.目前,我收到此错误:

Traceback (most recent call last):
  File "test.py", line 13, in <module>
    comp.place_annotation(circle.centre())
TypeError: No to_python (by-value) converter found for C++ type: std::shared_ptr<cgl::Anchor>
Run Code Online (Sandbox Code Playgroud)

从调用circle.centre(),它返回一个std :: shared_ptr.我可以将每个std :: shared_ptr更改为boost :: shared_ptr(Boost Python可以很好地使用)但是要改变的代码量相当大,我想使用标准库.

circle方法声明如下:

const std::shared_ptr<Anchor> centre() const
{
    return Centre;
}
Run Code Online (Sandbox Code Playgroud)

像这样的锚类:

class Anchor
{
    Point Where;
    Annotation* Parent;
public:

    Anchor(Annotation* parent) :
        Parent(parent)
    {
        // Do nothing.
    }

    void update(const Renderer& renderer)
    {
        if(Parent)
        {
            Parent->update(renderer);
        }
    }

    void set(Point point)
    {
        Where = point;
    }

    Point where() const
    {
        return Where;
    }
};
Run Code Online (Sandbox Code Playgroud)

相关的Boost Python代码是:

class_<Circle, bases<Annotation> >("Circle", init<float>())
.def("radius", &Circle::radius)
    .def("set_radius",  &Circle::set_radius)
    .def("diameter", &Circle::diameter)
    .def("top_left", &Circle::top_left)
    .def("centre", &Circle::centre);

// The anchor base class.
class_<Anchor, boost::noncopyable>("Anchor", no_init)
    .def("where", &Anchor::where);
Run Code Online (Sandbox Code Playgroud)

我正在使用Boost 1.48.0.有任何想法吗?

Dmi*_*riy 16

看起来像boost :: python不支持C++ 11 std :: shared_ptr.

如果你看看到文件升压/蟒蛇/转换器/ shared_ptr_to_python.hpp你会发现执行模板功能shared_ptr_to_python升压(shared_ptr的<T> const的&X):: shared_ptr的的(它解释了为什么代码工作正常进行的boost :: shared_ptr的).

我想你有几个选择:

  • 使用boost :: shared_ptr(你试图避免)
  • 为std :: shared_ptr编写shared_ptr_to_python的实现(恕我直言,最佳选择)
  • 发送请求到boost :: python开发人员以支持std :: shared_ptr


cdy*_*n37 6

除非我误解了,否则我认为这解决了你的问题:

boost::python::register_ptr_to_python<std::shared_ptr<Anchor>>();
Run Code Online (Sandbox Code Playgroud)

http://www.boost.org/doc/libs/1_57_0/libs/python/doc/v2/register_ptr_to_python.html