python - Cython:将单个元素分配给多维内存 View 切片

标签 python python-3.x slice cython memoryview

每当我将单个值分配给多维内存 View 的切片时,Cython 似乎使用了错误的步幅,除非切片沿着第一维。我在下面给出一个完整的例子:

# bug.py
import numpy as np

def bug():
    #cdef int[:, ::1] a
    a = 2*np.ones((2, 2), dtype=np.intc)
    a[:, :1] = 1
    print(np.asarray(a))

如果我们在 Python 中运行它(例如 python3 -c 'import bug; bug.bug()'),我们得到

[[1 2]
 [1 2]]

如预期的那样打印出来。我现在通过将文件重命名为 bug.pyx 用 Cython 编译它,将以下内容保存在同一目录的 Makefile 中,

# Makefile
python = python3
python_config = $(python)-config
CC = gcc
CFLAGS  = $(shell $(python_config) --cflags) -fPIC
CFLAGS += $(shell $(python_config) --includes)
python_libdir = $(shell $(python) -c "import sysconfig; \
    print(sysconfig.get_config_var('LIBDIR'));")
LDLIBS  = -L$(python_libdir) -Wl,-rpath=$(python_libdir)
LDLIBS += $(shell $(python_config) --libs)
LDFLAGS = $(shell $(python_config) --ldflags) -shared

bug.so: bug.c; $(CC) $(CFLAGS) $(LDFLAGS) $(LDLIBS) -o bug.so bug.c
bug.c: bug.pyx; $(python) -m cython -3 $<

并运行make。运行 python3 -c 'import bug; bug.bug()' 再次获取编译后的 bug.so,再次打印出来

[[1 2]
 [1 2]]

如果我们现在取消注释 cdef 声明,运行 makepython3 -c 'import bug; bug.bug()' 再次,我们得到

[[1 1]
 [2 2]]

这是错误的。我不相信 int[:,::1] 声明是错误的,因为 Cython 会提示。如果我只用 int[:, :] 替换它,它就可以工作。此外,如果我分配给 a 的第一个维度,a[:1, :] = 1,它会起作用。

这是一个已知问题,还是我以某种方式误解了 Cython 内存 View 的这种看似基本的用法?

最佳答案

我提交了一个 bug report从那以后,问题就变成了fixed .

关于python - Cython:将单个元素分配给多维内存 View 切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55959627/

相关文章:

python - 从列表列表中删除所有出现的特定值 python

python - 区分curses中的^J和<Enter>

python - 如何从numpy中的一维数组中提取零维切片

arrays - std.algorithm.remove() 复制数组项?

python - 如何分配给非字符串 "name"或索引的列?

python - 如何从类方法传递函数指针

python - 使用 Pandas 读取csv文件时如何选择多行?

c++ - 使用 python3-config 进行 Pybind11 编译不起作用

python - 我可以移动虚拟环境吗?

带有重复标签的xml解析