29

我正在尝试通过定义 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 函数似乎没有正确检测到cd字段之间的边界,并且认为您正在传递长度总和的 char 数组。

除了重新洗牌数据(这是可能的但不理想),还有另一种方法可以将具有固定长度字符串数据的recarray传递给Cython吗?

更新:这似乎是一个潜在的 Cython 错误。请参阅以下关于 Cython google 组的讨论,该讨论暗示了问题出现的位置:

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

4

1 回答 1

1

这是截至 2014 年 2 月 22 日已在 Github 上的主 cython 分支中修复的错误,该补丁计划包含在 v0.20.2 中:https ://github.com/cython/cython/commit/58d9361e0a6d4cb3d4e87775f78e0550c2fea836

于 2014-03-14T20:29:19.220 回答