2016-01-11 35 views
1

the manual about struct.calcsizestruct.calcsize(python)實際計算的結果是什麼?

truct.calcsize(fmt)¶ 

    Return the size of the struct (and hence of the string) corresponding to the given format 

但我不知道爲什麼struct.calcsize( 'HLL')不struct.calcsize( 'H')加struct.calcsize( 'L')的兩倍。見下文。任何想法?

In [216]: struct.calcsize('hll') 
Out[216]: 24 

In [217]: struct.calcsize('h') 
Out[217]: 2 

In [218]: struct.calcsize('l') 
Out[218]: 8 
+1

「*默認情況下,打包給定C結構的結果包含填充字節,以便爲所涉及的C類型保持適當的對齊。*」我不明白這是如何工作的,但這可能是說明。也許'l'總是需要8個字節用於對齊時與其他字段打包,但是當它是孤立的,可以省略。 –

回答

1

我認爲這是由於填充元素比機器字短,出於效率的目的。

對存儲器地址的訪問是機器字長度的倍數(例如對於64位機器爲8字節)往往會更快。出於這個原因,C編譯器會填充它們的結構,除非另有說明。 struct模塊將爲互操作性做同樣的工作。

雖然它看起來可以配置,但取決於您打算如何使用它。

相關問題