[Numpy-discussion] embedded PyArray_FromDimsAndDataSegmentation Fault

Robert Kern robert.kern@gmail....
Wed May 14 19:12:52 CDT 2008


On Wed, May 14, 2008 at 6:40 PM, Thomas Hrabe <thrabe@burnham.org> wrote:
>>I didn't know a person could write a stand-alone program using NumPy
>>this way (can you?)
>
> Well, this is possible when you embed python and use the "simple" objects such as ints, strings, ....
> Why should it be impossible to do it for numpy then?

numpy exposes its API as a pointer to an array which contains function
pointers. import_array() imports the extension module, accesses the
PyCObject that contains this pointer, and sets a global pointer
appropriately. There are #defines macros to emulate the functions by
dereferencing the appropriate element of the array and calling it with
the given macro arguments. The reason you get the error about
returning nothing when the return type of main() is declared int is
because this macro is only intended to work inside of an initmodule()
function of an extension module, whose return type is void.
import_array() includes error handling logic and will return if there
is an error. You get the segfault without import_array() because all
of the functions you try to call are trying to dereference an array
which has not been initialized.

> My plan is to send multidimensional arrays from C to python and to apply some python specific functions to them.

Well, first you need to call Py_Initialize() to start the VM.
Otherwise, you can't import numpy to begin with. I guess you could
write a "void load_numpy(void)" function which just exists to call
import_array(). Just be sure to check the exception state
appropriately after it returns.

But for the most part, it's much better to drive your C code using
Python than the other around.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
 -- Umberto Eco


More information about the Numpy-discussion mailing list