The fields of your union are declared incorrectly. You've declared an attribute named "ch[2]"
.
To demonstrate this, have a look at this variant of your program:
#Demo of union at work
from ctypes import *
class a(Union):
_fields_= [("i", c_int, 16),
("ch[2]",c_char)]
key=a()
key.i = 65
print getattr(key, "ch[2]")
Output
A
You probably meant to write code like this:
_fields_= [("i", c_int, 16),
("ch", c_byte*2)]
This declares ch
to be an array of c_byte
, with length 2.
Note that I use c_byte
in place of c_char
because you expect an integral type rather than a character.
So, here's the corrected program:
#Demo of union at work
from ctypes import *
class a(Union):
_fields_= [("i", c_int, 16),
("ch",c_byte*2)]
key=a()
key.i=512
print key.i
print key.ch[0]
print key.ch[1]
Output
512
0
2