user3223301
user3223301

Reputation: 211

Confusion in getting size of a structure

How to get size of a structure? I have used sys.getsizeof() but it's not giving the desired output.

Let's consider below code:

#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))

oUTPUT:

Gender=0

Marital status=2

Bytes occupied by e=80

I want Bytes occupies by e=2

Any solution for that?

Upvotes: 0

Views: 59

Answers (2)

Francis Avila
Francis Avila

Reputation: 31651

ctypes.sizeof and sys.getsizeof are not the same. The former gives the size of the c structure, the latter gives the size of the python object wrapper.

Upvotes: 3

Cilyan
Cilyan

Reputation: 8501

You cannot compare a C struct with a ctypes.Structure object. The last one is a Python object that contains a lot more information than its companion c struct.

Upvotes: 0

Related Questions