python - Boost.Python 返回不可复制对象的列表

标签 python c++ boost-python

我有一个不可复制的类型 X,我想公开一个创建它们的 list 的函数:

#include <boost/python.hpp>

namespace py = boost::python;

struct X {
    X(int i) : i(i) { }
    X(const X& ) = delete;
    X& operator=(X const&) = delete;

    int i;
    friend std::ostream& operator<<(std::ostream& os, X const& x) {
        return os << "X(" << x.i << ")";
    }
};

py::list get_xs(int n) {
    py::list xs;
    for (int i = 0; i < n; ++i) {
        xs.append(X{i});
    }
    return xs;
}

BOOST_PYTHON_MODULE(Foo)
{
    py::class_<X, boost::noncopyable>("X", py::init<int>())
        .def(str(py::self))
        .def(repr(py::self))
    ;

    py::def("get_xs", get_xs);
}

这编译得很好,但是当我尝试使用它时,却给我带来了可怕的后果:

>>> import Foo
>>> Foo.get_xs(10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: No to_python (by-value) converter found for C++ type: X

该错误的实际含义是什么?我该如何解决?

最佳答案

noncopyable 看起来是问题所在。当 X 可复制时,一切都很好。

如果 X 必须是 noncopyable 则可以使用 boost::shared_ptr:

py::list get_xs(int n) {
    py::list xs;
    for (int i = 0; i < n; ++i) {
        xs.append(boost::shared_ptr<X>(new X(i)));
    }
    return xs;
}

....

BOOST_PYTHON_MODULE(Foo)
{
    py::class_<X, boost::shared_ptr<X>, boost::noncopyable>("X", py::init<int>())
    ...
    ...

    py::register_ptr_to_python<boost::shared_ptr<X>>();
}

关于python - Boost.Python 返回不可复制对象的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36262320/

相关文章:

javascript - 无法访问 Django + Angular 项目中的服务器媒体文件

python - 如何删除具有一定计数条件的列

c++ - CL.exe 在 Visual Studio 2012 中崩溃

c++ - 在不同的 main() 之间轻松切换

c++ - 如何在不使用 to_string 或 stoi 的情况下将 int 转换为 C++11 中的字符串?

c++ - 构建 boost-python 示例

python - 如何从 boost 线程调用 Python?

python - Django : global search in different model - Post result does not appears

c++ - 从暴露类返回提升列表

python - 使用 MySQLdb 在 Python 中执行 .sql 文件