Fred Drake | 68304cc | 2002-04-05 23:01:14 +0000 | [diff] [blame] | 1 | #include "Python.h" |
| 2 | |
| 3 | typedef struct { |
| 4 | PyObject_HEAD |
| 5 | PyObject *container; |
| 6 | } MyObject; |
| 7 | |
| 8 | static int |
| 9 | my_traverse(MyObject *self, visitproc visit, void *arg) |
| 10 | { |
| 11 | if (self->container != NULL) |
| 12 | return visit(self->container, arg); |
| 13 | else |
| 14 | return 0; |
| 15 | } |
| 16 | |
| 17 | static int |
| 18 | my_clear(MyObject *self) |
| 19 | { |
| 20 | Py_XDECREF(self->container); |
| 21 | self->container = NULL; |
| 22 | |
| 23 | return 0; |
| 24 | } |
| 25 | |
| 26 | static void |
| 27 | my_dealloc(MyObject *self) |
| 28 | { |
| 29 | PyObject_GC_UnTrack((PyObject *) self); |
| 30 | Py_XDECREF(self->container); |
| 31 | PyObject_GC_Del(self); |
| 32 | } |
| 33 | |
| 34 | static PyTypeObject |
| 35 | MyObject_Type = { |
| 36 | PyObject_HEAD_INIT(NULL) |
| 37 | 0, |
| 38 | "MyObject", |
| 39 | sizeof(MyObject), |
| 40 | 0, |
| 41 | (destructor)my_dealloc, /* tp_dealloc */ |
| 42 | 0, /* tp_print */ |
| 43 | 0, /* tp_getattr */ |
| 44 | 0, /* tp_setattr */ |
| 45 | 0, /* tp_compare */ |
| 46 | 0, /* tp_repr */ |
| 47 | 0, /* tp_as_number */ |
| 48 | 0, /* tp_as_sequence */ |
| 49 | 0, /* tp_as_mapping */ |
| 50 | 0, /* tp_hash */ |
| 51 | 0, /* tp_call */ |
| 52 | 0, /* tp_str */ |
| 53 | 0, /* tp_getattro */ |
| 54 | 0, /* tp_setattro */ |
| 55 | 0, /* tp_as_buffer */ |
| 56 | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, |
| 57 | 0, /* tp_doc */ |
| 58 | (traverseproc)my_traverse, /* tp_traverse */ |
| 59 | (inquiry)my_clear, /* tp_clear */ |
| 60 | 0, /* tp_richcompare */ |
| 61 | 0, /* tp_weaklistoffset */ |
| 62 | }; |
| 63 | |
| 64 | /* This constructor should be made accessible from Python. */ |
| 65 | static PyObject * |
| 66 | new_object(PyObject *unused, PyObject *args) |
| 67 | { |
| 68 | PyObject *container = NULL; |
| 69 | MyObject *result = NULL; |
| 70 | |
| 71 | if (PyArg_ParseTuple(args, "|O:new_object", &container)) { |
| 72 | result = PyObject_GC_New(MyObject, &MyObject_Type); |
| 73 | if (result != NULL) { |
| 74 | result->container = container; |
| 75 | PyObject_GC_Track(result); |
| 76 | } |
| 77 | } |
| 78 | return (PyObject *) result; |
| 79 | } |