title: Python reference count and ctypes
body: <p>Hallo,</p>
  
  <p>I have some troubles understanding the python reference count.
  What I want to do is return a tuple from c++ to python using the ctypes module.</p>
  
  <p>C++:</p>
  
  <pre><code>PyObject* foo(...)
  {
  
    ...
    return Py_BuildValue("(s, s)", value1, value2);
  }
  </code></pre>
  
  <p>Python:</p>
  
  <pre><code>pointer = c_foo(...) # c_foo loaded with ctypes
  obj = cast(pointer, py_object).value
  </code></pre>
  
  <p>I'm was not sure about the ref count of obj, so I tried <code>sys.getrefcount()</code>
   and got <code>3</code>. I think it should be <code>2</code> (the <code>getrefcount</code> functions makes one ref itself).</p>
  
  <p>Now I can't make <code>Py_DECREF()</code> before the return in C++ because the object gets deleted. Can I decrease the ref count in python?</p>
  
  <p><em><strong>edit</em></strong>
  What happens to the ref count when the cast function is called? I'm not really sure from the documentation below. <a href="http://docs.python.org/library/ctypes.html#ctypes.cast" rel="nofollow">http://docs.python.org/library/ctypes.html#ctypes.cast</a></p>
  
  <blockquote>
    <p>ctypes.cast(obj, type)
       This function is similar to the cast operator in C. It returns a new instance of type which points to the same memory block as obj. type must be a pointer type, and obj must be an object that can be interpreted as a pointer.</p>
  </blockquote>