title: ctypes __del__ of ctypes.Structure subclass not invoked for pointers to structures
body: <p>The C library I'm wrapping requires allocating and destroying the memory of the structure inside of C functions, and always passes pointers, not structures.</p>
  
  <p>I have a subclass of <code>ctypes.Structure</code> with a <code>__del__</code> method. This method is not invoked when calling <code>del</code> on an instance that is a pointer to the structure returned from a function in C (<code>Foo_init</code>). Interestingly, it is invoked when calling <code>del</code> if that instance is not a pointer, but the actual value, returned from a different C function (<code>Foo_init_value</code>).</p>
  
  <p>How can I get the <code>__del__</code> method to invoke for pointers to structures that were returned from a function in C?</p>
  
  <p>In Python:</p>
  
  <pre><code>import ctypes
  import gc
  libfoo = ctypes.CDLL("libfoo.so")
  
  class Foo(ctypes.Structure):
      _fields_ = [
          ('a', ctypes.c_int),
          ('b', ctypes.POINTER(ctypes.c_char)),
      ]
      def __del__(self):
          print('deleting')
          libfoo.Foo_destroy(self)
  
  # Get a pointer to Foo
  libfoo.Foo_init.restype = ctypes.POINTER(Foo)
  libfoo.Foo_init.argtypes = None
  
  # Get actual Foo, not pointer
  libfoo.Foo_init_value.restype = Foo
  libfoo.Foo_init_value.argtypes = None
  
  libfoo.Foo_destroy.restype = ctypes.c_int
  libfoo.Foo_destroy.argtypes = [ctypes.POINTER(Foo)]
  
  # Get a pointer to Foo
  foo = libfoo.Foo_init()
  # Nothing is printed here:
  del foo
  # Nothing is printed here
  gc.collect()
  # Nothing is printed here
  [f for f in gc.get_objects() if isinstance(f, Foo)]
  
  # Get an actual Foo, not pointer
  foo = libfoo.Foo_init_value()
  # This works, prints 'deleting', but crashes with freeing an invalid pointer
  # presumably because __del__ is passing the struct, not pointer to struct
  del foo
  </code></pre>
  
  <p>Here is my trivial C library:</p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  
  typedef struct Foo {
      int a;
      char *b;
  } Foo;
  
  /* Allocate and return pointer to Foo */
  /* __del__ does not work for this one */
  Foo *Foo_init(void)
  {
      Foo *foo = (Foo *) malloc(sizeof(Foo));
      foo-&gt;a = 0;
      foo-&gt;b = NULL;
      return foo;
  }
  
  /* Allocate and return value of Foo, not a pointer*/
  /* __del__ works on this */
  Foo Foo_init_value(void)
  {
      Foo *foo = Foo_init();
      return *foo;
  }
  
  int *Foo_destroy(Foo *foo)
  {
      if (foo-&gt;b) {
           free(foo-&gt;b);
           foo-&gt;b = NULL;
      }
      free(foo);
      return 0;
  }
  </code></pre>
  
  <p>To compile:</p>
  
  <pre><code>gcc -c -Wall -Werror -fpic foo.c
  gcc -shared -o libfoo.so foo.o
  </code></pre>