[vtkusers] Destroying objects from Python

Prabhu Ramachandran prabhu at aero.iitm.ernet.in
Tue Oct 1 14:43:16 EDT 2002


>>>>> "BC" == bryan cole <bryan.cole at teraview.co.uk> writes:

    BC> I've got a VTK/Python question.  With python, when/how are VTK
    BC> objects destroyed?

    BC> Normal python objects are destroyed when their reference
    BC> counts are decreased to zero, but this cannot be true of VTK
    BC> objects: if I create a set of VTK objects locally in a
    BC> function, these objects persist outside of this function, even
    BC> though their references have been lost.

I'm not the expert on this since David Gobbi wrote the implementation
but here is my explanation of how things work.  I'll let David correct
me if I'm wrong.  The VTK-Python wrappers are a thin layer around the
VTK library.  As you must be aware, VTK has its own reference counting
mechanism.  When a VTK object is used by another the object increases
the reference count of the object it uses.  When it no longer needs
the object the objects refcount is decremented and when it drops to
zero the object is destroyed.  Its the same as in Python.

So here is an example demonstrating how it all works:

>>> import sys
>>> import vtk
>>> cs = vtk.vtkConeSource()
>>> out = cs.GetOutput()
>>> print sys.getrefcount (out)
 2
>>> print out.GetReferenceCount ()
 3
>>> m = vtk.vtkPolyDataMapper()
>>> m.SetInput(out)
>>> print out.GetReferenceCount()
 4
>>> print sys.getrefcount (out)
 2
>>> o = out
>>> sys.getrefcount (out)
3
>>> print out.GetReferenceCount ()
4
# Now how are objects deleted?
>>> print cs.GetReferenceCount()
3
>>> print sys.getrefcount(cs)
2
# Now turn on debug to see if the object is indeed deleted.
>>> cs.DebugOn()
>>> del cs
Debug: In /skratch/prabhu/vtk/cvs/VTK/Common/vtkObject.cxx, line 230
vtkConeSource (0x819e468): UnRegistered by NULL, ReferenceCount = 2

Debug: In /skratch/prabhu/vtk/cvs/VTK/Common/vtkObject.cxx, line 230
vtkConeSource (0x819e468): UnRegistered by NULL, ReferenceCount = 1
>>> 
# this object is not deleted because out still holds a reference
# internally.
>>> del out
# still nothing happens because GetOutput() is still held by the
# mapper.
>>> del m
Debug: In /skratch/prabhu/vtk/cvs/VTK/Common/vtkObject.cxx, line 225
vtkConeSource (0x819d1d0): UnRegistered by vtkPolyData (0x8136640), ReferenceCount = 0

Debug: In /skratch/prabhu/vtk/cvs/VTK/Common/vtkObject.cxx, line 126
vtkObject (0x819d1d0): Destructing!

I think this explains everything. :)

prabhu



More information about the vtkusers mailing list