Python structure always stuck at 0 no matter what value you assign to it?

≯℡__Kan透↙ 提交于 2020-01-02 08:24:33

问题


I was writing a module to compact bits to be passed to C program, but keep getting errors. After some tests, I found out that the field a of class Blah is stuck at 0 no matter what. Does anyone know if this is a bug or if I'm doing something wrong here?

Sorry, I forgot to mention I'm using python 3.1.2 from http://www.python.org/download/releases/3.1.2/

>>> import ctypes
>>> class Blah(ctypes.Structure):
...     _fields_ = [("a", ctypes.c_uint64, 64),
...                 ("b", ctypes.c_uint16, 16),
...                 ("c", ctypes.c_uint8, 8),
...                 ("d", ctypes.c_uint8, 8)]
...
>>> x = Blah(0xDEAD,0xBEEF,0x44,0x12)
>>> print (hex(x.a) )
0x0
>>> print (hex(x.b ))
0xbeef
>>> print (hex(x.c ))
0x44
>>> print (hex(x.d ))
0x12
>>>
>>> g = Blah(0x2BAD,0xBEEF,0x55,0x12)
>>> print (hex(g.a ))
0x0
>>> print (hex(g.b ))
0xbeef
>>> print (hex(g.c ))
0x55
>>> print (hex(g.d ))
0x12
>>>

swapping first two fields' position gives same result

>>> import ctypes
>>> class Blah(ctypes.Structure):
...     _fields_ = [("a", ctypes.c_uint16, 16),
...                 ("b", ctypes.c_uint64, 64),
...                 ("c", ctypes.c_uint8, 8),
...                 ("d", ctypes.c_uint8, 8)]
...
>>> x = Blah(0xDEAD,0xBEEF,0x44,0x12)
>>> print (hex(x.a) )
0xdead
>>> print (hex(x.b ))
0x0
>>> print (hex(x.c ))
0x44
>>> print (hex(x.d ))
0x12
>>>
>>> g = Blah(0x2BAD,0xBEEF,0x55,0x12)
>>> print (hex(g.a ))
0x2bad
>>> print (hex(g.b ))
0x0
>>> print (hex(g.c ))
0x55
>>> print (hex(g.d ))
0x12
>>>

varying field's size and I observe some weird cutoff of the input

>>> import ctypes
>>> class Blah(ctypes.Structure):
...     _fields_ = [("a", ctypes.c_uint64, 40),
...                 ("b", ctypes.c_uint64, 40),
...                 ("c", ctypes.c_uint8, 8),
...                 ("d", ctypes.c_uint8, 8)]
...
>>> x = Blah(0xDEAD,0xBEEF,0x44,0x12)
>>> print (hex(x.a) )
0xad
>>> print (hex(x.b ))
0xef
>>> print (hex(x.c ))
0x44
>>> print (hex(x.d ))
0x12
>>>
>>> g = Blah(0x2BAD,0xBEEF,0x55,0x12)
>>> print (hex(g.a ))
0xad
>>> print (hex(g.b ))
0xef
>>> print (hex(g.c ))
0x55
>>> print (hex(g.d ))
0x12
>>>

Does anyone know why is this happening?


回答1:


You could omit the 3rd field as a workaround.

>>> import ctypes
>>> class Blah(ctypes.Structure):
...   _fields_ = [("a", ctypes.c_uint64), ('b', ctypes.c_uint16), ('c', ctypes.c_uint8), ('d', ctypes.c_uint8)]
... 
>>> x = Blah(0xDEAD,0xBEEF,0x44,0x12)
>>> hex(x.a)
'0xdead'
>>> hex(x.b)
'0xbeef'

I guess the rest is a bug.



来源:https://stackoverflow.com/questions/3824617/python-structure-always-stuck-at-0-no-matter-what-value-you-assign-to-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!