我似乎无法为 ctypes 中的结构实现 offsetof。我已经看过 ctypes 的常见问题解答,但要么它不起作用,要么我无法弄清楚细节。
Python 2.6.4 (r264:75706, Dec 19 2010, 13:04:47) [C] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import *
>>> class Dog(Structure):
... _fields_ = [('name', c_char_p), ('weight', c_int)]
... def offsetof(self, field):
... return addressof(field) - addressof(self)
...
>>> d = Dog('max', 80)
>>> d.offsetof(d.weight)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in offsetof
TypeError: invalid type
>>> d.offsetof(weight)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'weight' is not defined
>>> d.offsetof('weight')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in offsetof
TypeError: invalid type
它似乎addressof()
不适用于结构成员(例如d.weight
)。我尝试过其他涉及pointer()
and的事情byref()
,但没有运气。
当然,我希望它适用于所有架构,无论指针的大小如何,也不管填充的效果如何,所以请不要说只是对所有先前元素的 sizeof() 求和,除非你能确保您正在考虑 C 编译器添加的任何填充。
有任何想法吗?谢谢!