BOOST.PYTHON如何公开boost :: shared_ptr的Typedef

boost.Python How to expose typedef of boost::shared_ptr?

本文关键字:ptr Typedef shared BOOST 何公开 boost PYTHON      更新时间:2023-10-16

我的C 类定义为:

class MyFuture {
public:
    virtual bool isDone() = 0;
    virtual const std::string& get() = 0;
    virtual void onDone(MyCallBack& callBack) = 0;
    virtual ~MyFuture() { /* empty */ } 
};
typedef boost::shared_ptr<MyFuture> MyFuturePtr;

我使用boost.python将课程暴露于Python(此类从未在Python中创建,而是从API调用返回,因此noncopyable):

BOOST_PYTHON_MODULE(MySDK)
{
    class_<MyFuture, noncopyable>("MyFuture", no_init)
        .def("isDone", &MyFuture::isDone)
        .def("get", &MyFuture::get, return_value_policy<copy_const_reference>())
        .def("onDone", &MyFuture::onDone)
    ;
}

来自Python,我像以下方式一样使用它:

import MySDK
def main():
    # more code here ...
    future = session.submit()
    response = future.get
    print response
if __name__ == "__main__":
    main()      

,但这导致python错误:

File "main.py", line 14, in main
    future = session.submit()
TypeError: No to_python (by-value) converter found for C++ type: class boost::shared_ptr<class MySDK::MyFuture>     

如何公开Typedef typedef boost::shared_ptr<MyFuture> MyFuturePtr;

update

使用boost.python更改类公开:

class_<MyFuture, boost::shared_ptr<MyFuture> >("MyFuture", no_init)

导致编译器错误:

boostpythonconverteras_to_python_function.hpp(21): 
    error C2259: 'MySDK::MyFuture' : cannot instantiate abstract class
class_<MyFuture, boost::shared_ptr<MyFuture>, boost::noncopyable>("MyFuture")

根据文档

http://www.boost.org/doc/libs/1_62_0/libs/python/doc/doc/html/reference/high-high high-level_components.html#high_le_level_level_level_boost_component