c++ - 使用 Boost Python & std::shared_ptr

标签 c++ boost c++11 boost-python

我正在尝试让 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 可以很好地使用它)但是要更改的代码量相当可观,我想使用标准库。

circle 方法声明如下:

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

这样的 anchor 类:

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 的模板函数 shared_ptr_to_python(shared_ptr const& x) 的实现(它解释了为什么代码适用于boost::shared_ptr)。

我认为你有几个选择:

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

关于c++ - 使用 Boost Python & std::shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13986581/

相关文章:

c++ - 使用 boost::optional 制作可选的 std::function 参数

c++ - 在 C++ 中动态分配输入和输出二维数组

c++ - 迭代器和简单的赋值/析构函数

c++ - C++ 中的模板仅在 long 数据类型上出错

c# - 引发异常后未释放 Boost 共享互斥锁

c++ - Boost asio 无法在所有线程上运行 io 服务。io 服务在第一个线程调用时阻塞

c++ - 如何跳过基于范围的 for 循环的第一次迭代?

c++ - 在 C++ 中将非常量引用传递给右值

c++ - 使用 Thrust 进行流压缩;最佳实践和最快方法?

c++ - 在 Xcode 中使用 std::variant