【问题标题】:Boost-Python raw pointers constructorsBoost-Python 原始指针构造函数
【发布时间】:2010-06-23 09:12:24
【问题描述】:

我正在尝试使用 boost-python 向 python 公开一个 C++ 库。该库实际上包装了一个底层 C api,因此大量使用原始指针。

// implementation of function that creates a Request object
inline Request Service::createRequest(const char* operation) const
{
    blpapi_Request_t *request;
    ExceptionUtil::throwOnError(
            blpapi_Service_createRequest(d_handle, &request, operation)
        );
    return Request(request);
}

// request.h
class Request {
    blpapi_Request_t *d_handle;
    Element           d_elements;
    Request& operator=(const Request& rhs); // not implemented
public:
    explicit Request(blpapi_Request_t *handle); 
    Request(RequestRef ref);
    Request(Request &src);
};

// request.cpp
BOOST_PYTHON_MODULE(request)
{
    class_<blpapi_Request_t>;
    class_<Request, boost::noncopyable>("Request", init<blpapi_Request_t *>())
    .def(init<Request&>())
    ;
}

虽然 request.cpp 编译成功,但当我尝试使用该对象时,出现以下错误:

// error output
TypeError: No to_python (by-value) converter found for C++ type: class Request

为了调用它,python 代码如下所示:

from session import *
from service import *
from request import *

so = SessionOptions()
so.setServerHost('localhost')
so.setServerPort(8194)

session = Session(so)

# start sesssion
if not session.start():
    print 'Failed to start session'
    raise Exception

if not session.openService('//blp/refdata'):
    print 'Failed to open service //blp/refdata'
    raise Exception

service = session.getService('//blp/refdata')
request = service.createRequest('ReferenceDataRequest')

其他对象(SessionOptions、Session、Service)等也是我已成功为其创建 boost-python 包装器的 c++ 对象。

据我从 boost-python 文档了解到,这与传递原始指针有关,但我真的不明白我还应该做什么......

【问题讨论】:

    标签: c++ python boost pointers


    【解决方案1】:

    您的class_&lt;blpapi_Request_t&gt;; 没有声明任何内容;那个代码是正确的版本吗?

    如果是,那么更新它:

    class_<blpapi_Request_t>("blpapi_Request_t");
    

    也就是说,该错误表明您正在尝试使用 Request 对象并自动转换为尚未定义的 python 对象。

    你得到这个错误的原因是你把Request包装成boost::noncopyable,然后提供了一个工厂方法,它按值返回一个Request对象; boost::noncopyable 意味着不生成复制构造函数,因此没有自动 to-python 转换器。

    解决这个问题的方法有两种:一种是删除不可复制的提示;另一种是注册一个转换器,它接受一个 C++ 请求并返回一个 Python 请求对象。你真的需要 Request 的不可复制语义吗?

    【讨论】:

    • 我已经编辑了原始帖子以显示调用 createRequest 的 python 代码
    • 我已经编辑了我的答案。 python端的用法给了我需要的提示,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多