title: Using PyCapsule in Cython
body: <h2>Summary</h2>
  <p>I need to store a C struct inside a Python object for use in other parts boosted with Cython. I believe a PyCapsule is best suited for this purpose, but the results of my code is not what I am expecting. While the pointer address is correctly returned, the memory appears to have been freed.</p>
  <h2>Details</h2>
  <p>I am new to Cython and I am learning to use it to speed up part of my code. For the purpose of asking the question, I have simplified my code and an int is used instead of a struct.</p>
  <p>I wrote CythonTest.pyx according to my understanding of the <a href="https://docs.python.org/3.5/c-api/capsule.html" rel="nofollow noreferrer">PyCapsule documentation</a> and compiled it with setup.py using the standard command:</p>
  <pre><code>python setup.py build_ext --inplace
  </code></pre>
  <p>CythonTest.pyx</p>
  <pre><code>#cython: language_level=3
  
  from cpython.pycapsule cimport PyCapsule_New, PyCapsule_IsValid, PyCapsule_GetPointer
  
  class Test:
      def __init__(self):
          cdef int test = 10
          cdef const char *name = &quot;test&quot;
          self.vars = PyCapsule_New(&lt;void *&gt;&amp;test, name, NULL)
          
          # Print pointer address
          print(&quot;{0:x}&quot;.format(&lt;unsigned long long&gt;test))
          
      def peek(self):
          cdef const char *name = &quot;test&quot;
          if not PyCapsule_IsValid(self.vars, name):
              raise ValueError(&quot;invalid pointer to parameters&quot;)
          cdef int *test = &lt;int *&gt;PyCapsule_GetPointer(self.vars, name)
          print(test[0])
          
          # Print pointer address
          print(&quot;{0:x}&quot;.format(&lt;unsigned long long&gt;test))
  </code></pre>
  <p>setup.py</p>
  <pre><code>from distutils.core import setup
  from Cython.Build import cythonize
  
  setup(ext_modules=cythonize(&quot;CythonTest.pyx&quot;))
  </code></pre>
  <p>Then, I run this with the following Python script.</p>
  <pre><code>from CythonTest import Test
  
  test = Test()
  print(test.vars)
  test.peek()
  </code></pre>
  <p>The console prints out the following:</p>
  <pre><code>cbde7ebe70
  &lt;capsule object &quot;test&quot; at 0x0000027516467930&gt;
  0
  cbde7ebe70
  </code></pre>
  <p>It appears that the pointer has been successfully stored in a PyCapsule and retrieved as indicated by the identical address. However, 0 is now stored inside the address instead of 10. I am aware that using an int may have caused it to be garbage collected and changed the nature of the problem, but the same issue is observed when using PyMem_Malloc as well.</p>
  <p>So the question is: what is the correct way of using PyCapsule?</p>
  <h2>Environment</h2>
  <ul>
  <li>Compiler: Visual Studio Express 2015</li>
  <li>Cython: 0.26</li>
  <li>OS: Windows 10 (64 bit)</li>
  <li>Python: 3.5.3</li>
  <li>Spyder (IDE): 3.2.3</li>
  </ul>