Cython函数中的字符串

时间:2015-06-16 23:03:15

标签: python string cython

我想这样做是为了将字符串传递给Cython代码:

# 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!

但如评论中所示,此处它无法按预期工作。

我发现的唯一解决方法是将长度作为myfunc的参数传递。这是对的吗? 真的是将字符串传递给Cython代码的最简单方法吗?

# 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 个答案:

答案 0 :(得分:8)

最简单的recommended方法是将参数作为Python字符串:

def myfunc(str mystr):