[python]理解union

2020-01-09 20:58:59 浏览数 (1)

不懂数据结构苦啊

union在内存中只占有一块内存空间,空间大小由union中占位最多的数据类型决定,union在初始化的时候,union的值,由最后一个有效参数决定

代码语言:javascript复制
'''
Created on 2012-9-9

@author: jincheng
'''
from ctypes import *

print "aaa:"
value = raw_input()
v=int(value)
vv=long(value)
vvv=value
class aaa(Union):
    _fields_=[
       ("aaa",c_int),
       ("bbb",c_long),
       ("ccc",c_char),       ]

print "aaaaaaa:%s" %value

a=aaa(v,vv,vvv)

print "aaa: %d" %a.aaa
print "bbb: %ld" %a.bbb
print "ccc: %s" %a.ccc

test1

代码语言:javascript复制
c:Python27>python D:jinchengworkspaceGrayHatPythonchapter1.py
aaa:
6
aaaaaaa:6
aaa: 54
bbb: 54
ccc: 6

test2

代码语言:javascript复制
c:Python27>python D:jinchengworkspaceGrayHatPythonchapter1.py
aaa:
66
aaaaaaa:66

aaa: 13878
bbb: 13878
ccc: 66

修改

代码语言:javascript复制
from ctypes import *

print "aaa:"
value = raw_input()
v=int(value)

print "v %d" %v

print "bbb:"
val=raw_input()
vv=long(val)
vvv=value
class aaa(Union):
    _fields_=[
       ("aaa",c_int),
       ("bbb",c_long),
       ("ccc",c_char * 6),       ]

print "aaaaaaa:%s" %value

a=aaa(v,vv)

s=a.aaa

ss=int(s)

print "ss %d" %ss

print "aaa: %d" %a.aaa
print "bbb: %ld" %a.bbb
print "ccc: %s" %a.ccc

test

代码语言:javascript复制
D:Python27>python d:demo.py
aaa:
66
v 66
bbb:
55
aaaaaaa:66
ss 55
aaa: 55
bbb: 55
ccc: 7

0 人点赞