Python返回不可复制对象的列表
我有一个不可复制的Python返回不可复制对象的列表,python,c++,boost-python,Python,C++,Boost Python,我有一个不可复制的X类型,我想公开一个创建列表的函数: #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& oper
X
类型,我想公开一个创建列表的函数:
#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);
}
#包括
名称空间py=boost::python;
结构X{
X(inti):i(i){}
X(常数X&)=删除;
X&运算符=(X常量&)=删除;
int i;
friend std::ostream&operator>Foo.get_xs(10)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:没有为C++类型找到的TyPython(按值)转换器:X
这个错误到底是什么意思?我该如何修复它呢?不可复制
似乎是问题所在。当X
可复制时,一切都很好
如果X
必须是noncopyable
,则可以使用boost::shared\u 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>>();
}
py::list get_xs(int n){
py::list xs;
对于(int i=0;i
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>>();
}