问题
在 cython 中定义不同的对象时,内存视图将返回相同的地址。但是,数组本身在索引时会被修改。
背景。
我有用 cython 编写的基类和派生类。我注意到,当我对类应用多处理时,底层缓冲区在不同的进程中发生了变化,这不是有意的。在酸洗过程中,我编写了一个简单的 __reduce__ 方法和 __deepcopy__ 方法来重建原始对象。为了清楚起见,我降低了下面代码的复杂性。现在我的问题是,为什么内存视图返回相同的地址?此外,为什么即使 memoryview 相同,numpy 数组本身也会正确更改
#distutils: language=c++
import numpy as np
cimport numpy as np
cdef class Temp:
cdef double[::1] inp
def __init__(self, inp):
print(f'id of inp = {id(inp)}')
self.inp = inp
cdef np.ndarray x = np.ones(10)
cdef Temp a = Temp(x)
cdef Temp b = Temp(x)
cdef Temp c = Temp(x.copy())
b.inp[0] = -1
c.inp[2] = 10
print(f'id of a.inp = {id(a.inp)}\nid of b.inp = {id(b.inp))}\nid of c.inp = {id(c.inp)}')
print(f'id of a.inp.base = {id(a.inp.base)}\nid of b.inp.base = {id(b.inp.base))}\nid of c.inp.base = {id(c.inp.base)}')
print('a.inp.base',a.inp.base)
print('b.inp.base',b.inp.base) # expected to be the same as a
print('c.inp.base',c.inp.base) # expected to be different to a/b
输出:
id of inp = 139662709551872
id of inp = 139662709551872
id of inp = 139662709551952
id of a.inp = 139662450248672
id of b.inp = 139662450248672
id of c.inp = 139662450248672
id of a.inp.base = 139662709551872
id of b.inp.base = 139662709551872
id of c.inp.base = 139662709551952
a.inp.base [-1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
b.inp.base [-1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
c.inp.base [ 1. 1. 10. 1. 1. 1. 1. 1. 1. 1.]