<div>What is the rule of thumb when declaring functions from python&#39;s C-api when comes to ref counting?</div><div><br></div><div>If I define a test case like so:</div><div><br></div><div><div>cdef extern from &quot;Python.h&quot;:</div>
<div><br></div><div>    object PyWeakref_NewRef(object, object)</div><div>    object PyWeakref_GET_OBJECT(object)</div><div><br></div><div><br></div><div>class Foo(object):</div><div>    pass</div><div><br></div><div><br>
</div><div>cdef class Test:</div><div><br></div><div>    cdef object obj</div><div>    cdef object wr</div><div><br></div><div>    def __init__(self):</div><div>        self.obj = Foo()</div><div>        self.wr = PyWeakref_NewRef(self.obj, None)</div>
<div>    </div><div>    def get_ref(self):</div><div>        return PyWeakref_GET_OBJECT(self.wr)</div></div><div><br></div><div><br></div><div>I get these random python fatal errors:</div><div><br></div><div><div>In [8]: %timeit -n 1000 t.get_ref()</div>
<div>1000 loops, best of 3: 224 ns per loop</div><div><br></div><div>In [9]: %timeit -n 1000 t.get_ref()</div><div>Fatal Python error: deallocating None</div><div>Abort trap</div></div><div><br></div><div><br></div><div>However, if I redefine the macro signature and getter function to this:</div>
<div><br></div><div><div>from cpython cimport PyObject</div><div><br></div><div>cdef extern from &quot;Python.h&quot;:</div><div><br></div><div>    object PyWeakref_NewRef(object, object)</div><div>    PyObject* PyWeakref_GET_OBJECT(object)</div>
<div><br></div><div><br></div><div>class Foo(object):</div><div>    pass</div><div><br></div><div><br></div><div>cdef class Test:</div><div><br></div><div>    cdef object obj</div><div>    cdef object wr</div><div><br></div>
<div>    def __init__(self):</div><div>        self.obj = Foo()</div><div>        self.wr = PyWeakref_NewRef(self.obj, None)</div><div><br></div><div>    def clear_obj(self):</div><div>        self.obj = None</div><div>    </div>
<div>    def get_ref(self):</div><div>        return &lt;object&gt;PyWeakref_GET_OBJECT(self.wr)</div></div><div><br></div><div><br></div><div>Then it runs without issue. I can other gather is has to due the incref/decref going on in the generated C code. Should be doing something on my end to manually manage ref counts when using the C-Api?</div>
<div><br></div><div><br></div>