使用Boost Python的性病:: shared_ptr的(Using Boost Python

2019-08-04 11:16发布

我试图让升压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>

从调用circle.centre(),它返回一个std :: shared_ptr的。 我可以shared_ptr的改变每标准::到一个boost :: shared_ptr的(其升压用Python很好地扮演),但是代码量的改变相当可观的,我想使用标准库。

Circle方法声明如下:

const std::shared_ptr<Anchor> centre() const
{
    return Centre;
}

锚类是这样的:

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;
    }
};

而相关的升压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);

我使用升压1.48.0。 有任何想法吗?

Answer 1:

貌似的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的(你试图避免)
  • 写你shared_ptr_to_python的实施的std :: shared_ptr的(恕我直言最好的选择)
  • 发送请求的boost :: Python开发者支持的std :: shared_ptr的


Answer 2:

除非我误解了,我想这能解决你的问题:

boost::python::register_ptr_to_python<std::shared_ptr<Anchor>>();

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



Answer 3:

有此错误报告: https://svn.boost.org/trac/boost/ticket/6545

貌似有人在努力。



Answer 4:

从A段http://boost.2283326.n4.nabble.com/No-automatic-upcasting-with-std-shared-ptr-in-function-calls-td4573165.html :

/* make boost::python understand std::shared_ptr */
namespace boost {
       template<typename T>
       T *get_pointer(std::shared_ptr<T> p)
       {
               return p.get();
       }
}

为我工作。 你会定义类,比如:

class_<foo, std::shared_ptr<foo>>("Foo", ...);

有了这个,其他方法返回std::shared_ptr<foo>将只是工作。

有些魔术可能需要虚函数/多态性,应该在我挂线覆盖。



文章来源: Using Boost Python & std::shared_ptr