title: Python3 + ctypes callback causes memory leak in simple example
body: <p>While working on a complex program combining Python 3 code and C++ code using ctypes,  I found a memory leak that can easily be reproduced with the stripped down example below.</p>
  
  <p>My C++ code creates a Python object using a callback function. Next, it calls another callback on the Python object, that simply returns its argument.  The second callback causes the object's reference count to increase.  As a result,  the object never gets garbage-collected.</p>
  
  <p>This is the Python code (file bug.py):</p>
  
  <pre><code>import ctypes
  
  CreateObjectCallback = ctypes.CFUNCTYPE( ctypes.py_object )
  NoopCallback = ctypes.CFUNCTYPE( ctypes.py_object, ctypes.py_object )
  
  lib = ctypes.cdll.LoadLibrary("./libbug.so")
  
  lib.test.restype = ctypes.py_object
  lib.test.argtypes = [ CreateObjectCallback, NoopCallback ]
  
  class Foo:
      def __del__(self):
          print("garbage collect foo");
  
  def create():
      return Foo()
  
  def noop(object):
      return object
  
  lib.test(CreateObjectCallback(create), NoopCallback(noop))
  </code></pre>
  
  <p>This is the C++ code (file bug.cpp):</p>
  
  <pre><code>#include &lt;python3.6m/Python.h&gt;
  #include &lt;iostream&gt;
  #include &lt;assert.h&gt;
  
  extern "C" {
  
    typedef void *(*CreateObjectCallback)();
    typedef void *(*NoopCallback)(void *arg);
  
    void *test(CreateObjectCallback create, NoopCallback noop)
    {
      void *object = create();
      std::cerr &lt;&lt; "ref cnt = " &lt;&lt; ((PyObject*)(object))-&gt;ob_refcnt &lt;&lt; std::endl;
      object = noop(object);
      std::cerr &lt;&lt; "ref cnt = " &lt;&lt; ((PyObject*)(object))-&gt;ob_refcnt &lt;&lt; std::endl;
      return object;
    }
  }
  </code></pre>
  
  <p>And here are the commands I use to compile and run:</p>
  
  <pre><code>g++ -O3 -W -Wextra -Wno-return-type -Wall -Werror -fPIC -MMD   -c -o bug.o bug.cpp
  g++ -shared -Wl,-soname,libbug.so -o libbug.so bug.o 
  python3 bug.py
  </code></pre>
  
  <p>The output is:</p>
  
  <pre><code>ref cnt = 1
  ref cnt = 2
  </code></pre>
  
  <p>In other words,  the call to the noop function incorrectly increases the reference count, and the Foo object is not garbage collected.  Without the call to the noop function, the Foo object is garbage collected.  The expected output is:</p>
  
  <pre><code>ref cnt = 1
  ref cnt = 1
  garbage collect foo
  </code></pre>
  
  <p>Is this a known issue?  Does anyone know a work-around or solution? Is this caused by a bug in ctypes?</p>