I am wrapping a C file so I can use it in python. The output of the C function is an array of doubles. I want this to be a numpy array in python. I get garbage. Here's an example that generates the error.
First, the C file (focus on the last function definition, everything else should be OK):
#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 goes OK (from what I understand - I used a python script that compiles everything).
In python, I run the following script to test my new module:
try:
import _tmp
res = _tmp.error()
print(res)
except:
print("fail")
The result I see on the screen is garbage. I tried substituting (int)NPY_FLOAT
with (int)NPY_FLOAT32, (int)NPY_FLOAT64, (int)NPY_DOUBLE
and I still get garbage.
I am using python2.7.
Thanks!!!
EDIT: following the answer below, I changed the last function to:
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 shows an empty array.
PyArray_SimpleNewFromData(1, dims, NPY_DOUBLE, vector)
. Does it not work like that either? – Rigadoondims[1] = 2
is an indexing error – Diageotropism