2016-09-14 8 views
1

folgenden Beispiele und die numpy C-API (http://docs.scipy.org/doc/numpy/reference/c-api.html) Zugriff, ich versuche numpy Array-Daten in cpp zuzugreifen, wie folgt aus:numpy Array-Daten in C (für numpy 1.7+)

#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 

Wenn die API deprecation ist, ein- und ich, beim Kompilieren:

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

Was die legitime Art und Weise, dies zu tun in numpy 1.7+ sein würde?

Antwort

1

Sie könnten versuchen, eine höhere Bibliothek zu verwenden, die numpy Arrays in C++ - Container mit der richtigen Containersemantik umschließt.

Probieren Sie xtensor und die xtensor-python Bindungen.

Es gibt auch eine cookie einen minimalen C++ Erweiterungsprojekt mit alle Textvorschlag für die Prüfung, die HTML-Dokumentation zu generieren und setup.p ...

Beispiel: C++ Code

#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(); 
} 

Python-Code:

import numpy as np 
import xtensor_python_test as xt 

a = np.arange(15).reshape(3, 5) 
s = xt.sum_of_sines(v) 
s 
+0

Frage an den C-API verwiesen, die Antwort in Bezug auf C++ Code. Die Frage bleibt, wie würde man das mit der C-API machen? – rhody

+2

Der fragliche C++ - Code verwendet die C-API und bindet sie in Konstrukte höherer Ebene ein. Außerdem lautet die ursprüngliche Frage "Ich versuche, auf numpy Array-Daten in cpp zuzugreifen". – Quant