Garbage Collection Question

C

Chaman Singh Verma

Hello,

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.

Bye.
csv
 
A

Aahz

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

Michael Hudson

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top