Extend Python mit C, Return Numpy Array gibt Müll
Ich verpacke eine C-Datei, damit ich sie in Python verwenden kann. Die Ausgabe der C-Funktion ist ein Array von Doppelwerten. Ich möchte, dass dies ein numpy Array in Python ist. Ich bekomme Müll. Hier ist ein Beispiel, das den Fehler erzeugt.
Zunächst die C-Datei (Fokus auf die letzte Funktionsdefinition, alles andere sollte in Ordnung sein):
#include <Python.h>
#include <numpy/arrayobject.h>
#include <stdio.h>
static char module_docstring[] =
"docstring";
static char error_docstring[] =
"generate the error";
static PyObject *_aux_error(PyObject *self, PyObject *args);
static PyMethodDef module_methods[] = {
{"error", _aux_error, METH_VARARGS, error_docstring},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC init_tmp(void) {
PyObject *m = Py_InitModule3("_tmp", module_methods, module_docstring);
if (m == NULL)
return;
/* Load `numpy` functionality. */
import_array();
}
static PyObject *_aux_error(PyObject *self ,PyObject *args) {
double vector[2] = {1.0 , 2.0};
npy_intp dims[1] = { 2 };
PyObject *ret = PyArray_SimpleNewFromData(1, dims, (int)NPY_FLOAT , vector );
return ret;
}
Compilation funktioniert (soweit ich weiß, habe ich ein Python-Skript verwendet, das alles kompiliert).
In Python führe ich das folgende Skript aus, um mein neues Modul zu testen:
try:
import _tmp
res = _tmp.error()
print(res)
except:
print("fail")
Das Ergebnis, das ich auf dem Bildschirm sehe, ist Müll. Ich habe versucht, @ zu ersetz(int)NPY_FLOAT
mit(int)NPY_FLOAT32, (int)NPY_FLOAT64, (int)NPY_DOUBLE
und ich bekomme noch müll. Ich benutze Python2.7.
Vielen Dank!!
BEARBEITE: Nach der Antwort unten habe ich die letzte Funktion geändert in:
static PyObject *_aux_error(PyObject *self, PyObject *args) {
double *vector = calloc(2, sizeof(double));
vector[0] = 1.0;
vector[1] = 2.0;
npy_intp *dims = calloc(1 , sizeof(npy_intp));
dims[1] = 2;
PyObject *ret = PyArray_SimpleNewFromData(1, dims, (int)NPY_FLOAT , &vector );
return ret;
}
Now Python zeigt ein leeres Array.