【发布时间】:2011-06-10 19:12:09
【问题描述】:
我似乎无法为 ctypes 中的结构实现 offsetof。我看过 FAQ for 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() 和byref() 的事情,但没有运气。
当然,我希望它适用于所有架构,无论指针大小如何, 并且不管填充的效果如何,所以请不要说只求和 sizeof() 对于所有以前的元素,除非您可以确保您正在使用任何填充 C 编译器添加考虑。
有什么想法吗?谢谢!
【问题讨论】:
标签: python c padding ctypes ffi