Cython says buffer types only allowed as function

2019-04-24 18:43发布

I am new to Cython and encountered this code snippet:

import numpy as np
cimport numpy as np

testarray = np.arange(5)
cdef np.ndarray[np.int_t, ndim=1] testarray1 = testarray.copy()
cdef np.ndarray[np.float_t, ndim=1] testarray2 = testarray.astype(np.float)

During compilation, it said Buffer types only allowed as function local variables. However, I am using .copy() or .astype() which is returning not a memoryview, but a copy. Why is this still happening? How can I get around this?

Thanks!

1条回答
小情绪 Triste *
2楼-- · 2019-04-24 18:55

When you define an array in cython using np.ndarray[Type, dim], that is accessing the python buffer interface, and those can't be set as module level variables. This is a separate issue from views vs copies of numpy array data.

Typically if I want to have an array as a module level variable (i.e not local to a method), I define a typed memoryview and then set it within a method using something like (untested):

import numpy as np
cimport numpy as np

cdef np.int_t[:] testarray1

def init_arrays(np.int_t[:] testarray):
    global testarray1
    testarray1 = testarray.copy()
查看更多
登录 后发表回答