Reputation: 12138
When is the Ada type attribute Alignment
needed when wrapping C structures from Ada?
Our typical wrapper structure looks like
type T is record
a : aliased Interfaces.C.unsigned_char;
b : aliased Interfaces.C.double;
end record;
Now, when/where is
for T'Alignment use 8;
needed?
And does this depend on the target architecture?
Upvotes: 2
Views: 940
Reputation: 44804
The alignment attribute's purpose is not to support C compatibility, it is cheifly to provide compatibility with hardware that has special alignment restrictions for its data (including some data for some CPUs, most typically floats and the FPU).
That being said, technically I suppose it could be useful for C compatibility in situations where you know the alignment rules used by the C compiler you are trying to make your Ada code compatible with.
In this particular case, I suspect what would happen would be that the compiler would make sure all objects of type T get laid out at a quadword boundry. However, the compiler might then chose to put seven bytes of fill in the middle of your T object to ensure that the double
is also put on a quadword boundry. You can't really say without forcing its hand with a record representation clause as well. If you care how the internals of a record structure are laid out (eg: you want to ensure it matches some C layout), you probably ought to be explicit about it.
Upvotes: 1
Reputation: 8522
Ada 2012 LRM's definition of 'Alignment.
When 'Alignment is associated with a type, the address of objects of that type must be evenly divisible by the alignment value.
So in your definition, an object of type T could be explicitly placed, or will be automatically allocated by the compiler, at address 800, but not 804.
This becomes relevant when certain data types must obey alignment constraints, such as doubles starting on a double-word (8-byte) boundary. (This is dependent on target architecture--some impose such constraints, others do not.) Likewise, some architecture may allow multi-byte values to start on odd addresses--'Alignment use 1--but most not.
This issue is most likely to arise in situations such as you describe where you need to define an Ada layout matching an externally defined one. Specifying 'Alignment can ensure that objects and record components get properly laid out to match the external source.
Often though, especially when interfacing to C, simply applying the Convention aspect or pragma to the corresponding type definitions will ensure that the Ada layout automatically matches the C layout, leaving all the detailed aligning and padding to the compiler.
Upvotes: 2