String in Cython Functions

I would like to do this to pass a string to 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 the comment, here it does not work as expected.


The only workaround I found was to pass the length as a parameter as well myfunc. Is it correct? Is this really the easiest way to pass a string to 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]       
+4
source share
1 answer

The easiest, recommended - just take the argument as a Python string:

def myfunc(str mystr):
+7
source

All Articles