Garbage Collection Question

N.E. Daynow panbru at comcast.net
Thu Aug 28 20:40:41 EDT 2003


Aahz wrote:
> In article <2ce55ce2.0308281518.4be94efc at posting.google.com>,
> Chaman Singh Verma <csv610 at yahoo.com> wrote:
> 
>>I am trying to integrate C++ with Python. I read that Python does
>>automatic garbage collection. I am creating new objects in C++ and
>>passing to Python, I don't know now who should control deleting the
>>objects. If I create objects in C++ do I have to clean them or Python
>>will use GC to remove unwanted objects.
> 
> 
> Depends whether it's a Python object created with a Python API call.  If
> not, your objects will never be touched by Python.

If your C++ object is represented in Python land by a Python opaque 
pointer (a/k/a a CObject), you can designate a destructor that will be 
called when your CObject's reference count reaches zero.  You'll need to 
create a destructor function of the proper form to pass to the CObject 
creation function:

     PyObject* PyCObject_FromVoidPtr(void* cobj, void (*destr)(void *))

Note that "cobj" is a pointer to your C++ object and "destr" is your 
destructor function which will simply delete the C++ object.  You can 
get a void pointer to your C++ object back from Python land with:

     void* PyCObject_AsVoidPtr(PyObject* self)

Good luck,

Tim





More information about the Python-list mailing list