Cython函数中的字符串 [英] String in Cython functions

查看:233
本文介绍了Cython函数中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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]       


推荐答案

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

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

def myfunc(str mystr):

这篇关于Cython函数中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆