如何将一个numpy字符串类型数组传递给Cython中的函数

Hey*_*his 16 python numpy cython

传递一个numpy数组的dtype np.float64_t工作正常(下图),但我无法传递字符串数组.

这是有效的:

# cython_testing.pyx
import numpy as np
cimport numpy as np

ctypedef np.float64_t dtype_t 

cdef func1 (np.ndarray[dtype_t, ndim=2] A):
    print A 

def testing():
    chunk = np.array ( [[94.,3.],[44.,4.]], dtype=np.float64)

    func1 (chunk)
Run Code Online (Sandbox Code Playgroud)

但我无法做到这一点: 我找不到匹配的'类型标识符'为numpy字符串dtypes.

# cython_testing.pyx
import numpy as np
cimport numpy as np

ctypedef np.string_t dtype_str_t 

cdef func1 (np.ndarray[dtype_str_t, ndim=2] A):
    print A 

def testing():
    chunk = np.array ( [['huh','yea'],['swell','ray']], dtype=np.string_)

    func1 (chunk)
Run Code Online (Sandbox Code Playgroud)

编译错误是:

Error compiling Cython file:
------------------------------------------------------------
ctypedef np.string_t dtype_str_t 
    ^
------------------------------------------------------------

cython_testing.pyx:9:9: 'string_t' is not a type identifier
Run Code Online (Sandbox Code Playgroud)

UPDATE

通过浏览numpy.pxd,我看到以下ctypedef陈述.也许这足以说我可以使用uint8_t并假装一切正常,只要我可以做一些演员?

ctypedef unsigned char      npy_uint8
ctypedef npy_uint8      uint8_t
Run Code Online (Sandbox Code Playgroud)

只需看看铸造的成本有多高.

JAB*_*JAB 7

看起来你运气不好.

http://cython.readthedocs.org/en/latest/src/tutorial/numpy.html

尚不支持某些数据类型,如布尔数组和字符串数组.


这个答案已经不再有效,正如Saullo Castro的回答所示,但我会将其留作历史用途.


Sau*_*tro 7

使用Cython 0.20.1,它可以使用cdef np.ndarray,而无需指定数据类型和维度数:

import numpy as np
cimport numpy as np

cdef func1(np.ndarray A):
    print A

def testing():
    chunk = np.array([['huh','yea'], ['swell','ray']])
    func1(chunk)
Run Code Online (Sandbox Code Playgroud)