Garbage Collection Question

Michael Hudson mwh at python.net
Fri Aug 29 08:00:35 EDT 2003


csv610 at yahoo.com (Chaman Singh Verma) writes:

> 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.

Um, I think I need more detail to fully answer this.

> If I create objects in C++ do I have to clean them or Python will
> use GC to remove unwanted objects.

As Aahz noted, Python only GCs objects it knows about, i.e. PyObjects.

A common pattern is to have a custom Python object encapsulate one of
your C++ objects.  So you do something like this:

static PyTypeObject Thing_Type;

struct ThingObject {
    PyObject_HEAD
    Thing* thing;
}

PyObject* Thing_New()
{
    Thing* thing = PyObject_New(ThingObject, &Thing_Type);
    thing->thing = new Thing();
    return (PyObject*)thing;
}

void thing_dealloc(PyObject* thing)
{
    delete ((ThingObject*)thing)->thing;
    thing->ob_type->tp_free();
}

and make sure thing_dealloc ends up in the tp_dealloc slot of
Thing_Type.

HTH,
mwh

-- 
  if-you-need-your-own-xxx.py-you-know-where-to-shove-it<wink>-ly 
  y'rs - tim
              -- Tim Peters dishes out versioning advice on python-dev




More information about the Python-list mailing list