Re: Structure inheritance and tail padding

eryk sun <[email protected]> Sat, 6 Feb 2016 20:04:11 -0600
Newsgroups gmane.comp.python.ctypes
Message-ID <CACL+1auNs50V0iYtV7jqzB87f9829+r+_JdDH812Dg9qj-r5YQ@mail.gmail.com>
On Sat, Feb 6, 2016 at 8:25 AM, Carlos Pita <[email protected]> wrote:
>
> just from observation I arrived to the unconfirmed conclusion that
> Structure inheritance adds tail padding. For example:
>
> class A(Structure):
>   _fields_ = [('a', c_double), ('b', c_char)]
>
> class B(A):
>   _fields_ = [('c', c_int)]
>

It's a subclass alternative to the following:

class A(Structure):
    _fields_ = (('a', c_double),
                ('b', c_char))

class B(Structure):
    _anonymous_ = '_A',
    _fields_ = (('_A', A),
                ('c',  c_int))

FYI, the padding at the end of "A" provides aligned access in
aggregates (arrays, structs). The size of "A" is 16 bytes, which is a
multiple of its 8-byte alignment. Similarly the size of B has to be
rounded up to 24 bytes, with 4 trailing pad bytes.

    >>> sizeof(B), alignment(B)
    (24, 8)
    >>> B.c
    <Field type=c_int, ofs=16, size=4>

Using a subclass is a good idea when several structures share a common
header. It's more flexible and scalable than cramming everything into
a union.

------------------------------------------------------------------------------
Site24x7 APM Insight: Get Deep Visibility into Application Performance
APM + Mobile APM + RUM: Monitor 3 App instances at just $35/Month
Monitor end-to-end web transactions and take corrective actions now
Troubleshoot faster and improve end-user experience. Signup Now!
http://pubads.g.doubleclick.net/gampad/clk?id=272487151&iu=/4140