为了举例,我有这个代码:
cimport cython
from libc.stdlib cimport malloc
cdef int i
cdef int ii
cdef int j = 0
cdef int parnum = 6
cdef int sysnum = 2
cdef Particle *parlist = <Particle *>malloc( parnum * cython.sizeof(Particle))
cdef System *psys = <System *>malloc( sysnum * cython.sizeof(System))
for i in range(sysnum):
psys[i].particles = <Particle *>malloc( (parnum / sysnum) * cython.sizeof(Particle))
for ii in range(parnum / sysnum):
psys[i].particles[ii].x = j
parlist[j] = psys[i].particles[ii]
j += 1
print("--- before changes ---")
for i in range(sysnum):
for ii in range(parnum / sysnum ):
print(psys[i].particles[ii].x)
print("--- before changes ---")
for i in range(parnum):
parlist[i].x = 0
print("--- after changes ---")
for i in range(sysnum):
for ii in range(parnum / sysnum ):
print(psys[i].particles[ii].x)
print("--- after changes ---")
cdef struct System:
Particle *particles
cdef struct Particle:
int x
当程序运行时,它会在更改 parlist 元素之前和之后打印相同的结果。所以我不知道为什么,当我改变 parlist 的值时, psys.particles 的值根本没有改变。就好像 parlist 是一个副本,而不是一个实例。我如何使它成为一个实例,指向相同的东西?
非常感谢