String in Cython functions

2019-04-27 18:25发布

问题:

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:

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

def myfunc(str mystr):