specifying string types in cython code
<p>I'm doing some experimentation with cython and I came across some unexpected behavior: </p>

<pre><code>In [1]: %load_ext cython

In [2]: %%cython
   ...: cdef class foo(object):
   ...:     cdef public char* val
   ...:     def __init__(self, char* val):
   ...:         self.val = val
   ...:

In [3]: f = foo('aaa')

In [4]: f.val
Out[4]: '\x01'
</code></pre>

<p>What's going on with <code>f.val</code>? repeated inspection produces seemingly random output, so it looks like <code>f.val</code> is pointing to invalid memory.</p>

<p>The answer to <a href="http://stackoverflow.com/questions/30879708/string-in-cython-functions">this question</a> suggests that you should use <code>str</code> instead.
Indeed, this version works fine:</p>

<pre><code>In [21]: %%cython
    ...: cdef class foo(object):
    ...:     cdef public str val
    ...:     def __init__(self, str val):
    ...:         self.val = val
</code></pre>

<p>So, what is going on in the first version? It seems like the <code>char*</code> is getting freed at some point after class construction but I'm not really clear on why.</p>

<p>When you convert a Python bytestring to a <code>char *</code> in Cython, Cython gives you a pointer to the contents of the string object. This raw pointer does not affect the string's Python refcount (it'd be infeasible to track which pointers refer to which strings).</p>

<p>When the string's refcount hits zero and the string is reclaimed, your pointer becomes invalid.</p>

<p>You shouldn't convert Python bytestrings to <code>char *</code>s unless you actually need a <code>char *</code>. If you do, make sure to also keep a normal Python reference to the string for as long as you need the <code>char *</code>, to extend the string's lifetime.</p>

python cython