在Python ctypes中为结构实现offsetof()

sam*_*amf 5 c python ctypes ffi padding

我似乎无法为ctypes中的结构实现offsetof.我已经看过ctypesFAQ,但要么它不起作用,要么我无法弄清楚细节.

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
Run Code Online (Sandbox Code Playgroud)

它似乎addressof()不适用于结构成员(例如d.weight).我曾尝试涉及其他的东西pointer()byref(),但没有运气.

当然,我希望这适用于所有体系结构,无论指针的大小如何,并且无论填充的效果如何,所以请不要仅仅为所有先前元素求和sizeof(),除非您可以确保你正在考虑C编译器添加的任何填充.

有任何想法吗?谢谢!

Sve*_*ach 15

class Dog(Structure):
    _fields_ = [('name', c_char_p), ('weight', c_int)]

Dog.name.offset
# 0
Dog.weight.offset
# 4 (on my 32-bit system)
Run Code Online (Sandbox Code Playgroud)

把它变成一种方法的任务留给读者:)