Cython说,即使对于ndarray.copy(),缓冲区类型也只允许用作函数局部变量 [英] Cython says buffer types only allowed as function local variables even for ndarray.copy()

查看:82
本文介绍了Cython说,即使对于ndarray.copy(),缓冲区类型也只允许用作函数局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Cython的新手,遇到了以下代码片段:

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)

在编译过程中,表示仅允许作为函数局部变量的缓冲区类型。但是,我正在使用 .copy() .astype(),它返回的不是内存视图,而是一个副本。为什么这种情况仍在发生?

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?

谢谢!

推荐答案

何时您可以使用 np.ndarray [Type,dim] 在cython中定义一个数组,该数组正在访问python缓冲区接口,而这些不能设置为模块级变量。这是与视图和numpy数组数据的副本不同的问题。

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.

通常,如果我想将数组作为模块级变量(即,不是方法的局部变量),则定义输入memoryview ,然后使用(unested)之类的方法在其中设置它:

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()

这篇关于Cython说,即使对于ndarray.copy(),缓冲区类型也只允许用作函数局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆