以前有人問過同樣的問題:Objective-C Runtime: What to put for size & alignment for class_addIvar? 但是沒有完全解決。class_addIvar在Objective-C中的對齊方式是什麼?
功能聲明如下:
BOOL class_addIvar(Class cls, const char *name, size_t size, uint8_t alignment, const char *types)
其用於一個實例變量添加到目標C動態創建的類。
第四說法,uint8_t alignment
,蘋果的文檔中描述:
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))
。
在一些教程中,它只是聲稱,如果伊娃是指針類型,我應該使用log2(sizeof(pointer_type))
;如果伊娃是價值型的,我應該使用sizeof(value_type)
。但爲什麼?有人可以詳細解釋這一點嗎?
說到指針類型,我不認爲應該在class_addIvar中使用_Alignof。在Apple的文檔中,應該使用log2(sizeof(pointer_type))。我現在理解數據對齊的概念,但仍不明白class_addIvar中指針類型的對齊方式。 –
@ZhuShengq我的壞。你應該做'log2(_Alignof(type))'。原因在於'class_addIvar'內部,它通過爲您執行'1 << alignment'操作來調整對齊。 –
謝謝,你只是澄清我的困惑! log2(_Alignof(type))使一切變得清晰。但是對於指針類型,Apple似乎希望我們使用_Alignof(int)作爲值類型,log2(_Alignof(int *))。也許蘋果在class_addIvar中執行值/指針類型檢查?我也用一些值類型和指針類型來實驗NSGetSizeAndAlignment。有趣的是它們的大小始終等於對齊。也許在其他平臺上它並不支持任何平臺的版本 –