2014-02-07 102 views
0

如何獲得結構尺寸?我已經使用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

對於任何解決方案?

回答

3

ctypes.sizeofsys.getsizeof是不一樣的。前者給出了c結構的大小,後者給出了python對象包裝的大小。

0

您無法將C structctypes.Structure對象進行比較。最後一個是Python對象,它包含比其伴侶c struct更多的信息。