[Pyrex] How do I return a PyObject * from python functions?

Roy Dragseth roy.dragseth at cc.uit.no
Sat Sep 22 00:30:08 CEST 2007


Hi, I might be missing something obvious here, but I'm really stuck.

I want to wrap a c-function that returns some data in a c-type array by 
creating a numpy array. So far so good, pyrex is really much easier than 
anything else I've come across.  But, when I use the standard interface for 
creating a numpy array from already allocated data I find that the function 
PyArray_SimpleNewFromData returns a PyObject pointer which points to the 
numpy array.  How on earth do I get that propagated out as a numpy array 
return value from the python function?

Below is an example code illustrating the problem.  When I compile it with 
pyrexc it says:
$ pyrexc pyrextest.pyx
/home/royd/python/ga/pyrextest.pyx:34:11: Cannot convert 'PyObject (*)' to 
Python object

Which of course makes sense as that is what I'm trying to do, but how do I 
convert a PyObject * to python object that can be returned?

Any help is greatly appreciated.

Regards,
r.


Here is pyrextest.pyx (it is stripped down to illustrate my problem):
# standard defs
ctypedef int size_t

cdef extern from "stdlib.h":
    cdef void *malloc(size_t)
    cdef void free(void *)

cdef extern from "object.h":
    ctypedef struct PyObject:
        pass

cdef extern from "numpy/arrayobject.h":
    cdef int NPY_CARRAY "NPY_CARRAY"
    cdef void import_array()

    cdef PyObject * PyArray_SimpleNewFromData(int nd, int * dims,
        int typenum,char * data)    
 
import_array()
                
def create_array():
    cdef int dims[2]
    cdef void *ptr
    cdef int ndim
    cdef PyObject* arr
    
    #Just create some space.
    dims[0] = 5
    dims[1] = 20
    ptr = malloc(sizeof(1.0)*100)
    #create a new numpy array that wraps ptr.
    arr = PyArray_SimpleNewFromData(ndim,dims,NPY_CARRAY,
                            <char *> ptr)
    return arr



More information about the Pyrex mailing list