Reference count problem (Python -> C)

Carl Bevil carl_bevil at
Tue Mar 11 07:43:12 CET 2003

Hello all.  I'm hoping that the issue I'm having is a fairly common one, and 
that there is an accepted solution.

Basically, I want to use Python to build a data structure up for use in C++.  
So I have Python code that looks like this:

import myStuff

root = myStuff.Tree("Root")
root.AddChild(myStuff.myObject("Child 1"))
root.AddChild(myStuff.myObject("Child 2"))
root.AddChild(myStuff.myObject("Child 3"))

Under the hood, this creates a new "Tree" object, which gets attached to a 
pointer internally.  Three "myObject" objects are also created, and each one 
gets attached to the tree object.

The problem is that Python doesn't know that under the hood the objects are 
getting assigned to internal pointers, so as soon as they are no longer 
referenced by Python objects, the are deleted.   So the "Child 1" object is 
deleted before the next line, same with "Child 2" and "Child 3", with root 
getting deleted at the very end.

Are there any good solutions for this type of thing?   I am using SWIG to 
generate my bindings, and was hoping to not have to hand-edit the generated 
files (as I may have to generate them several times over the course of the 

Something like a cross-language smart-pointer mechanism would be good, though 
I think that might be pie-in-the-sky thinking.  :-)

Any advice appreciated!


More information about the Python-list mailing list