|
| 1 | +/** |
| 2 | + * This file contains an exemplary base object class with intrusive reference |
| 3 | + * counting. The implementation is designed so that it does not have a direct |
| 4 | + * dependency on Python or nanobind. It can therefore be used in codebases |
| 5 | + * where a Python interface is merely an optional component. |
| 6 | + * |
| 7 | + * The file 'docs/intrusive.md' explains the basic rationale of intrusive |
| 8 | + * reference counting, while comments in this file and 'object.cpp' explain |
| 9 | + * technical aspects. |
| 10 | + */ |
| 11 | + |
| 12 | +#include <atomic> |
| 13 | +#pragma once |
| 14 | + |
| 15 | +/* While the implementation does not directly depend on Python, the PyObject* |
| 16 | + type occurs in a few function interfaces (in a fully opaque manner). We must |
| 17 | + therefore forward-declare it. */ |
| 18 | +extern "C" { |
| 19 | + struct _object; |
| 20 | + typedef _object PyObject; |
| 21 | +}; |
| 22 | + |
| 23 | +/** |
| 24 | + * \brief Object base class with intrusive reference counting |
| 25 | + * |
| 26 | + * The Object class provides a convenient foundation of a class hierarchy that |
| 27 | + * will ease lifetime and ownership-related issues whenever Python bindings are |
| 28 | + * involved. |
| 29 | + * |
| 30 | + * Internally, its constructor sets the `m_state` field to `1`, which indicates |
| 31 | + * that the instance is owned by C++. Bits 2..63 of this field are used to |
| 32 | + * store the actual reference count value. The `inc_ref()` and `dec_ref()` |
| 33 | + * functions can be used to increment or decrement this reference count. When |
| 34 | + * `dec_ref()` removes the last reference, the instance will be deallocated |
| 35 | + * using a `delete` expression handled using a polymorphic destructor. |
| 36 | + * |
| 37 | + * When a subclass of `Object` is constructed to Python or returned from C++ to |
| 38 | + * Python, nanobind will invoke `Object::set_self_py()`, which hands ownership |
| 39 | + * over to Python/nanobind. Any remaining references will be moved from the |
| 40 | + * `m_state` field to the Python reference count. In this mode, `inc_ref()` and |
| 41 | + * `dec_ref()` wrap Python reference counting primitives (`Py_INCREF()` / |
| 42 | + * `Py_DECREF()`) which must be made available by calling the function |
| 43 | + * `object_init_py` once during module initialization. Note that the `m_state` |
| 44 | + * field is also used to store a pointer to the `PyObject *`. Python instance |
| 45 | + * pointers are always aligned (i.e. bit 1 is zero), which disambiguates |
| 46 | + * between the two possible configurations. |
| 47 | + * |
| 48 | + * Within C++, the RAII helper class `ref` (defined below) can be used to keep |
| 49 | + * instances alive. This removes the need to call the `inc_ref()` / `dec_ref()` |
| 50 | + * functions explicitly. |
| 51 | + * |
| 52 | + * ``` |
| 53 | + * { |
| 54 | + * ref<MyClass> inst = new MyClass(); |
| 55 | + * inst->my_function(); |
| 56 | + * ... |
| 57 | + * } // end of scope, 'inst' automatically deleted if no longer referenced |
| 58 | + * ``` |
| 59 | + * |
| 60 | + * A separate optional file ``object_py.h`` provides a nanobind type caster |
| 61 | + * to bind functions taking/returning values of type `ref<T>`. |
| 62 | + */ |
| 63 | +class Object { |
| 64 | +public: |
| 65 | + Object() = default; |
| 66 | + |
| 67 | + /* The following move/assignment constructors/operators are no-ops. They |
| 68 | + intentionally do not change the reference count field (m_state) that |
| 69 | + is associated with a fixed address in memory */ |
| 70 | + Object(const Object &) : Object() { } |
| 71 | + Object(Object &&) : Object() { } |
| 72 | + Object &operator=(const Object &) { return *this; } |
| 73 | + Object &operator=(Object &&) { return *this; } |
| 74 | + |
| 75 | + // Polymorphic default destructor |
| 76 | + virtual ~Object() = default; |
| 77 | + |
| 78 | + /// Increase the object's reference count |
| 79 | + void inc_ref() const; |
| 80 | + |
| 81 | + /// Decrease the object's reference count and potentially deallocate it |
| 82 | + void dec_ref() const; |
| 83 | + |
| 84 | + /// Return the Python object associated with this instance (or NULL) |
| 85 | + PyObject *self_py() const; |
| 86 | + |
| 87 | + /// Set the Python object associated with this instance |
| 88 | + void set_self_py(PyObject *self); |
| 89 | + |
| 90 | +private: |
| 91 | + mutable std::atomic<uintptr_t> m_state { 1 }; |
| 92 | +}; |
| 93 | + |
| 94 | +/** |
| 95 | + * \brief Install Python reference counting handlers |
| 96 | + * |
| 97 | + * The `Object` class is designed so that the dependency on Python is |
| 98 | + * *optional*: the code compiles in ordinary C++ projects, in which case the |
| 99 | + * Python reference counting functionality will simply not be used. |
| 100 | + * |
| 101 | + * Python binding code must invoke `object_init_py` and provide functions that |
| 102 | + * can be used to increase/decrease the Python reference count of an instance |
| 103 | + * (i.e., `Py_INCREF` / `Py_DECREF`). |
| 104 | + */ |
| 105 | +void object_init_py(void (*object_inc_ref_py)(PyObject *), |
| 106 | + void (*object_dec_ref_py)(PyObject *)); |
| 107 | + |
| 108 | + |
| 109 | +/** |
| 110 | + * \brief RAII reference counting helper class |
| 111 | + * |
| 112 | + * ``ref`` is a simple RAII wrapper class that stores a pointer to a subclass |
| 113 | + * of ``Object``. It takes care of increasing and decreasing the reference |
| 114 | + * count of the underlying instance. When the last reference goes out of scope, |
| 115 | + * the associated object will be deallocated. |
| 116 | + * |
| 117 | + * A separate optional file ``object_py.h`` provides a nanobind type caster |
| 118 | + * to bind functions taking/returning values of type `ref<T>`. |
| 119 | + */ |
| 120 | +template <typename T> class ref { |
| 121 | +public: |
| 122 | + /// Create a nullptr reference |
| 123 | + ref() : m_ptr(nullptr) { } |
| 124 | + |
| 125 | + /// Construct a reference from a pointer |
| 126 | + ref(T *ptr) : m_ptr(ptr) { |
| 127 | + if (ptr) |
| 128 | + ((Object *) ptr)->inc_ref(); |
| 129 | + } |
| 130 | + |
| 131 | + /// Copy constructor |
| 132 | + ref(const ref &r) : m_ptr(r.m_ptr) { |
| 133 | + if (m_ptr) |
| 134 | + ((Object *) m_ptr)->inc_ref(); |
| 135 | + } |
| 136 | + |
| 137 | + /// Move constructor |
| 138 | + ref(ref &&r) noexcept : m_ptr(r.m_ptr) { |
| 139 | + r.m_ptr = nullptr; |
| 140 | + } |
| 141 | + |
| 142 | + /// Destroy this reference |
| 143 | + ~ref() { |
| 144 | + if (m_ptr) |
| 145 | + ((Object *) m_ptr)->dec_ref(); |
| 146 | + } |
| 147 | + |
| 148 | + /// Move another reference into the current one |
| 149 | + ref &operator=(ref &&r) noexcept { |
| 150 | + if (m_ptr) |
| 151 | + ((Object *) m_ptr)->dec_ref(); |
| 152 | + m_ptr = r.m_ptr; |
| 153 | + r.m_ptr = nullptr; |
| 154 | + return *this; |
| 155 | + } |
| 156 | + |
| 157 | + /// Overwrite this reference with another reference |
| 158 | + ref &operator=(const ref &r) { |
| 159 | + if (r.m_ptr) |
| 160 | + ((Object *) r.m_ptr)->inc_ref(); |
| 161 | + if (m_ptr) |
| 162 | + ((Object *) m_ptr)->dec_ref(); |
| 163 | + m_ptr = r.m_ptr; |
| 164 | + return *this; |
| 165 | + } |
| 166 | + |
| 167 | + /// Overwrite this reference with a pointer to another object |
| 168 | + ref &operator=(T *ptr) { |
| 169 | + if (ptr) |
| 170 | + ((Object *) ptr)->inc_ref(); |
| 171 | + if (m_ptr) |
| 172 | + ((Object *) m_ptr)->dec_ref(); |
| 173 | + m_ptr = ptr; |
| 174 | + return *this; |
| 175 | + } |
| 176 | + |
| 177 | + /// Compare this reference with another reference |
| 178 | + bool operator==(const ref &r) const { return m_ptr == r.m_ptr; } |
| 179 | + |
| 180 | + /// Compare this reference with another reference |
| 181 | + bool operator!=(const ref &r) const { return m_ptr != r.m_ptr; } |
| 182 | + |
| 183 | + /// Compare this reference with a pointer |
| 184 | + bool operator==(const T *ptr) const { return m_ptr == ptr; } |
| 185 | + |
| 186 | + /// Compare this reference with a pointer |
| 187 | + bool operator!=(const T *ptr) const { return m_ptr != ptr; } |
| 188 | + |
| 189 | + /// Access the object referenced by this reference |
| 190 | + T *operator->() { return m_ptr; } |
| 191 | + |
| 192 | + /// Access the object referenced by this reference |
| 193 | + const T *operator->() const { return m_ptr; } |
| 194 | + |
| 195 | + /// Return a C++ reference to the referenced object |
| 196 | + T &operator*() { return *m_ptr; } |
| 197 | + |
| 198 | + /// Return a const C++ reference to the referenced object |
| 199 | + const T &operator*() const { return *m_ptr; } |
| 200 | + |
| 201 | + /// Return a pointer to the referenced object |
| 202 | + explicit operator T *() { return m_ptr; } |
| 203 | + |
| 204 | + /// Return a const pointer to the referenced object |
| 205 | + T *get() { return m_ptr; } |
| 206 | + |
| 207 | + /// Return a pointer to the referenced object |
| 208 | + const T *get() const { return m_ptr; } |
| 209 | + |
| 210 | +private: |
| 211 | + T *m_ptr; |
| 212 | +}; |
0 commit comments