[Numpy-discussion] PyArray_FromDims segfault??
Travis Oliphant
oliphant at ee.byu.edu
Sun Dec 31 02:33:09 EST 2006
Xavier Gnata wrote:
> Hello,
>
> I would like to use PyObject_CallObject to call the imshow function from
> matplolib from a C code.
> So, the first step is to create a 2D PyArrayObject from a C array.
>
> I have read the Numpy book which is great but now I'm puzzled:
> My goal is to convert a C array of doubles into a 2D numpy array object.
> PyArray_SimpleNewFromData(nd, dims, typenum, data) seems to be the
> function I need but I did not manage to write/find any compiling *and*
> not segfaulting code performing this convertion :(
>
> Ok, maybe PyArray_SimpleNewFromData is to complex to begin with.
> Let's try with PyArray_FromDims... segfault also :(
>
> My code looks so simpleKK I cannot see what I'm doing the wrong way :(
>
> #include <python2.4/Python.h>
> #include <numpy/arrayobject.h>
>
> int
> main (int argc, char *argv[])
> {
>
> PyArrayObject *array;
> int i, length = 100;
> double* a;
> double x;
> Py_Initialize ();
>
> array = (PyArrayObject *)
> PyArray_FromDims(1, &length, PyArray_DOUBLE);
>
> a = new double[100];
> for (i = 0; i < length; i++) {
> x = (double) i/(length-1);
> a[i] = x;
> }
> Py_Finalize ();
>
> return 0;
> }
>
> g++ imshow.cpp -o imshow -lpython2.4
> -I/usr/lib/python2.4/site-packages/numpy/core/include/
>
> ./imshow -> Segmentation fault
>
> I really need the Py_Initialize/Py_Finalize calls because it is
> 'embedding python' (and not extending :)).
>
> To sum up, any code taking an double* and 2 int standind for the dimX
> and the dimY and returning the corresponding PyObject would be very
> much appreciated :) I don't care if it has to copy the data. The simpler
> the better.
>
You *always* need to use import_array() or one of it's variants
somewhere in your code. In this case, because you are returning from
main, you need to use:
import_array1(-1)
in order to return -1 on import error. The import array sets up the
C-API so it can be used.
Also, this code is not doing anything with the memory you just created
for array. If you want to use pre-existing memory, then
PyArray_SimpleNewFromData will work and construct a PyObject * (an
ndarray object) where the memory is the pointer you pass in for the
data-area to that function.
You must be sure that the memory is not released before the returned
object is used up or you will get segmentation faults.
-Travis
More information about the NumPy-Discussion
mailing list