class.h 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. /*
  2. pybind11/detail/class.h: Python C API implementation details for py::class_
  3. Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
  4. All rights reserved. Use of this source code is governed by a
  5. BSD-style license that can be found in the LICENSE file.
  6. */
  7. #pragma once
  8. #include "../attr.h"
  9. #include "../options.h"
  10. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  11. PYBIND11_NAMESPACE_BEGIN(detail)
  12. #if !defined(PYPY_VERSION)
  13. # define PYBIND11_BUILTIN_QUALNAME
  14. # define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
  15. #else
  16. // In PyPy, we still set __qualname__ so that we can produce reliable function type
  17. // signatures; in CPython this macro expands to nothing:
  18. # define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj) \
  19. setattr((PyObject *) obj, "__qualname__", nameobj)
  20. #endif
  21. inline std::string get_fully_qualified_tp_name(PyTypeObject *type) {
  22. #if !defined(PYPY_VERSION)
  23. return type->tp_name;
  24. #else
  25. auto module_name = handle((PyObject *) type).attr("__module__").cast<std::string>();
  26. if (module_name == PYBIND11_BUILTINS_MODULE)
  27. return type->tp_name;
  28. else
  29. return std::move(module_name) + "." + type->tp_name;
  30. #endif
  31. }
  32. inline PyTypeObject *type_incref(PyTypeObject *type) {
  33. Py_INCREF(type);
  34. return type;
  35. }
  36. #if !defined(PYPY_VERSION)
  37. /// `pybind11_static_property.__get__()`: Always pass the class instead of the instance.
  38. extern "C" inline PyObject *pybind11_static_get(PyObject *self, PyObject * /*ob*/, PyObject *cls) {
  39. return PyProperty_Type.tp_descr_get(self, cls, cls);
  40. }
  41. /// `pybind11_static_property.__set__()`: Just like the above `__get__()`.
  42. extern "C" inline int pybind11_static_set(PyObject *self, PyObject *obj, PyObject *value) {
  43. PyObject *cls = PyType_Check(obj) ? obj : (PyObject *) Py_TYPE(obj);
  44. return PyProperty_Type.tp_descr_set(self, cls, value);
  45. }
  46. // Forward declaration to use in `make_static_property_type()`
  47. inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type);
  48. /** A `static_property` is the same as a `property` but the `__get__()` and `__set__()`
  49. methods are modified to always use the object type instead of a concrete instance.
  50. Return value: New reference. */
  51. inline PyTypeObject *make_static_property_type() {
  52. constexpr auto *name = "pybind11_static_property";
  53. auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
  54. /* Danger zone: from now (and until PyType_Ready), make sure to
  55. issue no Python C API calls which could potentially invoke the
  56. garbage collector (the GC will call type_traverse(), which will in
  57. turn find the newly constructed type in an invalid state) */
  58. auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
  59. if (!heap_type) {
  60. pybind11_fail("make_static_property_type(): error allocating type!");
  61. }
  62. heap_type->ht_name = name_obj.inc_ref().ptr();
  63. # ifdef PYBIND11_BUILTIN_QUALNAME
  64. heap_type->ht_qualname = name_obj.inc_ref().ptr();
  65. # endif
  66. auto *type = &heap_type->ht_type;
  67. type->tp_name = name;
  68. type->tp_base = type_incref(&PyProperty_Type);
  69. type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
  70. type->tp_descr_get = pybind11_static_get;
  71. type->tp_descr_set = pybind11_static_set;
  72. if (PyType_Ready(type) < 0) {
  73. pybind11_fail("make_static_property_type(): failure in PyType_Ready()!");
  74. }
  75. # if PY_VERSION_HEX >= 0x030C0000
  76. // PRE 3.12 FEATURE FREEZE. PLEASE REVIEW AFTER FREEZE.
  77. // Since Python-3.12 property-derived types are required to
  78. // have dynamic attributes (to set `__doc__`)
  79. enable_dynamic_attributes(heap_type);
  80. # endif
  81. setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
  82. PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
  83. return type;
  84. }
  85. #else // PYPY
  86. /** PyPy has some issues with the above C API, so we evaluate Python code instead.
  87. This function will only be called once so performance isn't really a concern.
  88. Return value: New reference. */
  89. inline PyTypeObject *make_static_property_type() {
  90. auto d = dict();
  91. PyObject *result = PyRun_String(R"(\
  92. class pybind11_static_property(property):
  93. def __get__(self, obj, cls):
  94. return property.__get__(self, cls, cls)
  95. def __set__(self, obj, value):
  96. cls = obj if isinstance(obj, type) else type(obj)
  97. property.__set__(self, cls, value)
  98. )",
  99. Py_file_input,
  100. d.ptr(),
  101. d.ptr());
  102. if (result == nullptr)
  103. throw error_already_set();
  104. Py_DECREF(result);
  105. return (PyTypeObject *) d["pybind11_static_property"].cast<object>().release().ptr();
  106. }
  107. #endif // PYPY
  108. /** Types with static properties need to handle `Type.static_prop = x` in a specific way.
  109. By default, Python replaces the `static_property` itself, but for wrapped C++ types
  110. we need to call `static_property.__set__()` in order to propagate the new value to
  111. the underlying C++ data structure. */
  112. extern "C" inline int pybind11_meta_setattro(PyObject *obj, PyObject *name, PyObject *value) {
  113. // Use `_PyType_Lookup()` instead of `PyObject_GetAttr()` in order to get the raw
  114. // descriptor (`property`) instead of calling `tp_descr_get` (`property.__get__()`).
  115. PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
  116. // The following assignment combinations are possible:
  117. // 1. `Type.static_prop = value` --> descr_set: `Type.static_prop.__set__(value)`
  118. // 2. `Type.static_prop = other_static_prop` --> setattro: replace existing `static_prop`
  119. // 3. `Type.regular_attribute = value` --> setattro: regular attribute assignment
  120. auto *const static_prop = (PyObject *) get_internals().static_property_type;
  121. const auto call_descr_set = (descr != nullptr) && (value != nullptr)
  122. && (PyObject_IsInstance(descr, static_prop) != 0)
  123. && (PyObject_IsInstance(value, static_prop) == 0);
  124. if (call_descr_set) {
  125. // Call `static_property.__set__()` instead of replacing the `static_property`.
  126. #if !defined(PYPY_VERSION)
  127. return Py_TYPE(descr)->tp_descr_set(descr, obj, value);
  128. #else
  129. if (PyObject *result = PyObject_CallMethod(descr, "__set__", "OO", obj, value)) {
  130. Py_DECREF(result);
  131. return 0;
  132. } else {
  133. return -1;
  134. }
  135. #endif
  136. } else {
  137. // Replace existing attribute.
  138. return PyType_Type.tp_setattro(obj, name, value);
  139. }
  140. }
  141. /**
  142. * Python 3's PyInstanceMethod_Type hides itself via its tp_descr_get, which prevents aliasing
  143. * methods via cls.attr("m2") = cls.attr("m1"): instead the tp_descr_get returns a plain function,
  144. * when called on a class, or a PyMethod, when called on an instance. Override that behaviour here
  145. * to do a special case bypass for PyInstanceMethod_Types.
  146. */
  147. extern "C" inline PyObject *pybind11_meta_getattro(PyObject *obj, PyObject *name) {
  148. PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
  149. if (descr && PyInstanceMethod_Check(descr)) {
  150. Py_INCREF(descr);
  151. return descr;
  152. }
  153. return PyType_Type.tp_getattro(obj, name);
  154. }
  155. /// metaclass `__call__` function that is used to create all pybind11 objects.
  156. extern "C" inline PyObject *pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs) {
  157. // use the default metaclass call to create/initialize the object
  158. PyObject *self = PyType_Type.tp_call(type, args, kwargs);
  159. if (self == nullptr) {
  160. return nullptr;
  161. }
  162. // This must be a pybind11 instance
  163. auto *instance = reinterpret_cast<detail::instance *>(self);
  164. // Ensure that the base __init__ function(s) were called
  165. for (const auto &vh : values_and_holders(instance)) {
  166. if (!vh.holder_constructed()) {
  167. PyErr_Format(PyExc_TypeError,
  168. "%.200s.__init__() must be called when overriding __init__",
  169. get_fully_qualified_tp_name(vh.type->type).c_str());
  170. Py_DECREF(self);
  171. return nullptr;
  172. }
  173. }
  174. return self;
  175. }
  176. /// Cleanup the type-info for a pybind11-registered type.
  177. extern "C" inline void pybind11_meta_dealloc(PyObject *obj) {
  178. auto *type = (PyTypeObject *) obj;
  179. auto &internals = get_internals();
  180. // A pybind11-registered type will:
  181. // 1) be found in internals.registered_types_py
  182. // 2) have exactly one associated `detail::type_info`
  183. auto found_type = internals.registered_types_py.find(type);
  184. if (found_type != internals.registered_types_py.end() && found_type->second.size() == 1
  185. && found_type->second[0]->type == type) {
  186. auto *tinfo = found_type->second[0];
  187. auto tindex = std::type_index(*tinfo->cpptype);
  188. internals.direct_conversions.erase(tindex);
  189. if (tinfo->module_local) {
  190. get_local_internals().registered_types_cpp.erase(tindex);
  191. } else {
  192. internals.registered_types_cpp.erase(tindex);
  193. }
  194. internals.registered_types_py.erase(tinfo->type);
  195. // Actually just `std::erase_if`, but that's only available in C++20
  196. auto &cache = internals.inactive_override_cache;
  197. for (auto it = cache.begin(), last = cache.end(); it != last;) {
  198. if (it->first == (PyObject *) tinfo->type) {
  199. it = cache.erase(it);
  200. } else {
  201. ++it;
  202. }
  203. }
  204. delete tinfo;
  205. }
  206. PyType_Type.tp_dealloc(obj);
  207. }
  208. /** This metaclass is assigned by default to all pybind11 types and is required in order
  209. for static properties to function correctly. Users may override this using `py::metaclass`.
  210. Return value: New reference. */
  211. inline PyTypeObject *make_default_metaclass() {
  212. constexpr auto *name = "pybind11_type";
  213. auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
  214. /* Danger zone: from now (and until PyType_Ready), make sure to
  215. issue no Python C API calls which could potentially invoke the
  216. garbage collector (the GC will call type_traverse(), which will in
  217. turn find the newly constructed type in an invalid state) */
  218. auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
  219. if (!heap_type) {
  220. pybind11_fail("make_default_metaclass(): error allocating metaclass!");
  221. }
  222. heap_type->ht_name = name_obj.inc_ref().ptr();
  223. #ifdef PYBIND11_BUILTIN_QUALNAME
  224. heap_type->ht_qualname = name_obj.inc_ref().ptr();
  225. #endif
  226. auto *type = &heap_type->ht_type;
  227. type->tp_name = name;
  228. type->tp_base = type_incref(&PyType_Type);
  229. type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
  230. type->tp_call = pybind11_meta_call;
  231. type->tp_setattro = pybind11_meta_setattro;
  232. type->tp_getattro = pybind11_meta_getattro;
  233. type->tp_dealloc = pybind11_meta_dealloc;
  234. if (PyType_Ready(type) < 0) {
  235. pybind11_fail("make_default_metaclass(): failure in PyType_Ready()!");
  236. }
  237. setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
  238. PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
  239. return type;
  240. }
  241. /// For multiple inheritance types we need to recursively register/deregister base pointers for any
  242. /// base classes with pointers that are difference from the instance value pointer so that we can
  243. /// correctly recognize an offset base class pointer. This calls a function with any offset base
  244. /// ptrs.
  245. inline void traverse_offset_bases(void *valueptr,
  246. const detail::type_info *tinfo,
  247. instance *self,
  248. bool (*f)(void * /*parentptr*/, instance * /*self*/)) {
  249. for (handle h : reinterpret_borrow<tuple>(tinfo->type->tp_bases)) {
  250. if (auto *parent_tinfo = get_type_info((PyTypeObject *) h.ptr())) {
  251. for (auto &c : parent_tinfo->implicit_casts) {
  252. if (c.first == tinfo->cpptype) {
  253. auto *parentptr = c.second(valueptr);
  254. if (parentptr != valueptr) {
  255. f(parentptr, self);
  256. }
  257. traverse_offset_bases(parentptr, parent_tinfo, self, f);
  258. break;
  259. }
  260. }
  261. }
  262. }
  263. }
  264. inline bool register_instance_impl(void *ptr, instance *self) {
  265. get_internals().registered_instances.emplace(ptr, self);
  266. return true; // unused, but gives the same signature as the deregister func
  267. }
  268. inline bool deregister_instance_impl(void *ptr, instance *self) {
  269. auto &registered_instances = get_internals().registered_instances;
  270. auto range = registered_instances.equal_range(ptr);
  271. for (auto it = range.first; it != range.second; ++it) {
  272. if (self == it->second) {
  273. registered_instances.erase(it);
  274. return true;
  275. }
  276. }
  277. return false;
  278. }
  279. inline void register_instance(instance *self, void *valptr, const type_info *tinfo) {
  280. register_instance_impl(valptr, self);
  281. if (!tinfo->simple_ancestors) {
  282. traverse_offset_bases(valptr, tinfo, self, register_instance_impl);
  283. }
  284. }
  285. inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) {
  286. bool ret = deregister_instance_impl(valptr, self);
  287. if (!tinfo->simple_ancestors) {
  288. traverse_offset_bases(valptr, tinfo, self, deregister_instance_impl);
  289. }
  290. return ret;
  291. }
  292. /// Instance creation function for all pybind11 types. It allocates the internal instance layout
  293. /// for holding C++ objects and holders. Allocation is done lazily (the first time the instance is
  294. /// cast to a reference or pointer), and initialization is done by an `__init__` function.
  295. inline PyObject *make_new_instance(PyTypeObject *type) {
  296. #if defined(PYPY_VERSION)
  297. // PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first
  298. // inherited object is a plain Python type (i.e. not derived from an extension type). Fix it.
  299. ssize_t instance_size = static_cast<ssize_t>(sizeof(instance));
  300. if (type->tp_basicsize < instance_size) {
  301. type->tp_basicsize = instance_size;
  302. }
  303. #endif
  304. PyObject *self = type->tp_alloc(type, 0);
  305. auto *inst = reinterpret_cast<instance *>(self);
  306. // Allocate the value/holder internals:
  307. inst->allocate_layout();
  308. return self;
  309. }
  310. /// Instance creation function for all pybind11 types. It only allocates space for the
  311. /// C++ object, but doesn't call the constructor -- an `__init__` function must do that.
  312. extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
  313. return make_new_instance(type);
  314. }
  315. /// An `__init__` function constructs the C++ object. Users should provide at least one
  316. /// of these using `py::init` or directly with `.def(__init__, ...)`. Otherwise, the
  317. /// following default function will be used which simply throws an exception.
  318. extern "C" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
  319. PyTypeObject *type = Py_TYPE(self);
  320. std::string msg = get_fully_qualified_tp_name(type) + ": No constructor defined!";
  321. PyErr_SetString(PyExc_TypeError, msg.c_str());
  322. return -1;
  323. }
  324. inline void add_patient(PyObject *nurse, PyObject *patient) {
  325. auto &internals = get_internals();
  326. auto *instance = reinterpret_cast<detail::instance *>(nurse);
  327. instance->has_patients = true;
  328. Py_INCREF(patient);
  329. internals.patients[nurse].push_back(patient);
  330. }
  331. inline void clear_patients(PyObject *self) {
  332. auto *instance = reinterpret_cast<detail::instance *>(self);
  333. auto &internals = get_internals();
  334. auto pos = internals.patients.find(self);
  335. assert(pos != internals.patients.end());
  336. // Clearing the patients can cause more Python code to run, which
  337. // can invalidate the iterator. Extract the vector of patients
  338. // from the unordered_map first.
  339. auto patients = std::move(pos->second);
  340. internals.patients.erase(pos);
  341. instance->has_patients = false;
  342. for (PyObject *&patient : patients) {
  343. Py_CLEAR(patient);
  344. }
  345. }
  346. /// Clears all internal data from the instance and removes it from registered instances in
  347. /// preparation for deallocation.
  348. inline void clear_instance(PyObject *self) {
  349. auto *instance = reinterpret_cast<detail::instance *>(self);
  350. // Deallocate any values/holders, if present:
  351. for (auto &v_h : values_and_holders(instance)) {
  352. if (v_h) {
  353. // We have to deregister before we call dealloc because, for virtual MI types, we still
  354. // need to be able to get the parent pointers.
  355. if (v_h.instance_registered()
  356. && !deregister_instance(instance, v_h.value_ptr(), v_h.type)) {
  357. pybind11_fail(
  358. "pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
  359. }
  360. if (instance->owned || v_h.holder_constructed()) {
  361. v_h.type->dealloc(v_h);
  362. }
  363. }
  364. }
  365. // Deallocate the value/holder layout internals:
  366. instance->deallocate_layout();
  367. if (instance->weakrefs) {
  368. PyObject_ClearWeakRefs(self);
  369. }
  370. PyObject **dict_ptr = _PyObject_GetDictPtr(self);
  371. if (dict_ptr) {
  372. Py_CLEAR(*dict_ptr);
  373. }
  374. if (instance->has_patients) {
  375. clear_patients(self);
  376. }
  377. }
  378. /// Instance destructor function for all pybind11 types. It calls `type_info.dealloc`
  379. /// to destroy the C++ object itself, while the rest is Python bookkeeping.
  380. extern "C" inline void pybind11_object_dealloc(PyObject *self) {
  381. clear_instance(self);
  382. auto *type = Py_TYPE(self);
  383. type->tp_free(self);
  384. #if PY_VERSION_HEX < 0x03080000
  385. // `type->tp_dealloc != pybind11_object_dealloc` means that we're being called
  386. // as part of a derived type's dealloc, in which case we're not allowed to decref
  387. // the type here. For cross-module compatibility, we shouldn't compare directly
  388. // with `pybind11_object_dealloc`, but with the common one stashed in internals.
  389. auto pybind11_object_type = (PyTypeObject *) get_internals().instance_base;
  390. if (type->tp_dealloc == pybind11_object_type->tp_dealloc)
  391. Py_DECREF(type);
  392. #else
  393. // This was not needed before Python 3.8 (Python issue 35810)
  394. // https://github.com/pybind/pybind11/issues/1946
  395. Py_DECREF(type);
  396. #endif
  397. }
  398. std::string error_string();
  399. /** Create the type which can be used as a common base for all classes. This is
  400. needed in order to satisfy Python's requirements for multiple inheritance.
  401. Return value: New reference. */
  402. inline PyObject *make_object_base_type(PyTypeObject *metaclass) {
  403. constexpr auto *name = "pybind11_object";
  404. auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
  405. /* Danger zone: from now (and until PyType_Ready), make sure to
  406. issue no Python C API calls which could potentially invoke the
  407. garbage collector (the GC will call type_traverse(), which will in
  408. turn find the newly constructed type in an invalid state) */
  409. auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
  410. if (!heap_type) {
  411. pybind11_fail("make_object_base_type(): error allocating type!");
  412. }
  413. heap_type->ht_name = name_obj.inc_ref().ptr();
  414. #ifdef PYBIND11_BUILTIN_QUALNAME
  415. heap_type->ht_qualname = name_obj.inc_ref().ptr();
  416. #endif
  417. auto *type = &heap_type->ht_type;
  418. type->tp_name = name;
  419. type->tp_base = type_incref(&PyBaseObject_Type);
  420. type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
  421. type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
  422. type->tp_new = pybind11_object_new;
  423. type->tp_init = pybind11_object_init;
  424. type->tp_dealloc = pybind11_object_dealloc;
  425. /* Support weak references (needed for the keep_alive feature) */
  426. type->tp_weaklistoffset = offsetof(instance, weakrefs);
  427. if (PyType_Ready(type) < 0) {
  428. pybind11_fail("PyType_Ready failed in make_object_base_type(): " + error_string());
  429. }
  430. setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
  431. PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
  432. assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
  433. return (PyObject *) heap_type;
  434. }
  435. /// dynamic_attr: Allow the garbage collector to traverse the internal instance `__dict__`.
  436. extern "C" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) {
  437. PyObject *&dict = *_PyObject_GetDictPtr(self);
  438. Py_VISIT(dict);
  439. // https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_traverse
  440. #if PY_VERSION_HEX >= 0x03090000
  441. Py_VISIT(Py_TYPE(self));
  442. #endif
  443. return 0;
  444. }
  445. /// dynamic_attr: Allow the GC to clear the dictionary.
  446. extern "C" inline int pybind11_clear(PyObject *self) {
  447. PyObject *&dict = *_PyObject_GetDictPtr(self);
  448. Py_CLEAR(dict);
  449. return 0;
  450. }
  451. /// Give instances of this type a `__dict__` and opt into garbage collection.
  452. inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
  453. auto *type = &heap_type->ht_type;
  454. type->tp_flags |= Py_TPFLAGS_HAVE_GC;
  455. #if PY_VERSION_HEX < 0x030B0000
  456. type->tp_dictoffset = type->tp_basicsize; // place dict at the end
  457. type->tp_basicsize += (ssize_t) sizeof(PyObject *); // and allocate enough space for it
  458. #else
  459. type->tp_flags |= Py_TPFLAGS_MANAGED_DICT;
  460. #endif
  461. type->tp_traverse = pybind11_traverse;
  462. type->tp_clear = pybind11_clear;
  463. static PyGetSetDef getset[] = {{
  464. #if PY_VERSION_HEX < 0x03070000
  465. const_cast<char *>("__dict__"),
  466. #else
  467. "__dict__",
  468. #endif
  469. PyObject_GenericGetDict,
  470. PyObject_GenericSetDict,
  471. nullptr,
  472. nullptr},
  473. {nullptr, nullptr, nullptr, nullptr, nullptr}};
  474. type->tp_getset = getset;
  475. }
  476. /// buffer_protocol: Fill in the view as specified by flags.
  477. extern "C" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags) {
  478. // Look for a `get_buffer` implementation in this type's info or any bases (following MRO).
  479. type_info *tinfo = nullptr;
  480. for (auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {
  481. tinfo = get_type_info((PyTypeObject *) type.ptr());
  482. if (tinfo && tinfo->get_buffer) {
  483. break;
  484. }
  485. }
  486. if (view == nullptr || !tinfo || !tinfo->get_buffer) {
  487. if (view) {
  488. view->obj = nullptr;
  489. }
  490. PyErr_SetString(PyExc_BufferError, "pybind11_getbuffer(): Internal error");
  491. return -1;
  492. }
  493. std::memset(view, 0, sizeof(Py_buffer));
  494. buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
  495. if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->readonly) {
  496. delete info;
  497. // view->obj = nullptr; // Was just memset to 0, so not necessary
  498. PyErr_SetString(PyExc_BufferError, "Writable buffer requested for readonly storage");
  499. return -1;
  500. }
  501. view->obj = obj;
  502. view->ndim = 1;
  503. view->internal = info;
  504. view->buf = info->ptr;
  505. view->itemsize = info->itemsize;
  506. view->len = view->itemsize;
  507. for (auto s : info->shape) {
  508. view->len *= s;
  509. }
  510. view->readonly = static_cast<int>(info->readonly);
  511. if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
  512. view->format = const_cast<char *>(info->format.c_str());
  513. }
  514. if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
  515. view->ndim = (int) info->ndim;
  516. view->strides = info->strides.data();
  517. view->shape = info->shape.data();
  518. }
  519. Py_INCREF(view->obj);
  520. return 0;
  521. }
  522. /// buffer_protocol: Release the resources of the buffer.
  523. extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {
  524. delete (buffer_info *) view->internal;
  525. }
  526. /// Give this type a buffer interface.
  527. inline void enable_buffer_protocol(PyHeapTypeObject *heap_type) {
  528. heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer;
  529. heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer;
  530. heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer;
  531. }
  532. /** Create a brand new Python type according to the `type_record` specification.
  533. Return value: New reference. */
  534. inline PyObject *make_new_python_type(const type_record &rec) {
  535. auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.name));
  536. auto qualname = name;
  537. if (rec.scope && !PyModule_Check(rec.scope.ptr()) && hasattr(rec.scope, "__qualname__")) {
  538. qualname = reinterpret_steal<object>(
  539. PyUnicode_FromFormat("%U.%U", rec.scope.attr("__qualname__").ptr(), name.ptr()));
  540. }
  541. object module_;
  542. if (rec.scope) {
  543. if (hasattr(rec.scope, "__module__")) {
  544. module_ = rec.scope.attr("__module__");
  545. } else if (hasattr(rec.scope, "__name__")) {
  546. module_ = rec.scope.attr("__name__");
  547. }
  548. }
  549. const auto *full_name = c_str(
  550. #if !defined(PYPY_VERSION)
  551. module_ ? str(module_).cast<std::string>() + "." + rec.name :
  552. #endif
  553. rec.name);
  554. char *tp_doc = nullptr;
  555. if (rec.doc && options::show_user_defined_docstrings()) {
  556. /* Allocate memory for docstring (using PyObject_MALLOC, since
  557. Python will free this later on) */
  558. size_t size = std::strlen(rec.doc) + 1;
  559. tp_doc = (char *) PyObject_MALLOC(size);
  560. std::memcpy((void *) tp_doc, rec.doc, size);
  561. }
  562. auto &internals = get_internals();
  563. auto bases = tuple(rec.bases);
  564. auto *base = (bases.empty()) ? internals.instance_base : bases[0].ptr();
  565. /* Danger zone: from now (and until PyType_Ready), make sure to
  566. issue no Python C API calls which could potentially invoke the
  567. garbage collector (the GC will call type_traverse(), which will in
  568. turn find the newly constructed type in an invalid state) */
  569. auto *metaclass
  570. = rec.metaclass.ptr() ? (PyTypeObject *) rec.metaclass.ptr() : internals.default_metaclass;
  571. auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
  572. if (!heap_type) {
  573. pybind11_fail(std::string(rec.name) + ": Unable to create type object!");
  574. }
  575. heap_type->ht_name = name.release().ptr();
  576. #ifdef PYBIND11_BUILTIN_QUALNAME
  577. heap_type->ht_qualname = qualname.inc_ref().ptr();
  578. #endif
  579. auto *type = &heap_type->ht_type;
  580. type->tp_name = full_name;
  581. type->tp_doc = tp_doc;
  582. type->tp_base = type_incref((PyTypeObject *) base);
  583. type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
  584. if (!bases.empty()) {
  585. type->tp_bases = bases.release().ptr();
  586. }
  587. /* Don't inherit base __init__ */
  588. type->tp_init = pybind11_object_init;
  589. /* Supported protocols */
  590. type->tp_as_number = &heap_type->as_number;
  591. type->tp_as_sequence = &heap_type->as_sequence;
  592. type->tp_as_mapping = &heap_type->as_mapping;
  593. type->tp_as_async = &heap_type->as_async;
  594. /* Flags */
  595. type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
  596. if (!rec.is_final) {
  597. type->tp_flags |= Py_TPFLAGS_BASETYPE;
  598. }
  599. if (rec.dynamic_attr) {
  600. enable_dynamic_attributes(heap_type);
  601. }
  602. if (rec.buffer_protocol) {
  603. enable_buffer_protocol(heap_type);
  604. }
  605. if (rec.custom_type_setup_callback) {
  606. rec.custom_type_setup_callback(heap_type);
  607. }
  608. if (PyType_Ready(type) < 0) {
  609. pybind11_fail(std::string(rec.name) + ": PyType_Ready failed: " + error_string());
  610. }
  611. assert(!rec.dynamic_attr || PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
  612. /* Register type with the parent scope */
  613. if (rec.scope) {
  614. setattr(rec.scope, rec.name, (PyObject *) type);
  615. } else {
  616. Py_INCREF(type); // Keep it alive forever (reference leak)
  617. }
  618. if (module_) { // Needed by pydoc
  619. setattr((PyObject *) type, "__module__", module_);
  620. }
  621. PYBIND11_SET_OLDPY_QUALNAME(type, qualname);
  622. return (PyObject *) type;
  623. }
  624. PYBIND11_NAMESPACE_END(detail)
  625. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)