我试图在cython中创建一个函数,通过定义cython结构类型接受numpy结构化数组或记录数组。假设我有数据:
a = np.recarray(3, dtype=[('a', np.float32), ('b', np.int32), ('c', '|S5'), ('d', '|S3')])
a[0] = (1.1, 1, 'this\0', 'to\0')
a[1] = (2.1, 2, 'that\0', 'ta\0')
a[2] = (3.1, 3, 'dogs\0', 'ot\0')
(注意:下面描述的问题在有或没有空终止符的情况下发生)
然后我有了cython代码:
import numpy as np
cimport numpy as np
cdef packed struct tstruct:
np.float32_t a
np.int32_t b
char[5] c
char[3] d
def test_struct(tstruct[:] x):
cdef:
int k
tstruct y
for k in xrange(3):
y = x[k]
print y.a, y.b, y.c, y.d
当我尝试运行test_struct(a)
时,我收到错误:
ValueError: Expected a dimension of size 5, got 8
如果在数组和相应的结构中重新排序,使得包含字符串的字段彼此不相邻,则该函数按预期工作。看起来好像Cython函数没有正确检测c
和d
字段之间的边界,并认为您传入了长度总和的char数组。
如果没有重新调整数据(可能但不理想),是否有另一种方法可以将带有固定长度字符串数据的重新排列传递给Cython?
更新:这似乎是一个潜在的Cython错误。请参阅以下有关Cython谷歌群组的讨论,该群组提示问题出现在哪里:
https://groups.google.com/forum/#!topic/cython-users/TbLbXdi0_h4
更新2:自2014年2月23日起,该错误已在Github上的主cython分支中修复,该补丁计划包含在v0.20.2中:https://github.com/cython/cython/commit/58d9361e0a6d4cb3d4e87775f78e0550c2fea836
答案 0 :(得分:1)
这是一个错误,已于2014年2月22日在Github上的主cython分支中修复,该补丁计划包含在v0.20.2中:https://github.com/cython/cython/commit/58d9361e0a6d4cb3d4e87775f78e0550c2fea836