In [1]:
%load_ext cython
In [2]:
%%cython
# cython: language_level=3
def f(char* text):
print(text)
In [3]:
f('It is I, Arthur, son of Uther Pendragon')
In [4]:
f(b'It is I, Arthur, son of Uther Pendragon')
In [9]:
%%cython
# cython: language_level=3
def g(str text):
print(text)
In [10]:
g('It is I, Arthur, son of Uther Pendragon')
Assigning Python unicode string to a C string
In [11]:
%%cython
def f(str text):
cdef char *s
s = text
print(s)
f('What? A swallow carrying a coconut?')
Even assign after encode fails...
In [12]:
%%cython
def f(str text):
cdef char *s
s = text.encode('utf-8')
print(s)
f('A five ounce bird could not carry a 1 pound coconut.')
You must have a Python unicode string variable
In [13]:
%%cython
def f(str text):
cdef char *s
bstr = text.encode('utf-8')
s = bstr
print(s)
f('It could be carried by an African swallow!')
In [14]:
%%cython
from libc.string cimport strcat
def f1(a, b):
""" A lot of effort to use strcat """
cdef:
char* ca # Declare C strings
char* cb
pa = a.encode('utf-8') # Make a bytes object
pb = b.encode('utf-8')
ca = pa # Assign bytes to the C strings
cb = pb
strcat(ca, cb) # Call the API method
pout = ca.decode('utf-8')
return pout
def f2(a, b):
""" Python: much easier """
return a + b
In [15]:
%timeit -n 1000 f1('first part', 'second part')
%timeit -n 1000 f2('first part', 'second part')
In [ ]: