Creating C Structures in Cython

I would like to create my own list container using Cython. I am very new to this, and after the documentation I could create such a structure:

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

but when the time comes to access the members of the structure, I cannot find a good syntax:

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

throws: "warning: intlists.pyx: 8: 12: local variable 'li' specified before the destination" which allows me to assume that using my cython structure is wrong ...

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

+7
source share
2 answers

You must allocate memory for 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 
+9
source

Your li code has a pointer to an intList . This pointer is not initialized to indicate anything, so accessing li.value pointless (and erroneous).

The response fabrizioM creates a stack (not a pointer to one) on the stack, so memory is reserved for li.value .

If you want to create an intList with the actual data (which, as I understand it, you intend to be similar to the structure of linked lists), and if you want you to be able to return this intList from functions, etc., you will have to isolate your structures intList in a bunch and create there a complete list of links. Cython allows you to easily call malloc (and free ).

+4
source

All Articles