Cython 函数中的字符串

String in Cython functions

我想这样做以将字符串传递给 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]       

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

def myfunc(str mystr):