【发布时间】:2017-03-02 03:23:26
【问题描述】:
如果可以对以下代码的输出给出任何解释,我将不胜感激。我不明白为什么 sizeof(struct_2) 和 sizeof(my_struct_2) 不同,提供 sizeof(struct_1) 和 sizeof(c_int) 相同。
似乎ctypes 以某种不同的方式将struct 包装在struct 中?
from ctypes import *
class struct_1(Structure):
pass
int8_t = c_int8
int16_t = c_int16
uint8_t = c_uint8
struct_1._fields_ = [
('tt1', int16_t),
('tt2', uint8_t),
('tt3', uint8_t),
]
class struct_2(Structure):
pass
int8_t = c_int8
int16_t = c_int16
uint8_t = c_uint8
struct_2._fields_ = [
('t1', int8_t),
('t2', uint8_t),
('t3', uint8_t),
('t4', uint8_t),
('t5', int16_t),
('t6', struct_1),
('t7', struct_1 * 6),
]
class my_struct_2(Structure):
#_pack_ = 1 # This will give answer as 34
#_pack_ = 4 #36
_fields_ = [
('t1', c_int8),
('t2', c_uint8),
('t3', c_uint8),
('t4', c_uint8),
('t5', c_int16),
('t6', c_int),
('t7', c_int * 6),
]
print "size of c_int : ", sizeof(c_int)
print "size of struct_1 : ", sizeof(struct_1)
print "size of my struct_2 : ", sizeof(my_struct_2)
print "siz of origional struct_2: ", sizeof(struct_2)
输出:
size of c_int : 4
size of struct_1 : 4
size of my struct_2 : 36
siz of origional struct_2: 34 ==> why not 36 ??
编辑:
重命名 t6->t7(struct_1 数组)并从 struct_2 中删除 pack=2。但我仍然看到struct_2 和my_struct_2 的大小不同
【问题讨论】:
-
这是什么语言?如果是“C”,它使用了一些我不熟悉的扩展。
-
在我看来像 Python,而不是 C。
-
我认为是因为
struct_2被打包,所以t5之后没有填充。但是my_struct_2没有打包,所以在t5和t6之间有2 个字节的填充以使其字对齐。 -
顺便说一句,为什么
struct_2和my_struct_2中有两个t6成员?第二个不应该是t7吗? -
添加了[python](删除[memory-alignment]以腾出空间),因为问题是关于Python“ctypes”模块的。
标签: python c struct padding ctypes