首页 > 解决方案 > 将 boost.python 代码更新为没有 numeric.hpp 的新 API

问题描述

我正在尝试编译pyBKT项目,它使用boost::python的库在版本 1.63 中发生了显着变化,当boost/python/numeric.hpp被删除时。我boost/numpy.hpp按照建议将其更新为,但在将代码的其他部分更新为新 API 时遇到问题。

特别是,我在使用以下将结果包装到numpy对象中的代码时遇到了问题。

//wrapping results in numpy objects.
npy_intp all_stateseqs_dims[2] = {1, bigT}; 
PyObject * all_stateseqs_pyObj = PyArray_SimpleNewFromData(2, all_stateseqs_dims, NPY_INT, all_stateseqs); 
boost::python::handle<> all_stateseqs_handle( all_stateseqs_pyObj );
boost::python::numpy::ndarray all_stateseqs_handle_arr( all_stateseqs_pyObj );

npy_intp all_data_dims[2] = {num_subparts, bigT}; 
PyObject * all_data_pyObj = PyArray_SimpleNewFromData(2, all_data_dims, NPY_INT, all_data); 
boost::python::handle<> all_data_handle( all_data_pyObj );
boost::python::numpy::ndarray all_data_arr( all_data_handle );

报告的错误是

generate/synthetic_data_helper.cpp:161:65: error: no matching function for call to ‘boost::python::numpy::ndarray::ndarray(boost::python::handle<>&)’

我知道这意味着找不到带有此参数的构造函数,但我不知道如何更改它,因为我不是 C++ 程序员。

标签: c++boostboost-python

解决方案


我只是直接使用 numpy API,因为我必须支持回 Numpy 1.4(RHEL6 默认,叹气)。事实证明还不错,您只需返回一个新对象。这假定您已经暴露了一个图像对象:

// accessor to wrap data from image up into read-only numpy array
//
static inline object image_get_data(object &imageobj) {
    // extract image base
    const image &img = extract<const image&>(imageobj);

    // build read-only array around data
    npy_intp dims[2] = {img.width, img.height};
    PyObject* array = PyArray_New(
        &PyArray_Type, 2, dims, NPY_COMPLEX64, NULL, (void*)img.data(), 0,
        NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_ALIGNED, NULL
    );

    // increment reference to image object and set base pointer
    // of array, this will establish an ownership link so that
    // image instance won't be destroyed before the array.
    incref(image.ptr());
    NPY_SET_BASE(array, image.ptr());
    return object(handle<>(array));
}

然后将其添加到图像对象中:

 .add_property("data", &image_get_data, "read-only numpy array containing image data")

推荐阅读