将带有字符串的结构化numpy阵列传递到Cython函数



我正在尝试在Cython中创建一个函数,该函数通过定义Cython struct类型来接受Numpy结构化数组或记录数组。假设我有数据:

a = np.recarray(3, dtype=[('a', np.float32),  ('b', np.int32), ('c', '|S5'), ('d', '|S3')])
a[0] = (1.1, 1, 'this', 'to')
a[1] = (2.1, 2, 'that', 'ta')
a[2] = (3.1, 3, 'dogs', 'ot')

(注意:下面描述的问题发生在有或没有零终端的情况下)

我有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阵列中的思考。

缩短了对数据进行重新封装(这是可能的,但不是理想的),还有另一种方法将带有固定长度字符串数据的重新派机传递到Cython中吗?

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

https://groups.google.com/forum/# !! topic/cython-users/tblbxdi0_h4

更新2:此错误已固定在2014年2月23日GitHub的Master Cython分支机构中,该补丁定于v0.20.2:https://github.com中包含/cython/cython/commit/58d9361e0a6d4cb3d4e8777777777777777777550C2FEA836

这是一个错误,截至2014年2月22日,Github的主Cython分支已固定,该贴片计划包含在v0.20.2:https://github中。com/cython/cython/commit/58d9361e0a6d4cb3d4e87777777777777777550c2fea836

最新更新