简体   繁体   English

如何在cython中声明全局numpy.ndarray?

[英]How to declare a global numpy.ndarray in cython?

I want to create a signal processing algorithm that needs to hold some internal state in a numpy array. 我想创建一个信号处理算法,需要在numpy数组中保持一些内部状态。

For speed, I coded that in cython and declared the state a global variable like this: 为了速度,我在cython中对其进行了编码,并将状态声明为如下全局变量:

import numpy as np
cimport numpy  as np
cdef np.ndarray delay_buffer

However, what I really would like to do is this: 但是,我真正想做的是:

import numpy as np
cimport numpy as np
DTYPE = np.float32
ctypedef np.float32_t DTYPE_t
cdef np.ndarray[DTYPE_t] delay_buffer

This I can do anyhwere else, but not in the global scope. 我可以做任何其他事情,但不是在全球范围内。 Is there any way to accomplish this? 有没有办法实现这个目标?

Is there any way to accomplish this? 有没有办法实现这个目标?

No. As the error says, Buffer types only allowed as function local variables . 不会。如错误所示, Buffer types only allowed as function local variables

One alternative is to use a monolithic main function. 一种替代方案是使用单片main函数。 This really only takes indenting everything but it means that you can only share so much. 这真的只需缩进一切,但这意味着你只能分享这么多。

My favourite alternative would be to upgrade to the modern method of using memoryviews: 我最喜欢的选择是升级到使用内存视图的现代方法:

cdef DTYPE_t[:] delay_buffer

The should be faster, cleaner and no less powerful. 应该更快,更清洁,同样强大。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM