class_support.h 23 KB

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