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