[Pyrex] How do I return a PyObject * from python functions?
Robert Bradshaw
robertwb at math.washington.edu
Sat Sep 22 00:33:46 CEST 2007
Try using the object type. (This is simply a PyObject* that is
refcounted). E.g.
cdef extern from "numpy/arrayobject.h":
cdef object PyArray_SimpleNewFromData(int nd, int * dims, int
typenum,char * data)
(This assumes that PyArray_SimpleNewFromData gives you a new
reference, check the numpy documentation for that.)
On Sep 21, 2007, at 3:30 PM, Roy Dragseth wrote:
> 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
>
> _______________________________________________
> Pyrex mailing list
> Pyrex at lists.copyleft.no
> http://lists.copyleft.no/mailman/listinfo/pyrex
More information about the Pyrex
mailing list