获得结构大小的困惑

时间:2014-02-07 14:42:16

标签: python

如何获得结构的大小?我使用了sys.getsizeof(),但它没有提供所需的输出。

让我们考虑下面的代码:

#using bit fields for storing variables
from ctypes import *
def MALE():
    return 0
def FEMALE():
    return 1
def SINGLE():
    return 0
def MARRIED():
    return 1
def DIVORCED():
    return 2
def WIDOWED():
    return 3
class employee(Structure):
    _fields_= [("gender",c_short, 1),                            #1 bit size for storage
               ("mar_stat", c_short, 2),                         #2 bit size for storage
               ("hobby",c_short, 3),                             #3 bit size for storage
               ("scheme",c_short, 4)]                            #4 bit size for storage
e=employee()
e.gender=MALE()
e.mar_status=DIVORCED()
e.hobby=5
e.scheme=9
print "Gender=%d\n" % (e.gender)
print "Marital status=%d\n" % (e.mar_status)
import sys
print "Bytes occupied by e=%d\n" % (sys.getsizeof(e))

输出:

Gender=0

Marital status=2

Bytes occupied by e=80

我想要Bytes occupies by e=2

任何解决方案?

2 个答案:

答案 0 :(得分:3)

ctypes.sizeofsys.getsizeof不一样。前者给出了c结构的大小,后者给出了python对象包装器的大小。

答案 1 :(得分:0)

您无法将C structctypes.Structure对象进行比较。最后一个是Python对象,它包含的信息比其伴随c struct要多得多。