将字符串传递给 Cython 函数
Passing string into Cython functions
过去几天我一直在试验 Cython,我有一个关于 c / cython 将字符串作为字符数组/指针处理的方式的快速问题:
def function(char *string):
for i in xrange(len(string)):
print string[i]
print &string[i]
例如,当我编译 运行 代码时,将 "abc"
作为参数,我得到以下答案:
97
abc
98
bc
99
c
现在我的问题是:
- 为什么cython会打印出
string[i]
中每个字符的ascii值?
- 为什么cython在
&string[i]
中打印出索引i
开始的字符串的后缀?
非常感谢。
像 Python 3 bytes
,当你在 Cython 中索引一个 char *
时,Cython treats the char
at that index as a numeric value, not text。这就是 print string[i]
打印数字的原因。
print &string[i]
的行为继承自 C。如果 char *
指向以下以 null 结尾的字符串:
|
v
+-+-+-+-+
|a|b|c| |
+-+-+-+-+
那么&string[1]
就是一个char *
,指向这里:
|
v
+-+-+-+-+
|a|b|c| |
+-+-+-+-+
这是也是一个以null结尾的字符串,这个字符串中有字符bc
。当你 print
它时,Cython 打印 bc
.
Cython docs建议不要使用char *
s:
Generally speaking: unless you know what you are doing, avoid using C strings where possible and use Python string objects instead.
过去几天我一直在试验 Cython,我有一个关于 c / cython 将字符串作为字符数组/指针处理的方式的快速问题:
def function(char *string):
for i in xrange(len(string)):
print string[i]
print &string[i]
例如,当我编译 运行 代码时,将 "abc"
作为参数,我得到以下答案:
97
abc
98
bc
99
c
现在我的问题是:
- 为什么cython会打印出
string[i]
中每个字符的ascii值? - 为什么cython在
&string[i]
中打印出索引i
开始的字符串的后缀?
非常感谢。
像 Python 3 bytes
,当你在 Cython 中索引一个 char *
时,Cython treats the char
at that index as a numeric value, not text。这就是 print string[i]
打印数字的原因。
print &string[i]
的行为继承自 C。如果 char *
指向以下以 null 结尾的字符串:
|
v
+-+-+-+-+
|a|b|c| |
+-+-+-+-+
那么&string[1]
就是一个char *
,指向这里:
|
v
+-+-+-+-+
|a|b|c| |
+-+-+-+-+
这是也是一个以null结尾的字符串,这个字符串中有字符bc
。当你 print
它时,Cython 打印 bc
.
Cython docs建议不要使用char *
s:
Generally speaking: unless you know what you are doing, avoid using C strings where possible and use Python string objects instead.