blob: e46aecf38587f6361d1d890d326591cb27e6a577 [file] [log] [blame]
Andrew Hsieh83760d22013-06-18 12:24:28 -07001/* Weak references objects for Python. */
2
3#ifndef Py_WEAKREFOBJECT_H
4#define Py_WEAKREFOBJECT_H
5#ifdef __cplusplus
6extern "C" {
7#endif
8
9
10typedef struct _PyWeakReference PyWeakReference;
11
12/* PyWeakReference is the base struct for the Python ReferenceType, ProxyType,
13 * and CallableProxyType.
14 */
15struct _PyWeakReference {
16 PyObject_HEAD
17
18 /* The object to which this is a weak reference, or Py_None if none.
19 * Note that this is a stealth reference: wr_object's refcount is
20 * not incremented to reflect this pointer.
21 */
22 PyObject *wr_object;
23
24 /* A callable to invoke when wr_object dies, or NULL if none. */
25 PyObject *wr_callback;
26
27 /* A cache for wr_object's hash code. As usual for hashes, this is -1
28 * if the hash code isn't known yet.
29 */
30 long hash;
31
32 /* If wr_object is weakly referenced, wr_object has a doubly-linked NULL-
33 * terminated list of weak references to it. These are the list pointers.
34 * If wr_object goes away, wr_object is set to Py_None, and these pointers
35 * have no meaning then.
36 */
37 PyWeakReference *wr_prev;
38 PyWeakReference *wr_next;
39};
40
41PyAPI_DATA(PyTypeObject) _PyWeakref_RefType;
42PyAPI_DATA(PyTypeObject) _PyWeakref_ProxyType;
43PyAPI_DATA(PyTypeObject) _PyWeakref_CallableProxyType;
44
45#define PyWeakref_CheckRef(op) PyObject_TypeCheck(op, &_PyWeakref_RefType)
46#define PyWeakref_CheckRefExact(op) \
47 (Py_TYPE(op) == &_PyWeakref_RefType)
48#define PyWeakref_CheckProxy(op) \
49 ((Py_TYPE(op) == &_PyWeakref_ProxyType) || \
50 (Py_TYPE(op) == &_PyWeakref_CallableProxyType))
51
52/* This macro calls PyWeakref_CheckRef() last since that can involve a
53 function call; this makes it more likely that the function call
54 will be avoided. */
55#define PyWeakref_Check(op) \
56 (PyWeakref_CheckRef(op) || PyWeakref_CheckProxy(op))
57
58
59PyAPI_FUNC(PyObject *) PyWeakref_NewRef(PyObject *ob,
60 PyObject *callback);
61PyAPI_FUNC(PyObject *) PyWeakref_NewProxy(PyObject *ob,
62 PyObject *callback);
63PyAPI_FUNC(PyObject *) PyWeakref_GetObject(PyObject *ref);
64
65PyAPI_FUNC(Py_ssize_t) _PyWeakref_GetWeakrefCount(PyWeakReference *head);
66
67PyAPI_FUNC(void) _PyWeakref_ClearRef(PyWeakReference *self);
68
69/* Explanation for the Py_REFCNT() check: when a weakref's target is part
70 of a long chain of deallocations which triggers the trashcan mechanism,
71 clearing the weakrefs can be delayed long after the target's refcount
72 has dropped to zero. In the meantime, code accessing the weakref will
73 be able to "see" the target object even though it is supposed to be
74 unreachable. See issue #16602. */
75
76#define PyWeakref_GET_OBJECT(ref) \
77 (Py_REFCNT(((PyWeakReference *)(ref))->wr_object) > 0 \
78 ? ((PyWeakReference *)(ref))->wr_object \
79 : Py_None)
80
81
82#ifdef __cplusplus
83}
84#endif
85#endif /* !Py_WEAKREFOBJECT_H */