Reference count problem (Python -> C)

A. Lloyd Flanagan alloydflanagan at attbi.com
Tue Mar 11 12:08:49 EST 2003


Carl Bevil <carl_bevil at yahoo.com> wrote in message news:<CFN376909466722801 at news.mindspring.com>...
> 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 

I would think you'd have to use Py_INCREF() in C++ to increment the
reference counts for for the objects.
So when you add an object to the tree, the tree will have to increment
the reference count.  Python won't do it since it doesn't have a
python variable referring to the object.  When the tree is done with
object, it will have to do a Py_DECREF() so python can free up the
memory.




More information about the Python-list mailing list