What Are The Exact Rules For Structure Alignment On IPhone OS?

- 1 answer

I'm using the Objective-C NSMethodSignature / @encode facilities to do some cross-language data type translation, which means that I need to be able to programmatically copy values into a structure described in @encode() format. e.g., I may have 4 floats and need to insert them into a CGRect, which is a structure containing 2 structures, each of which contains 2 floats each. In @encode terminology, the type is this:


To do this I need to be able to guess the structure layout knowing only the data types of the primitive structure members -- in this case 4 floats.

It appears that historically there have been two different conventions for ARM struct alignment. One was to align all members of the struct on a boundary size which would satisfy the largest member. The other was to align all members on the boundary size appropriate to each member's data type.

Which is used in OS X / iPhone OS, both on ARM and on x86 / x86_64?



If you simply want to encode a CGRect you should probably use the UIGeometryKeyedCoding category addition for NSCoder -encodeCGRect:forKey:.

If you are wanting to go between systems you might consider converting the CGRect to an NSRect using NSRectFromCGRect() and then encoding the NSRect using -encodeValueOfObjCType:at:.

If you are wanting to encode other C structures Apple has a very clear policy laid out in the documentation labled 'Encoding and Decoding C Data Types'. As it states under 'Structures and Bit Fields', "The best technique for archiving a structure or a collection of bit fields is to archive the fields independently and chose the appropriate type of encoding/decoding method for each."