help with struct arrays and buffer formats

8 views
Skip to first unread message

Peter Schay

unread,
Nov 2, 2025, 12:54:22 PMNov 2
to cython...@googlegroups.com
Hi,
I am figuring out how to use struct arrays and would very much appreciate answers to a couple quick questions.  

In the example below, the Cython typed memoryview "foos" can be assigned to an cvarrayA which has format string describing the struct fields.

1) Is there a cast that would allow assigning foos = <...>cvarrayB, or some other way to just treat each element as n opaque bytes ?

2) Are there any differences in how "foos" may be used after assigning to cvarrayA vs cvarrayB?  (assuming there is a way to assign to the opaque style cvarrayB)


from cython cimport view

cdef struct Foo:
    int a
    char b
    float c

def run():
    cdef Foo [:] foos
    n = 5
    cvarrayA = view.array(shape=(n,), itemsize=sizeof(Foo), format='T{i:a:c:b:f:c:}')
    cvarrayB = view.array(shape=(n,), itemsize=sizeof(Foo), format='B')

    foos = cvarrayA
    print(f'assigned to A')

    # foos = cvarrayB
    # ValueError: Buffer dtype mismatch, expected 'int' but got 'unsigned char' in 'Foo.a'

    foos = <Foo[:]>cvarrayB
    # foo.pyx:24:19: Can only create cython.array from pointer or array 
run()

Thanks!!
Pete


Peter Schay

unread,
Nov 2, 2025, 12:56:00 PMNov 2
to cython...@googlegroups.com
Oops - sorry to correct my own question. 
I meant "sizeof(Foo)" opaque bytes, of course.  n is the number of Foo's.

Peter Schay

unread,
Nov 3, 2025, 12:22:07 PMNov 3
to cython...@googlegroups.com
Hi again; I managed to get something ultra-simple working which is just fine for my purposes.
This compiles and prints n:
    cdef Foo[:] foos = <Foo[:n]>malloc(n*sizeof(Foo))
    print(f{len(foos)}')
Perfect!

I would like to understand more about how to use objects that support the buffer protocol; meanwhile I will use raw memory.
Thanks aggain, and any insights on the Cython array question would still be greatly appreciated.  

Reply all
Reply to author
Forward
0 new messages