Why is python ctypes class descriptor called when object is not being destroyed?
Question: 
    >>> 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 ?


Answer: `a` is a _proxy object_ , representing an array of C structs, in the Python
world. Each time you index into this object, `ctypes` creates a _new instance_
of the `A` class for you, to proxy the contained C structs.

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.

You could store the object produced by `a[0]` in a new variable:

    
    
    >>> 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:

    
    
    >>> 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):

    
    
    >>> del foo
    destructor called
    

