2016-07-31 20 views
2

Ich schrieb eine Erweiterung für Python 3 in C++Python: Prozess numpy Arrays

My Modul von Handhabungsanordnungen wie [1.0, 0.0, 0.0] fähig ist. Ich möchte auch Unterstützung für numpy Arrays hinzufügen.

I Prozessanordnungen mit dem folgenden Code:

PyObject * MyFunction(PyObject * self, PyObject * args) { 
    PyObject * list; 

    if (!PyArg_ParseTuple(args, "O!:MyFunction", PyList_Type, &list)) { 
     return 0; 
    } 

    int count = (int)PyList_Size(list); 
    for (int i = 0; i < count; ++i) { 
     double value = PyFloat_AsDouble(PyList_GET_ITEM(list, i)); 

     // ... 
    } 
} 

I eine Funktion soll, dass durch diese iterieren kann: np.array([2,3,1,0])

TL; DR:

Numpy Äquivalent für:

  • PyList_Type
  • PyList_Size
  • PyList_GET_ITEM oder PyList_GetItem
+1

Keine wirkliche Antwort und vielleicht haben Sie gute Gründe haben diese native Möglichkeit zu verwenden c die Schnittstelle ++, aber finden Sie [cython] (http : //cython.org/). Dies macht all das Zeug viel einfacher/netter und wird von einigen sehr coolen Projekten (z. B. scikit-learn) genutzt. – sascha

+0

normalerweise ist es umgekehrt: Sie schreiben eine numpy-Funktion, die auch mit Listen umgehen kann. – Daniel

+0

Ich möchte einfach durch ein numpy Array in C++ –

Antwort

1

Zu allererst gibt es kein Äquivalent für numpy:

  • PyList_Type
  • PyList_Size
  • PyList_GET_ITEM oder PyList_GetItem

Die numpy.array die buffer interface implementiert, so dass man schreiben kann:

const char * data; 
int size; 

PyArg_ParseTuple(args, "y#:MyFunction", &data, &size); 

Die numpy.array([1.0, 0.0, 0.0]) verwendet double Präzision:

double * array = (double *)data; 
int length = size/sizeof(double); 

Das vollständige Beispiel:

  • C++

    PyObject * MyFunction(PyObject * self, PyObject * args) { 
        const char * data; 
        int size; 
    
        if (!PyArg_ParseTuple(args, "y#:MyFunction", &data, &size)) { 
         return 0; 
        } 
    
        double * content = (double *)data; 
        int length = size/sizeof(double); 
    
        for (int i = 0; i < length; ++i) { 
         double value = content[i]; 
    
         // ... 
        } 
    
        Py_RETURN_NONE; 
    } 
    
  • Python

    MyFunction(numpy.array([1.0, 2.0, 3.0]))