Reputation: 3802
Someone has ask the same question before:Objective-C Runtime: What to put for size & alignment for class_addIvar? But it's not fully resolved.
The functions declaration is as follows:
BOOL class_addIvar(Class cls, const char *name, size_t size, uint8_t alignment, const char *types)
Which is used to add an instance variable to a dynamically created class in Objective-C.
The forth argument, uint8_t alignment
, is described in Apple's documentation:
The instance variable's minimum alignment in bytes is 1<<align. The minimum alignment of an instance variable depends on the ivar's type and the machine architecture. For variables of any pointer type, pass log2(sizeof(pointer_type))
.
In some tutorials, it's just claimed that if the ivar is pointer type, I should use log2(sizeof(pointer_type))
; if the ivar is value type, I should use sizeof(value_type)
. But why? Can someone explain this in detail?
Upvotes: 3
Views: 933
Reputation: 55573
If you really want to learn where these values come from, you'll need to look at architecture specific ABI references, for OSX and iOS, they can be found here: OS X, iOS.
Each of those documents should have a section titled 'Data Types and Data Alignment', which helps to explain those values for the specific architecture.
In practice, since C11, you can use the _Alignof
operator to have the compiler give you the correct value for a specific type (as it already needs to know this in order to generate proper machine code), so you can create a class_addIvar
that looks something like this:
class_addIvar(myClass, "someIvar", sizeof(int), log2(_Alignof(int)), @encode(int))
Which should take care of all those gory details of the underlying type for you.
Upvotes: 6