-
- from cffi import FFI
- import numpy as np
-
- s = '''
- typedef struct
- {
- int a;
- int b;
- float c;
- double d;
- } mystruct;
- '''
- ffi = FFI()
- ffi.cdef(s)
-
- m_arr = ffi.new("mystruct[2]")
-
- #create array and fill with dummy data
- for k in range(2):
-
- m = m_arr[k]
-
- m.a = k
- m.b = k + 1
- m.c = k + 2.0
- m.d = k + 3.0
-
- print(m_arr)
-
- # dtype for structured array in Numpy
- dt = np.dtype({'names': ('a', 'b', 'c', 'd'),
- 'formats': ('i4', 'i4', 'f4', 'f8'),
- 'offset': (ffi.offsetof('mystruct', 'a'),
- ffi.offsetof('mystruct', 'b'),
- ffi.offsetof('mystruct', 'c'),
- ffi.offsetof('mystruct', 'd'),
- )
- }, align=True)
-
- # member size, 20 bytes
- print('size, manually', 4 + 4 + 4 + 8)
-
- # total size of struct, 24 bytes
- print('sizeof', ffi.sizeof(m_arr[0]))
-
-
- #reason is member padding in structs
-
- buf = ffi.buffer(m_arr)
- print(buf)
-
- x = np.frombuffer(buf, dtype=dt)
- print(x)
-
-