[Cython] char* and string object
Jean-Alexandre Peyroux
peyroux at me.com
Sun Feb 1 00:23:36 CET 2009
Thank you for your advice.
Regards
Le 1 févr. 09 à 00:28, Dag Sverre Seljebotn a écrit :
> 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
> _______________________________________________
> Cython-dev mailing list
> Cython-dev at codespeak.net
> http://codespeak.net/mailman/listinfo/cython-dev
More information about the Cython-dev
mailing list