3

为了举例,我有这个代码:

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 是一个副本,而不是一个实例。我如何使它成为一个实例,指向相同的东西?

非常感谢

4

1 回答 1

1

好的,我读了一些关于指针的内容,这是我的解决方案:

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))
    psys[i].particles = &parlist[j]
    for ii in range(parnum / sysnum):
        parlist[j].x = j
        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 = i * 10

print("--- after changes ---")
for i in range(sysnum):
    for ii in range(parnum / sysnum ):
        print(psys[i].particles[ii].x)
print("--- after changes ---")

for i in range(parnum):
    change_onebyone(&parlist[i])

print("--- after function one by one ---")
for i in range(sysnum):
    for ii in range(parnum / sysnum ):
        print(psys[i].particles[ii].x)
print("--- after function one by one  ---")

change_all(parlist,parnum)

print("--- after function all---")
for i in range(sysnum):
    for ii in range(parnum / sysnum ):
        print(psys[i].particles[ii].x)
print("--- after function all---")

cdef change_onebyone(Particle *par):
    par.x *= 10

cdef change_all(Particle *parlist2, int num):
    for i in range(num):
        parlist2[i].x *= 10

cdef struct System:
    Particle *particles

cdef struct Particle:
    int x

我不知道它是否正确使用它,但它正在做我所期望的。

于 2013-02-27T15:36:36.960 回答