class.h 24 KB

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