
"ioquatix (Samuel Williams) via ruby-core" <ruby-core@ml.ruby-lang.org> wrote:
Are you saying that in general:
``` struct A { int x; float y; char z; struct S s; }; ```
and
``` struct B { int x; float y; }; ```
That reinterpreting a pointer to A as a pointer to B, and accessing field `B::y` is never undefined? And that generalises? The only rule I knew was the first field, if a struct, is guaranteed to be at offset=0. Are you able to link me to the standard?
(oops, battery died last week and I forgot about Ruby entirely :x) As long as it's the same HW arch, yes. AFAIK C itself doesn't say anything about it, it's up to every ABI. https://refspecs.linuxfoundation.org/elf/ has a bunch of ABIs. abi386-4.pdf (via pdftotext) states: Each member is assigned to the lowest available offset with the appropriate alignment. This may require internal padding, depending on the previous member.
While I understand what you are saying may be true, I was not able to find confirmation of it in the standard.
It's a lot of arch-specific ABIs to read through and I haven't read every one; but keep in mind FFI/Rust interop would not work at all without a predictable C ABI. I do similar things via Perl syscall wrapper and pack (same as Ruby Array#pack) on various architectures the GCC Compiler Farm (cfarm) provides with no problems. You can always add STATIC_ASSERT on the offsets to ensure new platforms are behaving. I don't expect Ruby will be able to run at all if there's a hypothetical platform with unpredictable offsets. All this only applies to C and normal C types (not C++)