Python返回一个不可编译对象的列表
Boost.Python return a list of noncopyable objects
我有一个不可压缩的类型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>>();
}
相关文章:
- 我可以将一个用clang c++11编译的对象与另一个用c++17编译的对象链接起来吗
- std::vector::p ush_back() 不会在 MSVC 上编译具有已删除移动构造函数的对象
- 是否可以在编译时初始化对象的 C 样式函数指针,以便它调用对象的成员函数?
- 如何制作一个作为类对象并具有编译时大小的数组?
- 由于缺少类模板,NVCC 编译面向对象代码时出现问题
- 编译时生成应在构造函数中创建的非 constexpr 对象数组
- 仅为从某种语言编译的对象添加链接库?
- 确保在编译期间仅同时使用来自同一工厂的对象
- 编译错误:临时对象构造函数中缺少参数
- 将 std::variant 与 gmock 1.8 对象一起使用时编译错误
- CMake + Qt,moc 编译失败,无法实现 QMetaObject 方法(编译器找不到基本 ui 对象的标头?
- 混合单独编译的对象
- 当自动编译对象文件时,如何使我的makefile使用我的cflags标志
- 默认情况下,仅使用生成文件编译对象
- 在 Eclipse 中保存时自动编译对象文件
- Python返回一个不可编译对象的列表
- 编译对象后链接共享库时出错
- 编译对象文件时出现g++错误
- 在单独的文件夹中编译对象,隐式规则不匹配
- 创建一个简单的"hello world"并将其与 2 个预编译对象链接在一起