在 Python ctypes 中为结构实现 offsetof()
我似乎无法为 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()
和 byref()
的事情,但没有运气。
当然,我希望它适用于所有体系结构,无论指针的大小如何, 并且无论填充的效果如何,所以请不要说只对 sizeof() 求和 对于所有先前的元素,除非您可以确保对 C 进行任何填充 编译器添加考虑在内。
有什么想法吗?谢谢!
I cannot seem to implement offsetof for a structure in ctypes. I have seen the
FAQ for ctypes, but either it doesn't work, or
I cannot figure out the details.
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
It seems addressof()
does not work on structure members (e.g. d.weight
). I have tried
other things involving pointer()
and byref()
, but no luck.
Of course I want this to work on all architectures, regardless of the size of a pointer,
and regardless of the effects of padding, so please don't say to just sum the sizeof()
for all previous elements, unless you can ensure that you're taking any padding the C
compiler adds into account.
Any ideas? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将其转化为方法的任务留给了读者:)
The task of turning this into a method is left to the reader :)
问题在于结构成员有时会以普通 Python 类型的形式返回。
例如
type(Test().f1) 是 type(Test().f2) 是 str
The trouble is that structure members are sometimes returned as plain python types.
For example
type(Test().f1) is type(Test().f2) is str