2016-03-28 58 views
1

我有一个类型X这是不可复制的列表,我要揭露创建它们的list功能:Boost.Python的返回不可复制的对象

#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 

这个错误实际上是什么意思?我如何解决它?

回答

1

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