boost::p ython 纯虚拟基类,具有静态工厂构造函数和 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() factory 函数构造新的 Base 实例。

我尝试了两种使用 boost::p ython 包装的方法。首先,类似于 Boost.Python:如何公开 std::unique_ptr 我尝试创建一个发布unique_ptr的__init__函数:

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

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++库源。

相关内容

最新更新