title: C array to PyArray
body: <p>I'm writing a Python C-Extension without using Cython.</p>
  
  <p>I want to allocate a double array in C, use it in an internal function (that happens to be in Fortran) and return it. I point out that the C-Fortran interface works perfectly in C.</p>
  
  <pre><code>static PyObject *
  Py_drecur(PyObject *self, PyObject *args)
  {
    // INPUT
    int n;
    int ipoly;
    double al;
    double be;
  
    if (!PyArg_ParseTuple(args, "iidd", &amp;n, &amp;ipoly, &amp;al, &amp;be))
      return NULL;
  
    // OUTPUT
    int nd = 1;
    npy_intp dims[] = {n};
    double a[n];
    double b[n];
    int ierr;
  
    drecur_(n, ipoly, al, be, a, b, ierr);
  
    // Create PyArray
    PyObject* alpha = PyArray_SimpleNewFromData(nd, dims, NPY_DOUBLE, a);
    PyObject* beta = PyArray_SimpleNewFromData(nd, dims, NPY_DOUBLE, b);
  
    Py_INCREF(alpha);
    Py_INCREF(beta);
  
    return Py_BuildValue("OO", alpha, beta);
  }
  </code></pre>
  
  <p>I debugged this code and I get a Segmentation fault when I try to create alpha out of a. Up to there everything works fine. The function drecur_ works and I get the same problem if it is removed.</p>
  
  <p>Now, what's the standard way of defining a PyArray around C data? I found documentation but no good example. Also, what about memory leakage? Is it correct to INCREF before return so that the instance of alpha and beta are preserved? What about the deallocation when they are not needed anymore?</p>
  
  <p><strong>EDIT</strong>
  I finally got it right with the approach found in <a href="http://www.scipy.org/Cookbook/C_Extensions/NumPy_arrays">NumPy cookbook</a>.</p>
  
  <pre><code>static PyObject *
  Py_drecur(PyObject *self, PyObject *args)
  {
    // INPUT
    int n;
    int ipoly;
    double al;
    double be;
    double *a, *b;
    PyArrayObject *alpha, *beta;
  
    if (!PyArg_ParseTuple(args, "iidd", &amp;n, &amp;ipoly, &amp;al, &amp;be))
      return NULL;
  
    // OUTPUT
    int nd = 1;
    int dims[2];
    dims[0] = n;
    alpha = (PyArrayObject*) PyArray_FromDims(nd, dims, NPY_DOUBLE);
    beta = (PyArrayObject*) PyArray_FromDims(nd, dims, NPY_DOUBLE);
    a = pyvector_to_Carrayptrs(alpha);
    b = pyvector_to_Carrayptrs(beta);
    int ierr;
  
    drecur_(n, ipoly, al, be, a, b, ierr);
  
    return Py_BuildValue("OO", alpha, beta);
  }
  
  double *pyvector_to_Carrayptrs(PyArrayObject *arrayin)  {
    int n=arrayin-&gt;dimensions[0];
    return (double *) arrayin-&gt;data;  /* pointer to arrayin data as double */
  }
  </code></pre>
  
  <p>Feel free to comment on this and thanks for the answers.</p>