Arrays of cdef classes?

37 views
Skip to first unread message

Connelly Barnes

unread,
Oct 23, 2011, 5:34:52 PM10/23/11
to cython-users
Hi,

I am wondering in Cython if it is possible to create arrays of cdef
classes.

For example, if I have a class Rectangle:

cdef class Rectangle:
...

If I try to in a separate function declare an array of Rectangles:

cdef Rectangle L[8]

This gives an error. I tried also using Rectangle *, but this only
works for C++ classes apparently. I also tried using a numpy array of
objects, this works fine but is slow since the generic Python methods
are called instead of the fast C methods.

The best solution I've found so far is creating a linked list cdef
class of Rectangles, and then traversing this list.

cdef class LinkedNode:
cdef Rectangle data
cdef LinkedNode next

However this approach has the disadvantage that (1) extra reference
counting is done while iterating over the list, and (2) it's not
possible to run a parallel for over the list, since the nogil section
fails due to the reference counting.

Does anyone know if there are other alternatives that would allow
random access, or not needing to use the GIL?

Thanks, Connelly

Stefan Behnel

unread,
Oct 24, 2011, 4:00:40 AM10/24/11
to cython...@googlegroups.com
Connelly Barnes, 23.10.2011 23:34:

Language support for borrowed references is still open:

http://trac.cython.org/cython_trac/ticket/498

The idea would be that you could explicitly declare a Python variable as
"borrowed", and then use it as a loop variable for a list, for example, so
that Cython could avoid the reference counting if possible.

If you are interested, you could make a little investment into getting this
feature implemented:

http://consulting.behnel.de/#openprojects

Stefan

Reply all
Reply to author
Forward
0 new messages