【问题标题】:boost.Python How to expose typedef of boost::shared_ptr?boost.Python 如何公开 boost::shared_ptr 的 typedef?
【发布时间】:2016-12-13 09:54:31
【问题描述】:

我有一个 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&lt;MyFuture&gt; MyFuturePtr;

更新

将使用 boost.Python 的类公开更改为:

class_&lt;MyFuture, boost::shared_ptr&lt;MyFuture&gt; &gt;("MyFuture", no_init)

导致编译错误:

boost\python\converter\as_to_python_function.hpp(21): 
    error C2259: 'MySDK::MyFuture' : cannot instantiate abstract class

【问题讨论】:

    标签: c++ boost boost-python


    【解决方案1】:

    【讨论】:

    • @GiovanniAzua 文档中有关于抽象类包装器的部分。您可能不得不卷起袖子阅读。我最初的怀疑是 boost::python 当前假设它可以创建一个 MyFuture,给定您创建的类定义。当然不能,因为它是一个抽象类。一定有办法注释它说没有构造函数。
    • @(Richard Hodges) 很公平,我一直在这样做,但没有关于这个案例的明显文档,一直在研究,因此是 OP。
    • @GiovanniAzua 找到了这个帖子。希望对您有所帮助:code.activestate.com/lists/python-cplusplus-sig/17171
    • @(Richard Hodges) 实际上它确实有帮助!我注意到我用shared_ptr&lt;ClusterFuture&gt; 替换了noncopyable 模板参数,它们可以共存,如链接示例中所示。请将您的答案修改为class_&lt;MyFuture, boost::shared_ptr&lt;MyFuture&gt;, noncopyable&gt;("MyFuture"),我会接受它,因为它解决了 OP
    猜你喜欢
    • 2011-03-04
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多