[Cython] char* and string object
Dag Sverre Seljebotn
dagss at student.matnat.uio.no
Sun Feb 1 00:28:55 CET 2009
Jean-Alexandre Peyroux wrote:
> Hello,
>
> I think i did not understand the handling character string. This is an
> example :
>
> user.pyx :
>
> cdef class User:
> def __init__(self, char* name):
> self.cname = name
>
> cpdef printName(self):
> print "My name is %s" % self.cname
>
> user.pxd :
>
> cdef class User:
> cdef readonly char* cname
>
> cpdef printName(self)
>
>
<snip>
> In [5]: u.cname
> Out[5]: '_3'
>
> I do not understand. My string is completely random, as if it was
> pointing in the wrong location of memory.
> I missed step ?
This is expected. When you do "self.cname = name", then you get a
pointer to the character buffer inside the "name" string object. Then,
"name" goes out of scope and is deallocated, along with its memory, and
perhaps filled with something else.
Moral? Only use conversion to char* when you really need it because you
call C code or similar, and also then you need to hold on to the
corresponding Python string as well.
--
Dag Sverre
More information about the Cython-dev
mailing list