c++ - Boost-Python 原始指针构造函数

标签 c++ python boost pointers

我正在尝试使用 boost-python 将 C++ 库公开给 python。该库实际上包装了一个底层 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 文档中了解到,这与传递原始指针有关,但我真的不明白我还应该做什么......

最佳答案

你的 class_<blpapi_Request_t>;不声明任何东西;该代码是正确的版本吗?

如果是,则更新它:

class_<blpapi_Request_t>("blpapi_Request_t");

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

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

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

关于c++ - Boost-Python 原始指针构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3100341/

相关文章:

python - "only length-1 arrays can be converted to Python scalars"- 浮点转换函数出错

c++ - 从函数指针创建 boost::function 的跨平台方式

c++ - 将boost_chrono_FOUND设置为FALSE,因此 “boost_chrono”软件包被视为未找到

c++ - boost::asio::io_service::run 在没有工作时不返回

python - 哪种形式的 unicode 规范化适合文本挖掘?

c++ - "operations.hpp"中的 OpenCV 2.4.2 编译问题

c++ - 如何将 Eigen::Tensor 传播到更高维度?

c++ - 仅从 PDF 文件中复制必要的对象

c++ - 未定义访问成员变量的访问权限(非公有非私有(private))

python - 仅在基类中获取属性(Python)