Author Topic: Structure Packing and Alignment  (Read 6568 times)

Offline Hooman

  • Administrator
  • Hero Member
  • *****
  • Posts: 4954
Structure Packing and Alignment
« on: July 13, 2021, 05:49:10 AM »
Hmm, here's a consideration for struct packing with #pragma pack that I'd never considered before:
Anybody who writes #pragma pack(1) may as well just wear a sign on their forehead that says “I hate RISC”

It seems using #pragma pack(1) affects not just the field alignment, but also the alignment of the struct as a whole when the struct is used for a field of some larger type.

Offline Vagabond

  • Global Moderator
  • Hero Member
  • *****
  • Posts: 1014
Re: Structure Packing and Alignment
« Reply #1 on: July 14, 2021, 08:06:08 PM »
That is interesting.

Did you see in the comments there might be a way to restore alignment to the struct but leave the data itself as packed?

Quote
Out of curiosity, could you combine #pragma pack(1) with __declspec(align(4)) to get the structure packing effect, without impacting the alignment of the structure when embedded in other structures?

My quick experiments suggest that yes you can add __declspec(align(4)) or alignas(4) to restore 4-byte alignment.

But note that this is not guaranteed to be sufficient; I believe some 64-bit architectures require 8-byte alignment?

__declspec(align(sizeof(void*))) should work but I have not tried it.

Prefer using “struct alignas(void*) Foo”

I suppose the OP2Utility code falls in the serialization category so it was appropriate to mark it with pragma pack.

Offline Hooman

  • Administrator
  • Hero Member
  • *****
  • Posts: 4954
Re: Structure Packing and Alignment
« Reply #2 on: July 20, 2021, 08:15:15 AM »
That is useful to know. I hadn't noticed the comments.

Indeed, this is relevant for OP2Utility.