1

I am creating a C extension for numpy. The function should return an array, so I decided to create a PyArrayObject with dimensions 50x10 using PyArray_SimpleNew and later fill it with some values. Here is the code:

PyArrayObject *a; npy_intp dims[2];
dims[0] = 50; dims[1] = 10;
a = (PyArrayObject *) PyArray_SimpleNew(2, dims, NPY_DOUBLE); 

However, the creation of the array a in the third line produces Segmentation Fault. Any idea what could be the problem?

  • 1
    maybe [creating numpy array in c extension segfaults](https://stackoverflow.com/a/25496494/2055064) helps, did you call `import_array()` ? – Thomas Apr 16 '20 at 21:02
  • Oh, thank you. I just posted a solution because I did not check your comment before. Anyway, it indeed fix the problem. Now the question is why? – German Farinas Apr 16 '20 at 21:47
  • "void import_array(void): This function must be called in the initialization section of a module that will make use of the C-API. It imports the module where the function-pointer table is stored and points the correct variable to it." textually copied from NumPy C-API doc. – German Farinas Apr 16 '20 at 21:56

1 Answers1

4

I needed to include import_array() in my init function as shown below. I dont know what import_array() does, but fix the problem.

PyMODINIT_FUNC
PyInit_multpy(void)
{
    import_array();
    return PyModule_Create(&multpymodule);
}

PS: It would be wonderful to know why import_array() has to be called in the PyMODINIT_FUNC. If somebody knows, please explain.