Python 在C语言中访问numpy数组数据(适用于numpy 1.7+;)

Python 在C语言中访问numpy数组数据(适用于numpy 1.7+;),python,numpy,c-api,Python,Numpy,C Api,以下示例和numpy C-API(),我尝试在cpp中访问numpy数组数据,如下所示: #include <Python.h> #include <frameobject.h> #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // TOGGLE OR NOT #include "numpy/ndarraytypes.h" #include "numpy/arrayobject.h" ... // here I have

以下示例和numpy C-API(),我尝试在cpp中访问numpy数组数据,如下所示:

#include <Python.h>
#include <frameobject.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // TOGGLE OR NOT
#include "numpy/ndarraytypes.h"
#include "numpy/arrayobject.h"
...
// here I have passed "some_python_object" to the C code
// .. and "some_python_object" has member "infobuf" that is a numpy array
//
unsigned long* fInfoBuffer;
PyObject* infobuffer = PyObject_GetAttrString(some_python_object, "infobuf");
PyObject* x_array    = PyArray_FROM_OT(infobuffer, NPY_UINT32);
fInfoBuffer          = (unsigned long*)PyArray_DATA(x_array); // DOES NOT WORK WHEN API DEPRECATION IS TOGGLED

>在NUMPY 1.7 +中,合法的方式是什么?

< P>你可以尝试使用一个更高级的库,它用适当的容器语义包装C++容器中的NUMPY数组。 尝试
xtensor
xtensorpython
绑定

  • Numpy至xtensor备忘单
  • xtensorpython项目

还有一个CooKiCeFuter,生成一个最小的C++扩展项目,所有的测试板、HTML文档和设置都可以。

<强>实例:C++代码< /强>

#include <numeric>                        // Standard library import for std::accumulate
#include "pybind11/pybind11.h"            // Pybind11 import to define Python bindings
#include "xtensor/xmath.hpp"              // xtensor import for the C++ universal functions
#define FORCE_IMPORT_ARRAY                // numpy C api loading
#include "xtensor-python/pyarray.hpp"     // Numpy bindings

double sum_of_sines(xt::pyarray<double> &m)
{
    auto sines = xt::sin(m);
    // sines does not actually hold any value, which are only computed upon access
    return std::accumulate(sines.begin(), sines.end(), 0.0);
}

PYBIND11_PLUGIN(xtensor_python_test)
{
    xt::import_numpy();
    pybind11::module m("xtensor_python_test", "Test module for xtensor python bindings");

    m.def("sum_of_sines", sum_of_sines,
        "Computes the sum of the sines of the values of the input array");

    return m.ptr();
}

这是因为
PyArray\u DATA
需要一个
PyArrayObject*
。 您可以尝试更改
x_数组的类型

PyArrayObject* x_array = (PyArrayObject*) PyArray_FROM_OT(infobuffer, NPY_UINT32)

参考C API的问题,答案与C++代码有关。问题仍然在于,如何使用C-API来实现这一点。C++中的代码使用了C API,并将其封装到更高级的构造中。另外,最初的问题是“我正在尝试访问cpp中的numpy数组数据,”
import numpy as np
import xtensor_python_test as xt

a = np.arange(15).reshape(3, 5)
s = xt.sum_of_sines(v)
s
PyArrayObject* x_array = (PyArrayObject*) PyArray_FROM_OT(infobuffer, NPY_UINT32)