使用 Boost Python 和 std::shared_ptr

2024-02-28

我正在尝试让 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>

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

圆方法声明如下:

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

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

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


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

如果您查看文件 boost/python/converter/shared_ptr_to_python.hpp 您会发现 boost::shared_ptr 的模板函数共享_ptr_to_python(shared_ptr const& x) 的实现(它解释了为什么代码可以很好地用于 boost::共享指针)。

我认为你有几个选择:

  • 使用 boost::shared_ptr (你试图避免)
  • 为 std::shared_ptr 编写 shared_ptr_to_python 的实现(恕我直言,最好的选择)
  • 向 boost::python 开发人员发送请求以支持 std::shared_ptr
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Boost Python 和 std::shared_ptr 的相关文章

随机推荐