Warning, file /sdk/codevis/thirdparty/pybind11/detail/class.h was not indexed or was modified since last indexation (in which case cross-reference links may be missing, inaccurate or erroneous).

0001 /*
0002     pybind11/detail/class.h: Python C API implementation details for py::class_
0003 
0004     Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
0005 
0006     All rights reserved. Use of this source code is governed by a
0007     BSD-style license that can be found in the LICENSE file.
0008 */
0009 
0010 #pragma once
0011 
0012 #include "../attr.h"
0013 #include "../options.h"
0014 
0015 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
0016 PYBIND11_NAMESPACE_BEGIN(detail)
0017 
0018 #if PY_VERSION_HEX >= 0x03030000 && !defined(PYPY_VERSION)
0019 #  define PYBIND11_BUILTIN_QUALNAME
0020 #  define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
0021 #else
0022 // In pre-3.3 Python, we still set __qualname__ so that we can produce reliable function type
0023 // signatures; in 3.3+ this macro expands to nothing:
0024 #  define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj) setattr((PyObject *) obj, "__qualname__", nameobj)
0025 #endif
0026 
0027 inline std::string get_fully_qualified_tp_name(PyTypeObject *type) {
0028 #if !defined(PYPY_VERSION)
0029     return type->tp_name;
0030 #else
0031     auto module_name = handle((PyObject *) type).attr("__module__").cast<std::string>();
0032     if (module_name == PYBIND11_BUILTINS_MODULE)
0033         return type->tp_name;
0034     else
0035         return std::move(module_name) + "." + type->tp_name;
0036 #endif
0037 }
0038 
0039 inline PyTypeObject *type_incref(PyTypeObject *type) {
0040     Py_INCREF(type);
0041     return type;
0042 }
0043 
0044 #if !defined(PYPY_VERSION)
0045 
0046 /// `pybind11_static_property.__get__()`: Always pass the class instead of the instance.
0047 extern "C" inline PyObject *pybind11_static_get(PyObject *self, PyObject * /*ob*/, PyObject *cls) {
0048     return PyProperty_Type.tp_descr_get(self, cls, cls);
0049 }
0050 
0051 /// `pybind11_static_property.__set__()`: Just like the above `__get__()`.
0052 extern "C" inline int pybind11_static_set(PyObject *self, PyObject *obj, PyObject *value) {
0053     PyObject *cls = PyType_Check(obj) ? obj : (PyObject *) Py_TYPE(obj);
0054     return PyProperty_Type.tp_descr_set(self, cls, value);
0055 }
0056 
0057 /** A `static_property` is the same as a `property` but the `__get__()` and `__set__()`
0058     methods are modified to always use the object type instead of a concrete instance.
0059     Return value: New reference. */
0060 inline PyTypeObject *make_static_property_type() {
0061     constexpr auto *name = "pybind11_static_property";
0062     auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
0063 
0064     /* Danger zone: from now (and until PyType_Ready), make sure to
0065        issue no Python C API calls which could potentially invoke the
0066        garbage collector (the GC will call type_traverse(), which will in
0067        turn find the newly constructed type in an invalid state) */
0068     auto heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
0069     if (!heap_type)
0070         pybind11_fail("make_static_property_type(): error allocating type!");
0071 
0072     heap_type->ht_name = name_obj.inc_ref().ptr();
0073 #ifdef PYBIND11_BUILTIN_QUALNAME
0074     heap_type->ht_qualname = name_obj.inc_ref().ptr();
0075 #endif
0076 
0077     auto type = &heap_type->ht_type;
0078     type->tp_name = name;
0079     type->tp_base = type_incref(&PyProperty_Type);
0080     type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
0081     type->tp_descr_get = pybind11_static_get;
0082     type->tp_descr_set = pybind11_static_set;
0083 
0084     if (PyType_Ready(type) < 0)
0085         pybind11_fail("make_static_property_type(): failure in PyType_Ready()!");
0086 
0087     setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
0088     PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
0089 
0090     return type;
0091 }
0092 
0093 #else // PYPY
0094 
0095 /** PyPy has some issues with the above C API, so we evaluate Python code instead.
0096     This function will only be called once so performance isn't really a concern.
0097     Return value: New reference. */
0098 inline PyTypeObject *make_static_property_type() {
0099     auto d = dict();
0100     PyObject *result = PyRun_String(R"(\
0101         class pybind11_static_property(property):
0102             def __get__(self, obj, cls):
0103                 return property.__get__(self, cls, cls)
0104 
0105             def __set__(self, obj, value):
0106                 cls = obj if isinstance(obj, type) else type(obj)
0107                 property.__set__(self, cls, value)
0108         )", Py_file_input, d.ptr(), d.ptr()
0109     );
0110     if (result == nullptr)
0111         throw error_already_set();
0112     Py_DECREF(result);
0113     return (PyTypeObject *) d["pybind11_static_property"].cast<object>().release().ptr();
0114 }
0115 
0116 #endif // PYPY
0117 
0118 /** Types with static properties need to handle `Type.static_prop = x` in a specific way.
0119     By default, Python replaces the `static_property` itself, but for wrapped C++ types
0120     we need to call `static_property.__set__()` in order to propagate the new value to
0121     the underlying C++ data structure. */
0122 extern "C" inline int pybind11_meta_setattro(PyObject* obj, PyObject* name, PyObject* value) {
0123     // Use `_PyType_Lookup()` instead of `PyObject_GetAttr()` in order to get the raw
0124     // descriptor (`property`) instead of calling `tp_descr_get` (`property.__get__()`).
0125     PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
0126 
0127     // The following assignment combinations are possible:
0128     //   1. `Type.static_prop = value`             --> descr_set: `Type.static_prop.__set__(value)`
0129     //   2. `Type.static_prop = other_static_prop` --> setattro:  replace existing `static_prop`
0130     //   3. `Type.regular_attribute = value`       --> setattro:  regular attribute assignment
0131     const auto static_prop = (PyObject *) get_internals().static_property_type;
0132     const auto call_descr_set = (descr != nullptr) && (value != nullptr)
0133                                 && (PyObject_IsInstance(descr, static_prop) != 0)
0134                                 && (PyObject_IsInstance(value, static_prop) == 0);
0135     if (call_descr_set) {
0136         // Call `static_property.__set__()` instead of replacing the `static_property`.
0137 #if !defined(PYPY_VERSION)
0138         return Py_TYPE(descr)->tp_descr_set(descr, obj, value);
0139 #else
0140         if (PyObject *result = PyObject_CallMethod(descr, "__set__", "OO", obj, value)) {
0141             Py_DECREF(result);
0142             return 0;
0143         } else {
0144             return -1;
0145         }
0146 #endif
0147     } else {
0148         // Replace existing attribute.
0149         return PyType_Type.tp_setattro(obj, name, value);
0150     }
0151 }
0152 
0153 #if PY_MAJOR_VERSION >= 3
0154 /**
0155  * Python 3's PyInstanceMethod_Type hides itself via its tp_descr_get, which prevents aliasing
0156  * methods via cls.attr("m2") = cls.attr("m1"): instead the tp_descr_get returns a plain function,
0157  * when called on a class, or a PyMethod, when called on an instance.  Override that behaviour here
0158  * to do a special case bypass for PyInstanceMethod_Types.
0159  */
0160 extern "C" inline PyObject *pybind11_meta_getattro(PyObject *obj, PyObject *name) {
0161     PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
0162     if (descr && PyInstanceMethod_Check(descr)) {
0163         Py_INCREF(descr);
0164         return descr;
0165     }
0166     return PyType_Type.tp_getattro(obj, name);
0167 }
0168 #endif
0169 
0170 /// metaclass `__call__` function that is used to create all pybind11 objects.
0171 extern "C" inline PyObject *pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs) {
0172 
0173     // use the default metaclass call to create/initialize the object
0174     PyObject *self = PyType_Type.tp_call(type, args, kwargs);
0175     if (self == nullptr) {
0176         return nullptr;
0177     }
0178 
0179     // This must be a pybind11 instance
0180     auto instance = reinterpret_cast<detail::instance *>(self);
0181 
0182     // Ensure that the base __init__ function(s) were called
0183     for (const auto &vh : values_and_holders(instance)) {
0184         if (!vh.holder_constructed()) {
0185             PyErr_Format(PyExc_TypeError, "%.200s.__init__() must be called when overriding __init__",
0186                          get_fully_qualified_tp_name(vh.type->type).c_str());
0187             Py_DECREF(self);
0188             return nullptr;
0189         }
0190     }
0191 
0192     return self;
0193 }
0194 
0195 /// Cleanup the type-info for a pybind11-registered type.
0196 extern "C" inline void pybind11_meta_dealloc(PyObject *obj) {
0197     auto *type = (PyTypeObject *) obj;
0198     auto &internals = get_internals();
0199 
0200     // A pybind11-registered type will:
0201     // 1) be found in internals.registered_types_py
0202     // 2) have exactly one associated `detail::type_info`
0203     auto found_type = internals.registered_types_py.find(type);
0204     if (found_type != internals.registered_types_py.end() &&
0205         found_type->second.size() == 1 &&
0206         found_type->second[0]->type == type) {
0207 
0208         auto *tinfo = found_type->second[0];
0209         auto tindex = std::type_index(*tinfo->cpptype);
0210         internals.direct_conversions.erase(tindex);
0211 
0212         if (tinfo->module_local)
0213             get_local_internals().registered_types_cpp.erase(tindex);
0214         else
0215             internals.registered_types_cpp.erase(tindex);
0216         internals.registered_types_py.erase(tinfo->type);
0217 
0218         // Actually just `std::erase_if`, but that's only available in C++20
0219         auto &cache = internals.inactive_override_cache;
0220         for (auto it = cache.begin(), last = cache.end(); it != last; ) {
0221             if (it->first == (PyObject *) tinfo->type)
0222                 it = cache.erase(it);
0223             else
0224                 ++it;
0225         }
0226 
0227         delete tinfo;
0228     }
0229 
0230     PyType_Type.tp_dealloc(obj);
0231 }
0232 
0233 /** This metaclass is assigned by default to all pybind11 types and is required in order
0234     for static properties to function correctly. Users may override this using `py::metaclass`.
0235     Return value: New reference. */
0236 inline PyTypeObject* make_default_metaclass() {
0237     constexpr auto *name = "pybind11_type";
0238     auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
0239 
0240     /* Danger zone: from now (and until PyType_Ready), make sure to
0241        issue no Python C API calls which could potentially invoke the
0242        garbage collector (the GC will call type_traverse(), which will in
0243        turn find the newly constructed type in an invalid state) */
0244     auto heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
0245     if (!heap_type)
0246         pybind11_fail("make_default_metaclass(): error allocating metaclass!");
0247 
0248     heap_type->ht_name = name_obj.inc_ref().ptr();
0249 #ifdef PYBIND11_BUILTIN_QUALNAME
0250     heap_type->ht_qualname = name_obj.inc_ref().ptr();
0251 #endif
0252 
0253     auto type = &heap_type->ht_type;
0254     type->tp_name = name;
0255     type->tp_base = type_incref(&PyType_Type);
0256     type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
0257 
0258     type->tp_call = pybind11_meta_call;
0259 
0260     type->tp_setattro = pybind11_meta_setattro;
0261 #if PY_MAJOR_VERSION >= 3
0262     type->tp_getattro = pybind11_meta_getattro;
0263 #endif
0264 
0265     type->tp_dealloc = pybind11_meta_dealloc;
0266 
0267     if (PyType_Ready(type) < 0)
0268         pybind11_fail("make_default_metaclass(): failure in PyType_Ready()!");
0269 
0270     setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
0271     PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
0272 
0273     return type;
0274 }
0275 
0276 /// For multiple inheritance types we need to recursively register/deregister base pointers for any
0277 /// base classes with pointers that are difference from the instance value pointer so that we can
0278 /// correctly recognize an offset base class pointer. This calls a function with any offset base ptrs.
0279 inline void traverse_offset_bases(void *valueptr, const detail::type_info *tinfo, instance *self,
0280         bool (*f)(void * /*parentptr*/, instance * /*self*/)) {
0281     for (handle h : reinterpret_borrow<tuple>(tinfo->type->tp_bases)) {
0282         if (auto parent_tinfo = get_type_info((PyTypeObject *) h.ptr())) {
0283             for (auto &c : parent_tinfo->implicit_casts) {
0284                 if (c.first == tinfo->cpptype) {
0285                     auto *parentptr = c.second(valueptr);
0286                     if (parentptr != valueptr)
0287                         f(parentptr, self);
0288                     traverse_offset_bases(parentptr, parent_tinfo, self, f);
0289                     break;
0290                 }
0291             }
0292         }
0293     }
0294 }
0295 
0296 inline bool register_instance_impl(void *ptr, instance *self) {
0297     get_internals().registered_instances.emplace(ptr, self);
0298     return true; // unused, but gives the same signature as the deregister func
0299 }
0300 inline bool deregister_instance_impl(void *ptr, instance *self) {
0301     auto &registered_instances = get_internals().registered_instances;
0302     auto range = registered_instances.equal_range(ptr);
0303     for (auto it = range.first; it != range.second; ++it) {
0304         if (self == it->second) {
0305             registered_instances.erase(it);
0306             return true;
0307         }
0308     }
0309     return false;
0310 }
0311 
0312 inline void register_instance(instance *self, void *valptr, const type_info *tinfo) {
0313     register_instance_impl(valptr, self);
0314     if (!tinfo->simple_ancestors)
0315         traverse_offset_bases(valptr, tinfo, self, register_instance_impl);
0316 }
0317 
0318 inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) {
0319     bool ret = deregister_instance_impl(valptr, self);
0320     if (!tinfo->simple_ancestors)
0321         traverse_offset_bases(valptr, tinfo, self, deregister_instance_impl);
0322     return ret;
0323 }
0324 
0325 /// Instance creation function for all pybind11 types. It allocates the internal instance layout for
0326 /// holding C++ objects and holders.  Allocation is done lazily (the first time the instance is cast
0327 /// to a reference or pointer), and initialization is done by an `__init__` function.
0328 inline PyObject *make_new_instance(PyTypeObject *type) {
0329 #if defined(PYPY_VERSION)
0330     // PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first inherited
0331     // object is a plain Python type (i.e. not derived from an extension type).  Fix it.
0332     ssize_t instance_size = static_cast<ssize_t>(sizeof(instance));
0333     if (type->tp_basicsize < instance_size) {
0334         type->tp_basicsize = instance_size;
0335     }
0336 #endif
0337     PyObject *self = type->tp_alloc(type, 0);
0338     auto inst = reinterpret_cast<instance *>(self);
0339     // Allocate the value/holder internals:
0340     inst->allocate_layout();
0341 
0342     return self;
0343 }
0344 
0345 /// Instance creation function for all pybind11 types. It only allocates space for the
0346 /// C++ object, but doesn't call the constructor -- an `__init__` function must do that.
0347 extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
0348     return make_new_instance(type);
0349 }
0350 
0351 /// An `__init__` function constructs the C++ object. Users should provide at least one
0352 /// of these using `py::init` or directly with `.def(__init__, ...)`. Otherwise, the
0353 /// following default function will be used which simply throws an exception.
0354 extern "C" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
0355     PyTypeObject *type = Py_TYPE(self);
0356     std::string msg = get_fully_qualified_tp_name(type) + ": No constructor defined!";
0357     PyErr_SetString(PyExc_TypeError, msg.c_str());
0358     return -1;
0359 }
0360 
0361 inline void add_patient(PyObject *nurse, PyObject *patient) {
0362     auto &internals = get_internals();
0363     auto instance = reinterpret_cast<detail::instance *>(nurse);
0364     instance->has_patients = true;
0365     Py_INCREF(patient);
0366     internals.patients[nurse].push_back(patient);
0367 }
0368 
0369 inline void clear_patients(PyObject *self) {
0370     auto instance = reinterpret_cast<detail::instance *>(self);
0371     auto &internals = get_internals();
0372     auto pos = internals.patients.find(self);
0373     assert(pos != internals.patients.end());
0374     // Clearing the patients can cause more Python code to run, which
0375     // can invalidate the iterator. Extract the vector of patients
0376     // from the unordered_map first.
0377     auto patients = std::move(pos->second);
0378     internals.patients.erase(pos);
0379     instance->has_patients = false;
0380     for (PyObject *&patient : patients)
0381         Py_CLEAR(patient);
0382 }
0383 
0384 /// Clears all internal data from the instance and removes it from registered instances in
0385 /// preparation for deallocation.
0386 inline void clear_instance(PyObject *self) {
0387     auto instance = reinterpret_cast<detail::instance *>(self);
0388 
0389     // Deallocate any values/holders, if present:
0390     for (auto &v_h : values_and_holders(instance)) {
0391         if (v_h) {
0392 
0393             // We have to deregister before we call dealloc because, for virtual MI types, we still
0394             // need to be able to get the parent pointers.
0395             if (v_h.instance_registered() && !deregister_instance(instance, v_h.value_ptr(), v_h.type))
0396                 pybind11_fail("pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
0397 
0398             if (instance->owned || v_h.holder_constructed())
0399                 v_h.type->dealloc(v_h);
0400         }
0401     }
0402     // Deallocate the value/holder layout internals:
0403     instance->deallocate_layout();
0404 
0405     if (instance->weakrefs)
0406         PyObject_ClearWeakRefs(self);
0407 
0408     PyObject **dict_ptr = _PyObject_GetDictPtr(self);
0409     if (dict_ptr)
0410         Py_CLEAR(*dict_ptr);
0411 
0412     if (instance->has_patients)
0413         clear_patients(self);
0414 }
0415 
0416 /// Instance destructor function for all pybind11 types. It calls `type_info.dealloc`
0417 /// to destroy the C++ object itself, while the rest is Python bookkeeping.
0418 extern "C" inline void pybind11_object_dealloc(PyObject *self) {
0419     clear_instance(self);
0420 
0421     auto type = Py_TYPE(self);
0422     type->tp_free(self);
0423 
0424 #if PY_VERSION_HEX < 0x03080000
0425     // `type->tp_dealloc != pybind11_object_dealloc` means that we're being called
0426     // as part of a derived type's dealloc, in which case we're not allowed to decref
0427     // the type here. For cross-module compatibility, we shouldn't compare directly
0428     // with `pybind11_object_dealloc`, but with the common one stashed in internals.
0429     auto pybind11_object_type = (PyTypeObject *) get_internals().instance_base;
0430     if (type->tp_dealloc == pybind11_object_type->tp_dealloc)
0431         Py_DECREF(type);
0432 #else
0433     // This was not needed before Python 3.8 (Python issue 35810)
0434     // https://github.com/pybind/pybind11/issues/1946
0435     Py_DECREF(type);
0436 #endif
0437 }
0438 
0439 /** Create the type which can be used as a common base for all classes.  This is
0440     needed in order to satisfy Python's requirements for multiple inheritance.
0441     Return value: New reference. */
0442 inline PyObject *make_object_base_type(PyTypeObject *metaclass) {
0443     constexpr auto *name = "pybind11_object";
0444     auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
0445 
0446     /* Danger zone: from now (and until PyType_Ready), make sure to
0447        issue no Python C API calls which could potentially invoke the
0448        garbage collector (the GC will call type_traverse(), which will in
0449        turn find the newly constructed type in an invalid state) */
0450     auto heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
0451     if (!heap_type)
0452         pybind11_fail("make_object_base_type(): error allocating type!");
0453 
0454     heap_type->ht_name = name_obj.inc_ref().ptr();
0455 #ifdef PYBIND11_BUILTIN_QUALNAME
0456     heap_type->ht_qualname = name_obj.inc_ref().ptr();
0457 #endif
0458 
0459     auto type = &heap_type->ht_type;
0460     type->tp_name = name;
0461     type->tp_base = type_incref(&PyBaseObject_Type);
0462     type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
0463     type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
0464 
0465     type->tp_new = pybind11_object_new;
0466     type->tp_init = pybind11_object_init;
0467     type->tp_dealloc = pybind11_object_dealloc;
0468 
0469     /* Support weak references (needed for the keep_alive feature) */
0470     type->tp_weaklistoffset = offsetof(instance, weakrefs);
0471 
0472     if (PyType_Ready(type) < 0)
0473         pybind11_fail("PyType_Ready failed in make_object_base_type():" + error_string());
0474 
0475     setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
0476     PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
0477 
0478     assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
0479     return (PyObject *) heap_type;
0480 }
0481 
0482 /// dynamic_attr: Support for `d = instance.__dict__`.
0483 extern "C" inline PyObject *pybind11_get_dict(PyObject *self, void *) {
0484     PyObject *&dict = *_PyObject_GetDictPtr(self);
0485     if (!dict)
0486         dict = PyDict_New();
0487     Py_XINCREF(dict);
0488     return dict;
0489 }
0490 
0491 /// dynamic_attr: Support for `instance.__dict__ = dict()`.
0492 extern "C" inline int pybind11_set_dict(PyObject *self, PyObject *new_dict, void *) {
0493     if (!PyDict_Check(new_dict)) {
0494         PyErr_Format(PyExc_TypeError, "__dict__ must be set to a dictionary, not a '%.200s'",
0495                      get_fully_qualified_tp_name(Py_TYPE(new_dict)).c_str());
0496         return -1;
0497     }
0498     PyObject *&dict = *_PyObject_GetDictPtr(self);
0499     Py_INCREF(new_dict);
0500     Py_CLEAR(dict);
0501     dict = new_dict;
0502     return 0;
0503 }
0504 
0505 /// dynamic_attr: Allow the garbage collector to traverse the internal instance `__dict__`.
0506 extern "C" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) {
0507     PyObject *&dict = *_PyObject_GetDictPtr(self);
0508     Py_VISIT(dict);
0509     return 0;
0510 }
0511 
0512 /// dynamic_attr: Allow the GC to clear the dictionary.
0513 extern "C" inline int pybind11_clear(PyObject *self) {
0514     PyObject *&dict = *_PyObject_GetDictPtr(self);
0515     Py_CLEAR(dict);
0516     return 0;
0517 }
0518 
0519 /// Give instances of this type a `__dict__` and opt into garbage collection.
0520 inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
0521     auto type = &heap_type->ht_type;
0522     type->tp_flags |= Py_TPFLAGS_HAVE_GC;
0523     type->tp_dictoffset = type->tp_basicsize; // place dict at the end
0524     type->tp_basicsize += (ssize_t)sizeof(PyObject *); // and allocate enough space for it
0525     type->tp_traverse = pybind11_traverse;
0526     type->tp_clear = pybind11_clear;
0527 
0528     static PyGetSetDef getset[] = {
0529         {const_cast<char*>("__dict__"), pybind11_get_dict, pybind11_set_dict, nullptr, nullptr},
0530         {nullptr, nullptr, nullptr, nullptr, nullptr}
0531     };
0532     type->tp_getset = getset;
0533 }
0534 
0535 /// buffer_protocol: Fill in the view as specified by flags.
0536 extern "C" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags) {
0537     // Look for a `get_buffer` implementation in this type's info or any bases (following MRO).
0538     type_info *tinfo = nullptr;
0539     for (auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {
0540         tinfo = get_type_info((PyTypeObject *) type.ptr());
0541         if (tinfo && tinfo->get_buffer)
0542             break;
0543     }
0544     if (view == nullptr || !tinfo || !tinfo->get_buffer) {
0545         if (view)
0546             view->obj = nullptr;
0547         PyErr_SetString(PyExc_BufferError, "pybind11_getbuffer(): Internal error");
0548         return -1;
0549     }
0550     std::memset(view, 0, sizeof(Py_buffer));
0551     buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
0552     if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->readonly) {
0553         delete info;
0554         // view->obj = nullptr;  // Was just memset to 0, so not necessary
0555         PyErr_SetString(PyExc_BufferError, "Writable buffer requested for readonly storage");
0556         return -1;
0557     }
0558     view->obj = obj;
0559     view->ndim = 1;
0560     view->internal = info;
0561     view->buf = info->ptr;
0562     view->itemsize = info->itemsize;
0563     view->len = view->itemsize;
0564     for (auto s : info->shape)
0565         view->len *= s;
0566     view->readonly = static_cast<int>(info->readonly);
0567     if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
0568         view->format = const_cast<char *>(info->format.c_str());
0569     if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
0570         view->ndim = (int) info->ndim;
0571         view->strides = &info->strides[0];
0572         view->shape = &info->shape[0];
0573     }
0574     Py_INCREF(view->obj);
0575     return 0;
0576 }
0577 
0578 /// buffer_protocol: Release the resources of the buffer.
0579 extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {
0580     delete (buffer_info *) view->internal;
0581 }
0582 
0583 /// Give this type a buffer interface.
0584 inline void enable_buffer_protocol(PyHeapTypeObject *heap_type) {
0585     heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer;
0586 #if PY_MAJOR_VERSION < 3
0587     heap_type->ht_type.tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
0588 #endif
0589 
0590     heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer;
0591     heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer;
0592 }
0593 
0594 /** Create a brand new Python type according to the `type_record` specification.
0595     Return value: New reference. */
0596 inline PyObject* make_new_python_type(const type_record &rec) {
0597     auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.name));
0598 
0599     auto qualname = name;
0600     if (rec.scope && !PyModule_Check(rec.scope.ptr()) && hasattr(rec.scope, "__qualname__")) {
0601 #if PY_MAJOR_VERSION >= 3
0602         qualname = reinterpret_steal<object>(
0603             PyUnicode_FromFormat("%U.%U", rec.scope.attr("__qualname__").ptr(), name.ptr()));
0604 #else
0605         qualname = str(rec.scope.attr("__qualname__").cast<std::string>() + "." + rec.name);
0606 #endif
0607     }
0608 
0609     object module_;
0610     if (rec.scope) {
0611         if (hasattr(rec.scope, "__module__"))
0612             module_ = rec.scope.attr("__module__");
0613         else if (hasattr(rec.scope, "__name__"))
0614             module_ = rec.scope.attr("__name__");
0615     }
0616 
0617     auto full_name = c_str(
0618 #if !defined(PYPY_VERSION)
0619         module_ ? str(module_).cast<std::string>() + "." + rec.name :
0620 #endif
0621         rec.name);
0622 
0623     char *tp_doc = nullptr;
0624     if (rec.doc && options::show_user_defined_docstrings()) {
0625         /* Allocate memory for docstring (using PyObject_MALLOC, since
0626            Python will free this later on) */
0627         size_t size = std::strlen(rec.doc) + 1;
0628         tp_doc = (char *) PyObject_MALLOC(size);
0629         std::memcpy((void *) tp_doc, rec.doc, size);
0630     }
0631 
0632     auto &internals = get_internals();
0633     auto bases = tuple(rec.bases);
0634     auto base = (bases.empty()) ? internals.instance_base
0635                                     : bases[0].ptr();
0636 
0637     /* Danger zone: from now (and until PyType_Ready), make sure to
0638        issue no Python C API calls which could potentially invoke the
0639        garbage collector (the GC will call type_traverse(), which will in
0640        turn find the newly constructed type in an invalid state) */
0641     auto metaclass = rec.metaclass.ptr() ? (PyTypeObject *) rec.metaclass.ptr()
0642                                          : internals.default_metaclass;
0643 
0644     auto heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
0645     if (!heap_type)
0646         pybind11_fail(std::string(rec.name) + ": Unable to create type object!");
0647 
0648     heap_type->ht_name = name.release().ptr();
0649 #ifdef PYBIND11_BUILTIN_QUALNAME
0650     heap_type->ht_qualname = qualname.inc_ref().ptr();
0651 #endif
0652 
0653     auto type = &heap_type->ht_type;
0654     type->tp_name = full_name;
0655     type->tp_doc = tp_doc;
0656     type->tp_base = type_incref((PyTypeObject *)base);
0657     type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
0658     if (!bases.empty())
0659         type->tp_bases = bases.release().ptr();
0660 
0661     /* Don't inherit base __init__ */
0662     type->tp_init = pybind11_object_init;
0663 
0664     /* Supported protocols */
0665     type->tp_as_number = &heap_type->as_number;
0666     type->tp_as_sequence = &heap_type->as_sequence;
0667     type->tp_as_mapping = &heap_type->as_mapping;
0668 #if PY_VERSION_HEX >= 0x03050000
0669     type->tp_as_async = &heap_type->as_async;
0670 #endif
0671 
0672     /* Flags */
0673     type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
0674 #if PY_MAJOR_VERSION < 3
0675     type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
0676 #endif
0677     if (!rec.is_final)
0678         type->tp_flags |= Py_TPFLAGS_BASETYPE;
0679 
0680     if (rec.dynamic_attr)
0681         enable_dynamic_attributes(heap_type);
0682 
0683     if (rec.buffer_protocol)
0684         enable_buffer_protocol(heap_type);
0685 
0686     if (rec.custom_type_setup_callback)
0687         rec.custom_type_setup_callback(heap_type);
0688 
0689     if (PyType_Ready(type) < 0)
0690         pybind11_fail(std::string(rec.name) + ": PyType_Ready failed (" + error_string() + ")!");
0691 
0692     assert(!rec.dynamic_attr || PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
0693 
0694     /* Register type with the parent scope */
0695     if (rec.scope)
0696         setattr(rec.scope, rec.name, (PyObject *) type);
0697     else
0698         Py_INCREF(type); // Keep it alive forever (reference leak)
0699 
0700     if (module_) // Needed by pydoc
0701         setattr((PyObject *) type, "__module__", module_);
0702 
0703     PYBIND11_SET_OLDPY_QUALNAME(type, qualname);
0704 
0705     return (PyObject *) type;
0706 }
0707 
0708 PYBIND11_NAMESPACE_END(detail)
0709 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)