使用boost将数据从PyObject复制到float *

时间:2018-10-23 10:18:13

标签: c++ boost-python

我认为这应该很容易,但是我无法使其工作。我想从python调用C++-function。作为参数,我有一个np-arrayC++看起来像这样:

void foo_python(PyObject *p, const int m, const int n){
    float *data = new float[m*n];
    memcpy(data,PyArray_DATA(p),m*n*sizeof(float));
    delete [] data;
}

当我使用python从

调用它时
hello_ext.foo_python(A,A.shape[0], A.shape[1])

我知道

  error: cannot convert ‘PyObject* {aka _object*}’ to ‘PyArrayObject* {aka tagPyArrayObject*}’ for argument ‘1’ to ‘void* PyArray_DATA(PyArrayObject*)’

这曾经有用,但是当我包含#include <boost/python/numpy.hpp> 时才出现,在此功能中我需要将ndarrays返回到python。

np::ndarray test() {
    int *data = new int[5];
    for (int i = 0; i < 5; ++i){
        data[i] = i+1;
    }
    p::tuple shape = p::make_tuple(5);
    p::tuple stride = p::make_tuple(sizeof(int));
    p::object own;
    np::dtype dt = np::dtype::get_builtin<int>();
    std::cout << " Here " << std::endl;
    np::ndarray array = np::from_data(data, dt, shape, stride, own);
    cout<<"Selective Multidimensional array :: "<<std::endl << 
    p::extract<char const *>(p::str(array)) << std::endl;
    // delete [] data;
    return array;
}

这是模块:

BOOST_PYTHON_MODULE(libhello_ext)
{
    using namespace boost::python;
    Py_Initialize();
    boost::python::numpy::initialize();
    def("greet", greet);
    def("sum", sum);
    def("foo_python", foo_python);
    def("test", test);
}

1 个答案:

答案 0 :(得分:0)

我想到的解决方案是将PyObject *p替换为np::ndarray &p。然后,我可以创建一个指针float *p = reinterpret_cast<float *>(p.get_data())

然后可以在p中使用

Map在{中使用Eigen::Matrix来创建Map<FMatrix > A(data, m, n);

typedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> FMatrix;