Re: why the sizeof a structure always multiple of 4

Thomas Heller <[email protected]> Fri, 14 Nov 2003 21:03:12 +0100
Newsgroups gmane.comp.python.ctypes.devel
Message-ID <[email protected]>
aaron <aaronyy-/[email protected]> writes:

> The structure with size less than 4 is correct.
> but once it oven 4, it will always round up to next
> multiple of 4.

Not true, this prints '5':

"""
from ctypes import *

class X(Structure):
    _fields_ = [("a", c_char),
                ("b", c_char),
                ("c", c_char),
                ("d", c_char),
                ("e", c_char)]

print sizeof(X)
"""

But, as soon as there is an integer in the structure, the alignment
requirements are set to the alignment of the integer, and this also
rounds the size to the next sizeof(int) multiple, so this prints '8':

"""
from ctypes import *

class X(Structure):
    _fields_ = [("a", c_int),
                ("b", c_char)]

print sizeof(X)
"""

This *may* not be exactly the same as in C (I'm not sure), depending on
the C compiler, but IIRC it is required internally to allow using arrays
of Structures.

If it is wrong for you, you can always use custom packing, and this
prints '5' again:

"""
from ctypes import *

class X(Structure):
    _pack_ = 1
    _fields_ = [("a", c_int),
                ("b", c_char)]

print sizeof(X)
"""

Thomas



-------------------------------------------------------
This SF. Net email is sponsored by: GoToMyPC
GoToMyPC is the fast, easy and secure way to access your computer from
any Web browser or wireless device. Click here to Try it Free!
https://www.gotomypc.com/tr/OSDN/AW/Q4_2003/t/g22lp?Target=mm/g22lp.tmpl