【问题标题】:Is it possible to pass a numpy array by reference into a cpdef function?是否可以通过引用将 numpy 数组传递给 cpdef 函数?
【发布时间】:2020-11-12 19:21:16
【问题描述】:

是否可以编写一个 Cython 函数,其中 numpy 数组 通过引用 传递(也许是内存视图?),我可以在 Python 中使用这样的函数?

我试过了:

cpdef void my_function(bytes line, int& counter, np.ndarray[np.uint32_t, ndim=2]& sums):
    ...
    ...

这里countersums 将通过引用传递。我对后者感兴趣(但很乐意接受关于这两者的批评和建议)。

编译器抛出:

Reference base type cannot be a Python object

我也收到了与cdef 相同的信息,但我不了解问题的完整病因。

【问题讨论】:

  • 介绍一下阵列? shape,尤其是dtype
  • @hpaulj unsigned integersshape = (76 x 74)

标签: python numpy cython


【解决方案1】:

是的 - 有点。

Numpy 数组是一个 Python 对象。无论如何,所有 Python 对象都是“通过引用”传递的(即,如果您在函数内部更改 Numpy 数组的内容,则在外部更改它)。

所以你就这样做

cpdef void my_function(bytes line, int& counter, np.ndarray[np.uint32_t, ndim=2] sums):

将其指定为 C++ 引用并没有多大意义。对于 Python 对象,Cython 隐藏了很多细节。


但是,cpdef 函数设计为可从 Python 和 Cython 调用。 Python 整数(和其他数字类型)are immutable。因此,当从 Python 调用时,更改 counter 不会像你想象的那样工作,如果它做了你希望的那样,它可能会破坏解释器。

因此,我会避免在 cpdef 函数中使用引用(并且可能主要完全避免 cpdef 函数 - 通常最好只决定 defcdef

【讨论】:

    猜你喜欢
    • 2016-06-19
    • 1970-01-01
    • 2012-08-05
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多