12

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]       
4
  • 1
    From the Cython tutorial: "Generally speaking: unless you know what you are doing, avoid using C strings where possible and use Python string objects instead." I'd recommend just declaring it as a str. Commented Jun 16, 2015 at 23:12
  • Can you post the code that would work with str @user2357112 ? Would it really be str or c_string or something else? Commented Jun 16, 2015 at 23:19
  • 1
    Well, char *mystr in C is just a pointer to some array (of characters or numbers), there is no way to know how large it is unless you explicitly provide its size with int length as you have done. If you want to avoid this, use def myfunc( str mystr): as @ user2357112 has indicated. Commented Jun 17, 2015 at 0:09
  • Ok great! @user2357112 I'll accept your answer if you post it Commented Jun 17, 2015 at 9:05

1 Answer 1

20

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

def myfunc(str mystr):
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.