Commit 5656dea4 authored by gabrieldemarmiesse's avatar gabrieldemarmiesse

In the string tutorial: Added try...finally and moved a small code snippet back to the .rst file.

parent 9cbd59ed
from libc.stdlib cimport free
from c_func cimport c_call_returning_a_c_string
def main():
cdef char* c_string = c_call_returning_a_c_string()
cdef bytes py_string = c_string
# A type cast to `object` or `bytes` will do the same thing:
py_string = <bytes> c_string
free(c_string)
......@@ -7,12 +7,16 @@ cdef Py_ssize_t n = strlen(hello_world)
cdef char* c_call_returning_a_c_string():
cdef char* c_string = <char *> malloc((n + 1) * sizeof(char))
if not c_string:
raise MemoryError()
strcpy(c_string, hello_world)
return c_string
cdef void get_a_c_string(char** c_string_ptr, Py_ssize_t *length):
c_string_ptr[0] = <char *> malloc((n + 1) * sizeof(char))
if not c_string_ptr[0]:
raise MemoryError()
strcpy(c_string_ptr[0], hello_world)
length[0] = n
......@@ -9,8 +9,7 @@ def main():
# get pointer and length from a C function
get_a_c_string(&c_string, &length)
py_bytes_string = c_string[:length]
free(c_string)
print(py_bytes_string) # py_bytes_string is still available
try:
py_bytes_string = c_string[:length] # Performs a copy of the data
finally:
free(c_string)
......@@ -107,7 +107,7 @@ within a well defined context.
Passing byte strings
--------------------
we have a dummy C functions declared in
we have dummy C functions declared in
a file called :file:`c_func.pyx` that we are going to reuse throughout this tutorial:
.. literalinclude:: ../../examples/tutorial/string/c_func.pyx
......@@ -119,9 +119,16 @@ We make a corresponding :file:`c_func.pxd` to be able to cimport those functions
It is very easy to pass byte strings between C code and Python.
When receiving a byte string from a C library, you can let Cython
convert it into a Python byte string by simply assigning it to a
Python variable:
Python variable::
.. literalinclude:: ../../examples/tutorial/string/assignment.pyx
from c_func cimport c_call_returning_a_c_string
cdef char* c_string = c_call_returning_a_c_string()
cdef bytes py_string = c_string
A type cast to :obj:`object` or :obj:`bytes` will do the same thing::
py_string = <bytes> c_string
This creates a Python byte string object that holds a copy of the
original C string. It can be safely passed around in Python code, and
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment