Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String in Cython functions

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]       
like image 666
Basj Avatar asked Jun 16 '15 23:06

Basj


1 Answers

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

def myfunc(str mystr):
like image 57
user2357112 supports Monica Avatar answered Nov 05 '22 15:11

user2357112 supports Monica