[python]理解union

发布时间:2019-09-05 07:33:58编辑:auto阅读(2256)

    不懂数据结构苦啊

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

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

    c:\Python27>python D:\jincheng\workspace\GrayHatPython\chapter1.py
    aaa:
    6
    aaaaaaa:6
    aaa: 54
    bbb: 54
    ccc: 6
    test2

    c:\Python27>python D:\jincheng\workspace\GrayHatPython\chapter1.py
    aaa:
    66
    aaaaaaa:66
    
    aaa: 13878
    bbb: 13878
    ccc: 66
    修改

    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
    D:\Python27>python d:\demo.py
    aaa:
    66
    v 66
    bbb:
    55
    aaaaaaa:66
    ss 55
    aaa: 55
    bbb: 55
    ccc: 7


关键字