简体   繁体   English

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

[英]Implementing offsetof() for structures in Python ctypes

I cannot seem to implement offsetof for a structure in ctypes. 我似乎无法为ctypes中的结构实现offsetof。 I have seen the FAQ for ctypes , but either it doesn't work, or I cannot figure out the details. 我已经看过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

It seems addressof() does not work on structure members (eg d.weight ). 似乎addressof()不适用于结构成员(例如d.weight )。 I have tried other things involving pointer() and byref() , but no luck. 我尝试过涉及pointer()byref()其他事情,但没有运气。

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

Any ideas? 有任何想法吗? Thanks! 谢谢!

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

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

The task of turning this into a method is left to the reader :) 把它变成一种方法的任务留给读者:)

The trouble is that structure members are sometimes returned as plain python types. 问题是结构成员有时以普通的python类型返回。 For example 例如

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM