Oleiade
Oleiade

Reputation: 6304

Creating C structs in Cython

I'd like to create my very own list container using Cython. I'm a very new begginer to it, and following the documentation I could get to creating such a structure :

cdef struct s_intList:
    int    value
    void*  next
ctypedef s_intList intList

but when comes the time to acces the struct members, I can't find the good syntax:

cpdef void  foo():
    cdef intList*    li
    # li.value OR li->value

throws : "warning: intlists.pyx:8:12: local variable 'li' referenced before assignment" which let me assume that my cython structs usage is incorrect...

Any idea of what I'm doing wrong here please? :) Thank you for you help

Upvotes: 17

Views: 21622

Answers (2)

lothario
lothario

Reputation: 1868

In your code, li is a pointer to an intList. This pointer is not initialized to point to anything, so accessing li.value is meaningless (and erroneous).

In fabrizioM's answer, an intList is created (not a pointer to one) on the stack, so there is a location in memory reserved for li.value.

If you want to create an intList with actual data (which I gather you intend to be like a linked list data structure), and if you want to be able to return that intList from functions, etc. you will have to allocate your intList structs on the heap and build up the full linked list from there. Cython allows you to call malloc (and free) easily to do this.

Upvotes: 6

fabmilo
fabmilo

Reputation: 48330

You have to allocate the memory for the intList. Either with a local variable or using malloc.

cdef struct s_intList:
    int    value
    void*  next

ctypedef s_intList intList

cpdef object foo():
    cdef intList li
    li.value = 10

Upvotes: 18

Related Questions