首先,我希望实现的功能是传递一个对象到一个对象的成员函数中,并且在这个函数中使用,但是该对象在外部被修改之后,再次传递进来时,发现并没有改变,这就比较奇怪。
最小化实现如下
ti.init(arch=ti.gpu, default_ip=ti.i32, default_fp=ti.f32)
class A():
def __init__(self) -> None:
self.t = 0.0
def Inc(self):
self.t = self.t + 0.2
@ti.data_oriented
class B():
def __init__(self) -> None:
self.a = A()
@ti.kernel
def UpdateOnceTaichi(self, a: ti.template()):
print("UpdateOnceTaichi a.t = ", a.t)
def UpdateOncePython(self, a):
print("UpdateOncePython a.t = ", a.t)
def Update(self):
self.a.Inc()
print("=" * 20)
print("After Update,self.a.t = ", self.a.t)
self.UpdateOncePython(self.a)
self.UpdateOnceTaichi(self.a)
if __name__ == "__main__":
b = B()
b.Update()
b.Update()
运行结果
[Taichi] version 1.2.1, llvm 10.0.0, commit 12ab828a, osx, python 3.9.7
[Taichi] Starting on arch=metal
====================
After Update,self.a.t = 0.2
UpdateOncePython a.t = 0.2
UpdateOnceTaichi a.t = 0.2
====================
After Update,self.a.t = 0.4
UpdateOncePython a.t = 0.4
UpdateOnceTaichi a.t = 0.2 # 为何不是0.4
作为对比,UpdateOnceTaichi中只打印了0.2,但是python函数打印0.4(正确),为何会出现这样的情况,ti.template()里面做了什么优化吗?