October 17, 2020
On Saturday, 17 October 2020 at 13:00:59 UTC, Per Nordlöw wrote:
> I understand that. I don't want the alignment of `S` to change. I want the padding after `s`

That padding is part of S. It is at the end, after its fields, but still part of it.

S's layout doesn't depend on what else is around it.

> in `T` to be avoided and have `c` start at byte-offset 7.

Use a union.

    struct S
    {
        int i;                  // 4 bytes
        short s;                // 2 byte
        bool b;                 // 1 byte
    }
    static assert(S.sizeof == 8);
    static assert(S.alignof == 4);

struct T {
   union {
       S s;
       struct {
           align(1):
           ubyte[7] _ignore_me;
           char c;
       }
   }
}

static assert(T.alignof == 4);
static assert(T.sizeof == 8);
static assert(T.c.offsetof == 7);

October 17, 2020
On Saturday, 17 October 2020 at 13:23:38 UTC, Adam D. Ruppe wrote:
> Use a union.

Nice! Thanks!
October 17, 2020
On 10/17/20 9:00 AM, Per Nordlöw wrote:
> On Saturday, 17 October 2020 at 12:51:21 UTC, ag0aep6g wrote:
>> c does come directly after s. The padding between b and c is part of s. If you don't want that padding, you can use `align(1)` to define S without padding. But then 75% of the ints in an S[] will be misaligned.
> 
> I understand that. I don't want the alignment of `S` to change. I want the padding after `s` in `T` to be avoided and have `c` start at byte-offset 7. I don't see why this padding is needed in the case where only a single (1-element array of) `S` is stored as a field inside another aggregate.
> 
> Ali's code prints:
> 
> === Memory layout of 'T' (.sizeof: 12, .alignof: 4) ===
>     0: S s
>     8: char c
>     9: ... 3-byte PADDING

There might be some good reasons for this.

For one, what happens if you copy the s? Does it copy the c too?

For another, this is how C does it, so I would expect it to at least match C for compatibility.

I think it *should* be possible to do this, if it's not already, just with pragmas. (i.e. pack T but not S).

-Steve
October 17, 2020
On Saturday, 17 October 2020 at 13:42:46 UTC, Steven Schveighoffer wrote:
> I think it *should* be possible to do this, if it's not already, just with pragmas. (i.e. pack T but not S).

Agree, a pragma, say `pragma(pack)`, to control this would be great to avoid the unsafe union hack.
1 2
Next ›   Last »