简体   繁体   English

为什么在没有销毁对象时调用python ctypes类描述符?

[英]Why is python ctypes class descriptor called when object is not being destroyed?

>>> from ctypes import *
>>> class A(Structure):
...  _fields_ = [('a', c_int)]
...  def __del__(self):
...   print("destructor called")
... 
>>> a = (A * 10)()
>>> a[0]
<__main__.A object at 0x7f93038cdd08>
>>> a[0]
destructor called
<__main__.A object at 0x7f93038cde18>
>>> a[0]
destructor called
<__main__.A object at 0x7f93038cdd08>
>>> a[0]
destructor called
<__main__.A object at 0x7f93038cde18>

Why is the destructor being called here ? 为什么在这里调用析构函数? Why is the address of the object different each time ? 为什么每次对象的地址都不同? Why doesn't python crash with a double free error ? 为什么python没有双重自由错误?

a is a proxy object , representing an array of C structs, in the Python world. a是一个代理对象 ,表示Python世界中的C结构数组。 Each time you index into this object, ctypes creates a new instance of the A class for you, to proxy the contained C structs. 每次索引此对象时, ctypes都会为您创建A类的新实例 ,以代理包含的C结构。

Now, because you don't store any references to this new object, it is also garbage collected as soon as it's repr() value has been echoed in the interpreter. 现在,因为您不存储对此新对象的任何引用,所以只要它的repr()值已在解释器中回显,它也会被垃圾收集。

You could store the object produced by a[0] in a new variable: 您可以将a[0]生成的对象存储在新变量中:

>>> foo = a[0]
>>> foo
<__main__.A object at 0x11061ea60>

This object will always be distinct from any others you create by indexing position 0 of a , but they all represent the same C struct because they reference the same address: 这个对象总是会从您的索引位置0创建的任何其他人不同的a ,但它们都代表相同的C结构,因为它们引用同一个地址:

>>> bar = a[0]
>>> foo is bar
False
>>> addressof(foo) == addressof(bar)
True

If you delete this reference the object is destructed again (provided you did not create more references to the Python proxy object of course): 如果删除此引用,则会再次销毁该对象(假设您当然没有创建对Python代理对象的更多引用):

>>> del foo
destructor called

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

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