Search code examples
cython

Is there a way to iterate over struct attributes?


Sorry if this has been asked before. It does seem very simple. I am wondering if there is a way to iterate over struct attributes.

E.g.

ctypedef struct Foo:
    int a, b
    
cdef Foo foo = [1, 2]


#want something like this
for i in range(2):
    print(foo[i])

Solution

  • As per @ShadowRanger's comment, the closest I can come up with how to do this is like so:

    ctypedef struct Foo:
        int a, b
        
    cdef union Bar:
        Foo *f
        int *g
    
    cdef Foo foo = [1, 2]
    cdef Bar bar
    
    bar.f = &foo
    
    for i in range(2):
        print(bar.g[i])
    

    Wrapping the struct with a corresponding array. This would only work if the struct was a collection of all the same type, however.