pythoncnumpypython-extensions

creating numpy array in c extension segfaults


I'm just trying to start off by creating a numpy array before I even start to write my extension. Here is a super simple program:

#include <stdio.h>
#include <iostream>
#include "Python.h"
#include "numpy/npy_common.h"
#include "numpy/ndarrayobject.h"
#include "numpy/arrayobject.h"

int main(int argc, char * argv[])
{
    int n = 2;
    int nd = 1;
    npy_intp size = {1};
    PyObject* alpha = PyArray_SimpleNew(nd, &size, NPY_DOUBLE);
    return 0;
}

This program segfaults on the PyArray_SimpleNew call and I don't understand why. I'm trying to follow some previous questions (e.g. numpy array C api and C array to PyArray). What am I doing wrong?


Solution

  • Typical usage of PyArray_SimpleNew is for example

    int nd = 2;
    npy_intp dims[] = {3,2};
    PyObject *alpha = PyArray_SimpleNew(nd, dims, NPY_DOUBLE);
    

    Note that the value of nd must not exceed the number of elements of array dims[].

    ALSO: The extension must call import_array() to set up the C API's function-pointer table:

    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.

    E.g. in Cython:

    import numpy as np
    cimport numpy as np
    
    np.import_array()  # so numpy's C API won't segfault
    
    cdef make_array():
      cdef np.npy_intp element_count = 100
      return np.PyArray_SimpleNew(1, &element_count, np.NPY_DOUBLE)