changeset 126:8371983fee63

Added support for weakrefs to contexts.
author Atul Varma <varmaa@toolness.com>
date Sun, 23 Aug 2009 17:07:45 -0700
parents 05e18059b5c4
children 4179d1e1a75c
files src/context.cpp src/context.h tests/test_pymonkey.py
diffstat 3 files changed, 15 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/src/context.cpp	Sun Aug 23 16:20:15 2009 -0700
+++ b/src/context.cpp	Sun Aug 23 17:07:45 2009 -0700
@@ -103,6 +103,8 @@
 static void
 PYM_JSContextDealloc(PYM_JSContextObject *self)
 {
+  if (self->weakrefs)
+    PyObject_ClearWeakRefs((PyObject *) self);
   if (self->cx) {
     JS_DestroyContext(self->cx);
     self->cx = NULL;
@@ -522,13 +524,14 @@
   0,                           /*tp_setattro*/
   0,                           /*tp_as_buffer*/
   /*tp_flags*/
-  Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
+  Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_WEAKREFS,
   /* tp_doc */
   "JavaScript Context.",
   (traverseproc) PYM_traverse, /* tp_traverse */
   (inquiry) PYM_clear,         /* tp_clear */
   0,		               /* tp_richcompare */
-  0,		               /* tp_weaklistoffset */
+  /* tp_weaklistoffset */
+  offsetof(PYM_JSContextObject, weakrefs),
   0,		               /* tp_iter */
   0,		               /* tp_iternext */
   PYM_JSContextMethods,        /* tp_methods */
@@ -552,6 +555,7 @@
   if (context == NULL)
     return NULL;
 
+  context->weakrefs = NULL;
   context->opCallback = NULL;
   context->runtime = runtime;
   Py_INCREF(runtime);
--- a/src/context.h	Sun Aug 23 16:20:15 2009 -0700
+++ b/src/context.h	Sun Aug 23 17:07:45 2009 -0700
@@ -47,6 +47,7 @@
   PYM_JSRuntimeObject *runtime;
   JSContext *cx;
   PyObject *opCallback;
+  PyObject *weakrefs;
 } PYM_JSContextObject;
 
 extern PyTypeObject PYM_JSContextType;
--- a/tests/test_pymonkey.py	Sun Aug 23 16:20:15 2009 -0700
+++ b/tests/test_pymonkey.py	Sun Aug 23 17:07:45 2009 -0700
@@ -438,6 +438,14 @@
         cx = rt.new_context()
         self.assertEqual(cx.get_runtime(), rt)
 
+    def testContextsAreWeakReferencable(self):
+        rt = pymonkey.Runtime()
+        cx = rt.new_context()
+        wcx = weakref.ref(cx)
+        self.assertEqual(cx, wcx())
+        del cx
+        self.assertEqual(wcx(), None)
+
     def testUndefinedCannotBeInstantiated(self):
         self.assertRaises(TypeError, pymonkey.undefined)