6

我似乎无法为 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 编译器添加的任何填充。

有任何想法吗?谢谢!

4

2 回答 2

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

Dog.name.offset
# 0
Dog.weight.offset
# 4 (on my 32-bit system)

将其转化为方法的任务留给读者 :)

于 2011-01-18T00:43:16.333 回答
0

问题是结构成员有时会作为普通的 python 类型返回。例如

class Test(Structure):
    _fields_ = [('f1', c_char), ('f2', c_char * 0)]

type(Test().f1) 是 type(Test().f2) 是 str

于 2013-12-20T03:44:03.233 回答