6

ctypes の構造体に offsetof を実装できないようです。ctypesの FAQ を見ました が、動作しないか、詳細がわかりません。

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コンパイラが追加するパディングを考慮しています。

何か案は?ありがとう!

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 に答える