[Cython] char* to string conversion
Stefan Behnel
stefan_ml at behnel.de
Wed Apr 29 18:55:27 CEST 2009
Jack Stahl wrote:
> Quick question. If I want to return a char * from Cython to Python as a
> string, should I be freeing the original char * or not? In other words,
> when Cython does the implicit conversion from char * ---> string, does it
> create a Python object and strcpy the char * into its data, or does it copy
> the pointer?
It creates a copy that is owned by the str/bytes object.
> Here's some code to make this clearer:
>
> cdef class MyStringHolder:
>
> cdef char *my_str
>
> ...
>
> cpdef add_to_set(object set):
> // Is this necessary or is this a memory leak?
> cdef char * str_cpy = <char*>malloc(strlen(my_str) + 1)
> strcpy(str_cpy, my_str)
>
> // Should this just be set.add(my_str)?
> set.add(str_cpy)
Yes, passing my_str should be enough (unless what you want is actually a
unicode string, in which case you need to decode it).
Stefan
More information about the Cython-dev
mailing list