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

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

Sorry, I forgot to mention that I am 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
>>>

replacing the first position of two fields gives the 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
>>>

changing the size of the field and I observe some strange clipping 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 this is happening?

+3
source share
1 answer

.

>>> 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'

, .

+1

Source: https://habr.com/ru/post/1767222/


All Articles