String in Cython functions

18.9k views Asked by At

I'd like to do this to pass a string to a Cython code:

# test.py
s = "Bonjour"
myfunc(s)

# test.pyx
def myfunc(char *mystr):
    cdef int i
    for i in range(len(mystr)):           # error! len(mystr) is not the length of string
        print mystr[i]                    # but the length of the *pointer*, ie useless!

but as shown in comment, here it doesn't work as expected.


The only workaround I've found is passing also the length as parameter of myfunc. Is it correct? Is it really the simplest way to pass a string to a Cython code?

# test.py
s = "Bonjour"
myfunc(s, len(s))


# test.pyx
def myfunc(char *mystr, int length):
    cdef int i
    for i in range(length):  
        print mystr[i]       
1

There are 1 answers

0
user2357112 On BEST ANSWER

The simplest, recommended way is to just take the argument as a Python string:

def myfunc(str mystr):