如何在PyCXX中访问numpy数组

时间:2010-10-09 19:26:58

标签: python numpy cpython pycxx

我想将numpy数组转换为c ++方面的一些double *或stl向量。我实际上正在使用PyCXX,我无法弄清楚访问数据的方式。

我现在能够像这样访问并返回数据缓冲区:

Py::Object arrayShape(const Py::Tuple& args ){
     Py::Object array= args[0];
     return array.getAttr("data");
}

但我不知道该怎么做。我的最终目标是从中获取gsl_vector。理想情况下,我不必重新记忆。但也许要问太多了;)

1 个答案:

答案 0 :(得分:2)

当我在寻找解决方案时,我发现只有其他人发布了相同的,长期未解答的问题,我发现解决方案后就发布了解决方案。你的问题就是这个问题。

首先,强烈考虑使用Cython作为你的胶水,并且不要再走这条危险的道路了。

除此之外,如果可能的话,使用PyArray_FromAny将为您提供基础数据的视图,否则将提供副本。一个非常简单的例子(如果你是一个诚实和善良的人,使用-std = c ++ 11构建,如果你是Windows用户,则使用VS2013):

#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/arrayobject.h>

Py::Object printNumpyArrayCxxFunction(const Py::Tuple& args)
{
    if(args.length() != 1)
    {
        throw Py::RuntimeError("Exactly one argument required.");
    }
    PyObject* vector_{PyArray_FromAny(*args[0], PyArray_DescrFromType(NPY_DOUBLE), 1, 1, NPY_ARRAY_CARRAY_RO, nullptr)};
    if(!vector_)
    {
        throw Py::ValueError("Failed to convert argument into a 1d numpy double (64-bit float) array.");
    }
    Py::Object vector(vector_, true);
    PyArrayObject* vector_npy{reinterpret_cast<PyArrayObject*>(vector_)};
    npy_intp vector_length{PyArray_SIZE(vector_npy)};
    double*const vector_begin{reinterpret_cast<double*>(PyArray_DATA(vector_npy))};
    double*const vector_end{vector_begin + vector_length};

    for(double* vector_iterator{vector_begin}; vector_iterator != vector_end; ++vector_iterator)
    {
        if(vector_iterator != vector_begin)
        {
            std::cout << ", ";
        }
        std::cout << *vector_iterator;
    }
    std::cout << std::endl;

    return Py::None();
}

注意将true参数作为Py :: Object构造函数的第二个参数,用于&#34;拥有&#34;对象! An example of a cpython3 extension that uses the Numpy C API in combination with PyCXX with cmake for building.该链接指向特定提交,因为我正在考虑将此扩展程序切换回使用Cython。