这有点猜测,因为我使用 C 结构的次数不多。
In [125]: SIZE1, SIZE2 = 3,4
In [127]: dtB=np.dtype([('y',np.uint16),('c',np.uint8,(SIZE2,))])
In [128]: np.ones((2,), dtype=dtB)
Out[128]:
array([(1, [1, 1, 1, 1]), (1, [1, 1, 1, 1])],
dtype=[('y', '<u2'), ('c', 'u1', (4,))])
In [129]: _.itemsize
Out[129]: 6
在此定义中,此数组的每条记录由 6 个字节组成,y 字段为 2,c 字段为 4。
然后将其嵌套在 A 定义中
In [130]: dtA=np.dtype([('x',np.uint32),('b',dtB,(SIZE1,))])
In [131]: np.ones((2,), dtype=dtA)
Out[131]:
array([(1, [(1, [1, 1, 1, 1]), (1, [1, 1, 1, 1]), (1, [1, 1, 1, 1])]),
(1, [(1, [1, 1, 1, 1]), (1, [1, 1, 1, 1]), (1, [1, 1, 1, 1])])],
dtype=[('x', '<u4'), ('b', [('y', '<u2'), ('c', 'u1', (4,))], (3,))])
In [132]: _.itemsize
Out[132]: 22
x 字段的每条记录有 4 个字节,3 个 b 元素有 3*6。
In [133]: __.tobytes()
Out[133]: b'\x01\x00\x00\x00\x01\x00\x01\x01\x01\x01\x01\x00\x01\x01\x01\x01\x01\x00\x01\x01\x01\x01\x01\x00\x00\x00\x01\x00\x01\x01\x01\x01\x01\x00\x01\x01\x01\x01\x01\x00\x01\x01\x01\x01'
并试图让数组更有趣:
In [136]: A['x']=[1,2]
In [139]: A['b']['y'] *= 3
In [141]: A['b']['c'][0]=2
In [142]: A['b']['c'][1]=3
In [143]: A
Out[143]:
array([(1, [(3, [2, 2, 2, 2]), (3, [2, 2, 2, 2]), (3, [2, 2, 2, 2])]),
(2, [(3, [3, 3, 3, 3]), (3, [3, 3, 3, 3]), (3, [3, 3, 3, 3])])],
dtype=[('x', '<u4'), ('b', [('y', '<u2'), ('c', 'u1', (4,))], (3,))])
In [144]: A[0].tobytes()
Out[144]: b'\x01\x00\x00\x00\x03\x00\x02\x02\x02\x02\x03\x00\x02\x02\x02\x02\x03\x00\x02\x02\x02\x02'
这些字节串是否与您的 c 结构一致?