Python Structure & Union

>>> class myclass(Union):
...     _fields_ = [("c_long", c_long),("c_char", c_char*8)]
...
>>> s = myclass(2)
>>> s
<__main__.myclass object at 0x01D2B800>
>>> s = myclass('ssss')  ### This Error I still can not figure out, why a structure can not ###constructed with a string as defined
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required
>>> s = myclass(22)
>>> s  ### s is just a pointer to the sturcture; if you wanna access it, you need use dot operator
<__main__.myclass object at 0x01D2B8A0>
>>> print(s)
<__main__.myclass object at 0x01D2B8A0>
>>> print(byref(s)) ### just like the location of the pointer s
<cparam 'P' (01D2B8C8)>
>>> print("helld{}".format(s))
helld<__main__.myclass object at 0x01D2B8A0>
>>> print("helld{:d}".format(s))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'd' for object of type 'str'
>>> print("helld{:ld}".format(s))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Invalid conversion specification
>>> print("helld{:d}".format(s))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'd' for object of type 'str'
 
### Definition of the stucture in Python
>>> class myStructure(Structure):
...     _fields_ = [("int", c_int),("long", c_long),("char", c_char*8)]
...
>>> s = myStructure("good")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required
>>> s = myStructure(22, 22, "dddd")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected string, str found
### for construction, the third argument is char, thus we need a prefix b attached
>>> s = myStructure(22, 22, b"ssss")
 
>>> print(s.int)
22
 
>>> s = myclass(2222222)
>>> s.c_char
b'\x8e\xe8!'
>>> s.c_long
2222222
>>>
 
posted @ 2015-10-12 13:27  Q_Quan  阅读(312)  评论(0)    收藏  举报