我正在从我试图解码的服务器接收字节串。我已经设法找出 ctypes 结构(参见代码),但它包含位域。
我通常做的只是使用 np.frombuffer 函数来获取数据,因为它可以识别大多数 ctypes。此外,我可以将数据写入 HDF5 文件,而无需任何更多操作。然而,由于位域,dtype 大小和 ctype 大小不匹配并且数据被转换,但显然是错误的。您应该能够按原样运行下面的代码。
import ctypes
import numpy as np
#%%
class SubStruct(ctypes.Structure):
_pack_ = 1
_fields_ = [('bUnderrange', ctypes.c_ubyte, 1),
('bOverrange', ctypes.c_ubyte, 1),
('bLimit_1a', ctypes.c_ubyte, 1),
('bLimit_1b', ctypes.c_ubyte, 1),
('bLimit_2a', ctypes.c_ubyte, 1),
('bLimit_2b', ctypes.c_ubyte, 1),
('bError', ctypes.c_ubyte, 1),
('TXPDO', ctypes.c_ubyte)] #This is a byte, rest are bits
class MainStruct(ctypes.Structure):
_pack_ = 4
_fields_ = [('stStatus', SubStruct),
('nValue', ctypes.c_ushort),
('fValue', ctypes.c_float)]
rawdata = b'X\x00W\x00ff\x86AV\x00\xd6\x0033{B\n\x00-\x00ff\x9aAW\x00\xc8\x01ff\nB'
#%%
a = SubStruct()
b = MainStruct()
print('Data size: ',len(rawdata))
print('\nSubStruct:')
print('Ctype size: ',ctypes.sizeof(a))
print('Dtype size: ',np.dtype(a).itemsize)
print('\nMainStruct:')
print('Ctype size: ',ctypes.sizeof(b))
print('Dtype size: ',np.dtype(b).itemsize)
data = np.frombuffer(rawdata, dtype=MainStruct) #WRONG
我期望的是:
array([((0, 0, 0, 1, 1, 0, 1), 87, 16.8),
((0, 1, 1, 0, 1, 0, 1), 214, 62.8),
((0, 1, 0, 1, 0, 0, 0), 45, 19.3),
((1, 1, 1, 0, 1, 0, 1), 456, 34.6)])
我得到的是:
array([((88, 0, 87, 0, 102, 102, 134, 65), 86, 62.79999924),
((10, 0, 45, 0, 102, 102, 154, 65), 87, 34.59999847)])
当 ctype 对我可用时,是否有一种有效的方法来获取正确的 dtype?或者一种有效操作原始数据的方法,以便我仍然可以应用 np.frombuffer 函数?
请您参考如下方法:
从 numpy 1.16 ( #12254 ) 开始,这将返回错误,而不是产生不正确的结果:
>>> data = np.frombuffer(rawdata, dtype=MainStruct)
TypeError: ctypes bitfields have no dtype equivalent
NumPy 不支持位域,因此无法实现。最好的办法是定义一个不包含位域的替换类型,然后改用它。
如果您将来看到这样的不正确行为,我强烈建议您在 NumPy 问题跟踪器上报告它,尤其是考虑到您拥有的最小示例。
