Returning Cython array
Question: How does one properly initialize and return a Cython array? For instance:

    
    
    cdef public double* cyTest(double[] input):
      cdef double output[3]
    
      for i in xrange(3):
        output[i] = input[i]**2
        print 'loop: ' + str(output[i])
      return output
    
    cdef double* test = [1,2,3]
    cdef double* results = cyTest(test)
    
    for i in xrange(3):
      print 'return: ' + str(results[i])
    

This returns:

    
    
    loop: 1.0->1.0
    loop: 2.0->4.0
    loop: 3.0->9.0
    return: 1.88706086937e-299
    return: 9.7051011575e+236
    return: 1.88706086795e-299
    

So obviously, `results` still points only to garbage instead of the values it
should point to. Admittedly, I am slightly confused with mixing the pointer
and array syntax and which one is preferable/possible in a Cython context.

In the end, I want to call `cyTest` from a pure C++ function:

    
    
    #include <iostream>
    #include <Python.h>
    #include "cyTest.h"
    
    void main() {
      Py_Initialize();
      initcyTest();
      double input[3] = {1,2,3};
      double* output = cyTest(input);
    
      for(int i = 0; i < 3; i++)
        std::cout << "cout: " << output[i] << std::endl;
    
      Py_Finalize();
    }
    

This returns similar results:

    
    
    loop: 1.0->1.0
    loop: 2.0->4.0
    loop: 3.0->9.0
    cout: 1
    cout: 6.30058e+077
    cout: 6.39301e-308
    

Anyone care to explain what error I'm making? I'd like to keep it as simple as
possible. It's just returning an array from Cython to C++ after all. I'll deal
with dynamic memory allocation later, if not necessary.


Answer: You are returning reference to local array ( output ), which will not work.

Try changing your script to:

    
    
    from cpython.mem cimport PyMem_Malloc
    
    cdef public double * cyTest(double[] input):
        cdef double * output = < double * >PyMem_Malloc( sizeof(double) * 3 )
        for i in xrange(3):
            output[i] = input[i]**2
            print 'loop: ' + str(output[i])
        return output
    

And in your c++ code,

after you done using `double* output` issue `free( output );`

If you want to use `cdef double* results = cyTest(test)` in your pyx script
then don't forget to use `PyMem_Free(results)`

