title: How to store python objects in Cython C++ containers?
body: <p>I would like to port an existing <a href="/questions/tagged/c%2b%2b" class="post-tag" title="show questions tagged &#39;c++&#39;" rel="tag">c++</a> library with <a href="/questions/tagged/cython" class="post-tag" title="show questions tagged &#39;cython&#39;" rel="tag">cython</a> to Python, with the C++ library employing <a href="/questions/tagged/templates" class="post-tag" title="show questions tagged &#39;templates&#39;" rel="tag">templates</a>. In this case, it is the <a href="http://www.ornl.gov/~1qn/adevs/index.html" rel="noreferrer">adevs library</a>.</p>
  
  <p><strong>The question is how can I store Python objects in a C++ container with Cython? I know this is somehow  <a href="https://groups.google.com/d/msg/cython-users/3IbBVnnVIxw/CggJCX28pmYJ" rel="noreferrer">discouraged</a>, for issues of reference counting, but can it be done nevertheless and if so, how?</strong></p>
  
  <p>I am aware of <a href="https://stackoverflow.com/a/16951962/2366781">Gauthier Boaglios' answer</a> to a <a href="https://stackoverflow.com/q/16907168/2366781">similar question</a>. However, this does not address the issue of reference counting, apparently, as I tried the following:</p>
  
  <p>Let's say in 'cadevs.pxd' I have the following code:</p>
  
  <pre><code>cdef extern from "adevs/adevs_digraph.h" namespace "adevs":
  cdef cppclass PortValue[VALUE, PORT]:
      PortValue() except +
      PortValue(PORT port, const VALUE&amp; value) except +
      PORT port
      VALUE value
  </code></pre>
  
  <p>And in 'adevs.pyx':</p>
  
  <pre><code>from cpython.ref cimport PyObject
  cimport cadevs
  
  ctypedef PyObject* PythonObject
  
  cdef class PortValue:
      cdef cadevs.PortValue[PythonObject, PythonObject]* _c_portvalue
  
      def __cinit__(self, object port, object value):
          self._c_portvalue = new cadevs.PortValue[PythonObject, PythonObject](
              &lt;PyObject *&gt;port, &lt;PyObject *&gt;value
          )
  
      def __dealloc__(self):
          del self._c_portvalue
  
      property port:
          def __get__(self):
              return &lt;object&gt;self._c_portvalue.port
  
      property value:
          def __get__(self):
              return &lt;object&gt;self._c_portvalue.value
  </code></pre>
  
  <p>Then I cythonize and compile</p>
  
  <pre><code>$ cython --cplus -3 adevs.pyx
  $ g++ -shared -pthread -fPIC -fwrapv -O2 -Wall -I/usr/include/python3.4m -I../include -lpython3.4m -o adevs.so adevs.cpp
  </code></pre>
  
  <p>But running in python or ipython</p>
  
  <pre><code>import adevs
  pv = adevs.PortValue((1,2), 3)
  pv.port
  pv.port
  </code></pre>
  
  <p>crashes Python as the reference to the (1, 2) tuple is lost, apparently.</p>