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?

4
  • 1
    maybe creating numpy array in c extension segfaults helps, did you call import_array() ? Commented Apr 16, 2020 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? Commented Apr 16, 2020 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. Commented Apr 16, 2020 at 21:56
  • 1
    Does this answer your question? creating numpy array in c extension segfaults Commented Dec 14, 2023 at 16:33

1 Answer 1

4

I needed to include import_array() in my init function as shown below. I don't 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.