[英]boost::python pure virtual base class with static factory constructor and std::unique_ptr
我已经查看了所有可以找到的相关问题,但无法针对这种特定情况提出答案。
我有一个C ++纯虚拟基类接口,我想将其公开给Python。 该实现继承自Base,并且不会公开:
struct Base : private boost::noncopyable
{
static std::unique_ptr<Base> create();
virtual ~Base();
virtual int get_int() = 0;
virtual void set_int(const int i) = 0;
};
我不需要Python来继承Base,而只是能够通过create()
工厂函数构造新的Base实例。
我尝试了两种使用boost :: python包装的方法。 首先,类似于Boost.Python:如何公开std :: unique_ptr我试图创建一个__init__
函数来释放unique_ptr:
namespace bp = boost::python;
bp::class_<Base, boost::noncopyable>("Base", bp::no_init)
.def("__init__",
bp::make_function([](Base& self) { return Master::create().release(); },
bp::return_value_policy<bp::manage_new_object>(),
boost::mpl::vector<Base*, Base&>(), "Create a new Base")
.staticmethod("__init__")
这可以在Python中编译和加载,但是__init__
实际上不是静态的!
create(...)
create( (Base)arg1) -> Base :
Create a new Base
C++ signature :
Base* create(Base {lvalue})
我尝试的make_constructor
方法是使用make_constructor
,如下所示:
namespace bp = boost::python;
bp::class_<Base, boost::noncopyable, std::unique_ptr<Base>>("Base", bp::no_init)
.def("__init__", bp::make_constructor(&Base::create));
bp::register_ptr_to_python<std::unique_ptr<Master>>();
但这不能编译: /usr/include/boost/python/make_constructor.hpp:40:20: fatal error: call to deleted constructor of std::unique_ptr<Base, std::default_delete<Base>> dispatch(x, is_pointer<T>());
我可以通过从std :: unique_ptr切换到std :: shared_ptr来使用第二种方法来使绑定工作,因为shared_ptr是默认可构造的。
这是可能的,因为我能够修改C ++库源代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.