Garbage Collection Question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Chaman Singh Verma

    Garbage Collection Question

    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
  • Aahz

    #2
    Re: Garbage Collection Question

    In article <2ce55ce2.03082 81518.4be94efc@ posting.google. com>,
    Chaman Singh Verma <csv610@yahoo.c om> wrote:[color=blue]
    >
    >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.[/color]

    Depends whether it's a Python object created with a Python API call. If
    not, your objects will never be touched by Python.
    --
    Aahz (aahz@pythoncra ft.com) <*> http://www.pythoncraft.com/

    This is Python. We don't care much about theory, except where it intersects
    with useful practice. --Aahz

    Comment

    • Michael Hudson

      #3
      Re: Garbage Collection Question

      csv610@yahoo.co m (Chaman Singh Verma) writes:
      [color=blue]
      > 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.[/color]

      Um, I think I need more detail to fully answer this.
      [color=blue]
      > If I create objects in C++ do I have to clean them or Python will
      > use GC to remove unwanted objects.[/color]

      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(Th ingObject, &Thing_Type) ;
      thing->thing = new Thing();
      return (PyObject*)thin g;
      }

      void thing_dealloc(P yObject* 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

      Comment

      Working...