internals.h
Go to the documentation of this file.
1 /*
2  pybind11/detail/internals.h: Internal data structure and related functions
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 "common.h"
13 
14 #if defined(WITH_THREAD) && defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
15 # include "../gil.h"
16 #endif
17 
18 #include "../pytypes.h"
19 
20 #include <exception>
21 
36 #ifndef PYBIND11_INTERNALS_VERSION
37 # if PY_VERSION_HEX >= 0x030C0000
38 // Version bump for Python 3.12+, before first 3.12 beta release.
39 # define PYBIND11_INTERNALS_VERSION 5
40 # else
41 # define PYBIND11_INTERNALS_VERSION 4
42 # endif
43 #endif
44 
45 // This requirement is mainly to reduce the support burden (see PR #4570).
46 static_assert(PY_VERSION_HEX < 0x030C0000 || PYBIND11_INTERNALS_VERSION >= 5,
47  "pybind11 ABI version 5 is the minimum for Python 3.12+");
48 
50 
51 using ExceptionTranslator = void (*)(std::exception_ptr);
52 
54 
55 constexpr const char *internals_function_record_capsule_name = "pybind11_function_record_capsule";
56 
57 // Forward declarations
58 inline PyTypeObject *make_static_property_type();
59 inline PyTypeObject *make_default_metaclass();
60 inline PyObject *make_object_base_type(PyTypeObject *metaclass);
61 
62 // The old Python Thread Local Storage (TLS) API is deprecated in Python 3.7 in favor of the new
63 // Thread Specific Storage (TSS) API.
64 #if PY_VERSION_HEX >= 0x03070000
65 // Avoid unnecessary allocation of `Py_tss_t`, since we cannot use
66 // `Py_LIMITED_API` anyway.
67 # if PYBIND11_INTERNALS_VERSION > 4
68 # define PYBIND11_TLS_KEY_REF Py_tss_t &
69 # if defined(__GNUC__) && !defined(__INTEL_COMPILER)
70 // Clang on macOS warns due to `Py_tss_NEEDS_INIT` not specifying an initializer
71 // for every field.
72 # define PYBIND11_TLS_KEY_INIT(var) \
73  _Pragma("GCC diagnostic push") \
74  _Pragma("GCC diagnostic ignored \"-Wmissing-field-initializers\"") \
75  Py_tss_t var \
76  = Py_tss_NEEDS_INIT; \
77  _Pragma("GCC diagnostic pop")
78 # else
79 # define PYBIND11_TLS_KEY_INIT(var) Py_tss_t var = Py_tss_NEEDS_INIT;
80 # endif
81 # define PYBIND11_TLS_KEY_CREATE(var) (PyThread_tss_create(&(var)) == 0)
82 # define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get(&(key))
83 # define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set(&(key), (value))
84 # define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set(&(key), nullptr)
85 # define PYBIND11_TLS_FREE(key) PyThread_tss_delete(&(key))
86 # else
87 # define PYBIND11_TLS_KEY_REF Py_tss_t *
88 # define PYBIND11_TLS_KEY_INIT(var) Py_tss_t *var = nullptr;
89 # define PYBIND11_TLS_KEY_CREATE(var) \
90  (((var) = PyThread_tss_alloc()) != nullptr && (PyThread_tss_create((var)) == 0))
91 # define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get((key))
92 # define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set((key), (value))
93 # define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set((key), nullptr)
94 # define PYBIND11_TLS_FREE(key) PyThread_tss_free(key)
95 # endif
96 #else
97 // Usually an int but a long on Cygwin64 with Python 3.x
98 # define PYBIND11_TLS_KEY_REF decltype(PyThread_create_key())
99 # define PYBIND11_TLS_KEY_INIT(var) PYBIND11_TLS_KEY_REF var = 0;
100 # define PYBIND11_TLS_KEY_CREATE(var) (((var) = PyThread_create_key()) != -1)
101 # define PYBIND11_TLS_GET_VALUE(key) PyThread_get_key_value((key))
102 # if defined(PYPY_VERSION)
103 // On CPython < 3.4 and on PyPy, `PyThread_set_key_value` strangely does not set
104 // the value if it has already been set. Instead, it must first be deleted and
105 // then set again.
106 inline void tls_replace_value(PYBIND11_TLS_KEY_REF key, void *value) {
107  PyThread_delete_key_value(key);
108  PyThread_set_key_value(key, value);
109 }
110 # define PYBIND11_TLS_DELETE_VALUE(key) PyThread_delete_key_value(key)
111 # define PYBIND11_TLS_REPLACE_VALUE(key, value) \
112  ::pybind11::detail::tls_replace_value((key), (value))
113 # else
114 # define PYBIND11_TLS_DELETE_VALUE(key) PyThread_set_key_value((key), nullptr)
115 # define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_set_key_value((key), (value))
116 # endif
117 # define PYBIND11_TLS_FREE(key) (void) key
118 #endif
119 
120 // Python loads modules by default with dlopen with the RTLD_LOCAL flag; under libc++ and possibly
121 // other STLs, this means `typeid(A)` from one module won't equal `typeid(A)` from another module
122 // even when `A` is the same, non-hidden-visibility type (e.g. from a common include). Under
123 // libstdc++, this doesn't happen: equality and the type_index hash are based on the type name,
124 // which works. If not under a known-good stl, provide our own name-based hash and equality
125 // functions that use the type name.
126 #if (PYBIND11_INTERNALS_VERSION <= 4 && defined(__GLIBCXX__)) \
127  || (PYBIND11_INTERNALS_VERSION >= 5 && !defined(_LIBCPP_VERSION))
128 inline bool same_type(const std::type_info &lhs, const std::type_info &rhs) { return lhs == rhs; }
129 using type_hash = std::hash<std::type_index>;
130 using type_equal_to = std::equal_to<std::type_index>;
131 #else
132 inline bool same_type(const std::type_info &lhs, const std::type_info &rhs) {
133  return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0;
134 }
135 
136 struct type_hash {
137  size_t operator()(const std::type_index &t) const {
138  size_t hash = 5381;
139  const char *ptr = t.name();
140  while (auto c = static_cast<unsigned char>(*ptr++)) {
141  hash = (hash * 33) ^ c;
142  }
143  return hash;
144  }
145 };
146 
148  bool operator()(const std::type_index &lhs, const std::type_index &rhs) const {
149  return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0;
150  }
151 };
152 #endif
153 
154 template <typename value_type>
155 using type_map = std::unordered_map<std::type_index, value_type, type_hash, type_equal_to>;
156 
158  inline size_t operator()(const std::pair<const PyObject *, const char *> &v) const {
159  size_t value = std::hash<const void *>()(v.first);
160  value ^= std::hash<const void *>()(v.second) + 0x9e3779b9 + (value << 6) + (value >> 2);
161  return value;
162  }
163 };
164 
168 struct internals {
169  // std::type_index -> pybind11's type information
171  // PyTypeObject* -> base type_info(s)
172  std::unordered_map<PyTypeObject *, std::vector<type_info *>> registered_types_py;
173  std::unordered_multimap<const void *, instance *> registered_instances; // void * -> instance*
174  std::unordered_set<std::pair<const PyObject *, const char *>, override_hash>
176  type_map<std::vector<bool (*)(PyObject *, void *&)>> direct_conversions;
177  std::unordered_map<const PyObject *, std::vector<PyObject *>> patients;
178  std::forward_list<ExceptionTranslator> registered_exception_translators;
179  std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across
180  // extensions
181 #if PYBIND11_INTERNALS_VERSION == 4
183 #endif
184  std::forward_list<std::string> static_strings; // Stores the std::strings backing
185  // detail::c_str()
186  PyTypeObject *static_property_type;
187  PyTypeObject *default_metaclass;
188  PyObject *instance_base;
189 #if defined(WITH_THREAD)
190  // Unused if PYBIND11_SIMPLE_GIL_MANAGEMENT is defined:
191  PYBIND11_TLS_KEY_INIT(tstate)
192 # if PYBIND11_INTERNALS_VERSION > 4
193  PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
194 # endif // PYBIND11_INTERNALS_VERSION > 4
195  // Unused if PYBIND11_SIMPLE_GIL_MANAGEMENT is defined:
196  PyInterpreterState *istate = nullptr;
197 
198 # if PYBIND11_INTERNALS_VERSION > 4
199  // Note that we have to use a std::string to allocate memory to ensure a unique address
200  // We want unique addresses since we use pointer equality to compare function records
201  std::string function_record_capsule_name = internals_function_record_capsule_name;
202 # endif
203 
204  internals() = default;
205  internals(const internals &other) = delete;
206  internals &operator=(const internals &other) = delete;
207  ~internals() {
208 # if PYBIND11_INTERNALS_VERSION > 4
209  PYBIND11_TLS_FREE(loader_life_support_tls_key);
210 # endif // PYBIND11_INTERNALS_VERSION > 4
211 
212  // This destructor is called *after* Py_Finalize() in finalize_interpreter().
213  // That *SHOULD BE* fine. The following details what happens when PyThread_tss_free is
214  // called. PYBIND11_TLS_FREE is PyThread_tss_free on python 3.7+. On older python, it does
215  // nothing. PyThread_tss_free calls PyThread_tss_delete and PyMem_RawFree.
216  // PyThread_tss_delete just calls TlsFree (on Windows) or pthread_key_delete (on *NIX).
217  // Neither of those have anything to do with CPython internals. PyMem_RawFree *requires*
218  // that the `tstate` be allocated with the CPython allocator.
219  PYBIND11_TLS_FREE(tstate);
220  }
221 #endif
222 };
223 
226 struct type_info {
227  PyTypeObject *type;
228  const std::type_info *cpptype;
230  void *(*operator_new)(size_t);
231  void (*init_instance)(instance *, const void *);
232  void (*dealloc)(value_and_holder &v_h);
233  std::vector<PyObject *(*) (PyObject *, PyTypeObject *)> implicit_conversions;
234  std::vector<std::pair<const std::type_info *, void *(*) (void *)>> implicit_casts;
235  std::vector<bool (*)(PyObject *, void *&)> *direct_conversions;
236  buffer_info *(*get_buffer)(PyObject *, void *) = nullptr;
237  void *get_buffer_data = nullptr;
238  void *(*module_local_load)(PyObject *, const type_info *) = nullptr;
239  /* A simple type never occurs as a (direct or indirect) parent
240  * of a class that makes use of multiple inheritance.
241  * A type can be simple even if it has non-simple ancestors as long as it has no descendants.
242  */
243  bool simple_type : 1;
244  /* True if there is no multiple inheritance in this type's inheritance tree */
246  /* for base vs derived holder_type checks */
247  bool default_holder : 1;
248  /* true if this is a type registered with py::module_local */
249  bool module_local : 1;
250 };
251 
253 #if defined(_MSC_VER) && defined(_DEBUG)
254 # define PYBIND11_BUILD_TYPE "_debug"
255 #else
256 # define PYBIND11_BUILD_TYPE ""
257 #endif
258 
262 #ifndef PYBIND11_COMPILER_TYPE
263 # if defined(_MSC_VER)
264 # define PYBIND11_COMPILER_TYPE "_msvc"
265 # elif defined(__INTEL_COMPILER)
266 # define PYBIND11_COMPILER_TYPE "_icc"
267 # elif defined(__clang__)
268 # define PYBIND11_COMPILER_TYPE "_clang"
269 # elif defined(__PGI)
270 # define PYBIND11_COMPILER_TYPE "_pgi"
271 # elif defined(__MINGW32__)
272 # define PYBIND11_COMPILER_TYPE "_mingw"
273 # elif defined(__CYGWIN__)
274 # define PYBIND11_COMPILER_TYPE "_gcc_cygwin"
275 # elif defined(__GNUC__)
276 # define PYBIND11_COMPILER_TYPE "_gcc"
277 # else
278 # define PYBIND11_COMPILER_TYPE "_unknown"
279 # endif
280 #endif
281 
283 #ifndef PYBIND11_STDLIB
284 # if defined(_LIBCPP_VERSION)
285 # define PYBIND11_STDLIB "_libcpp"
286 # elif defined(__GLIBCXX__) || defined(__GLIBCPP__)
287 # define PYBIND11_STDLIB "_libstdcpp"
288 # else
289 # define PYBIND11_STDLIB ""
290 # endif
291 #endif
292 
294 #ifndef PYBIND11_BUILD_ABI
295 # if defined(__GXX_ABI_VERSION)
296 # define PYBIND11_BUILD_ABI "_cxxabi" PYBIND11_TOSTRING(__GXX_ABI_VERSION)
297 # else
298 # define PYBIND11_BUILD_ABI ""
299 # endif
300 #endif
301 
302 #ifndef PYBIND11_INTERNALS_KIND
303 # if defined(WITH_THREAD)
304 # define PYBIND11_INTERNALS_KIND ""
305 # else
306 # define PYBIND11_INTERNALS_KIND "_without_thread"
307 # endif
308 #endif
309 
310 #define PYBIND11_INTERNALS_ID \
311  "__pybind11_internals_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \
312  PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI \
313  PYBIND11_BUILD_TYPE "__"
314 
315 #define PYBIND11_MODULE_LOCAL_ID \
316  "__pybind11_module_local_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \
317  PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI \
318  PYBIND11_BUILD_TYPE "__"
319 
323  static internals **internals_pp = nullptr;
324  return internals_pp;
325 }
326 
327 // forward decl
328 inline void translate_exception(std::exception_ptr);
329 
330 template <class T,
332 bool handle_nested_exception(const T &exc, const std::exception_ptr &p) {
333  std::exception_ptr nested = exc.nested_ptr();
334  if (nested != nullptr && nested != p) {
335  translate_exception(nested);
336  return true;
337  }
338  return false;
339 }
340 
341 template <class T,
343 bool handle_nested_exception(const T &exc, const std::exception_ptr &p) {
344  if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(exc))) {
345  return handle_nested_exception(*nep, p);
346  }
347  return false;
348 }
349 
350 inline bool raise_err(PyObject *exc_type, const char *msg) {
351  if (PyErr_Occurred()) {
352  raise_from(exc_type, msg);
353  return true;
354  }
355  PyErr_SetString(exc_type, msg);
356  return false;
357 }
358 
359 inline void translate_exception(std::exception_ptr p) {
360  if (!p) {
361  return;
362  }
363  try {
364  std::rethrow_exception(p);
365  } catch (error_already_set &e) {
367  e.restore();
368  return;
369  } catch (const builtin_exception &e) {
370  // Could not use template since it's an abstract class.
371  if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(e))) {
372  handle_nested_exception(*nep, p);
373  }
374  e.set_error();
375  return;
376  } catch (const std::bad_alloc &e) {
378  raise_err(PyExc_MemoryError, e.what());
379  return;
380  } catch (const std::domain_error &e) {
382  raise_err(PyExc_ValueError, e.what());
383  return;
384  } catch (const std::invalid_argument &e) {
386  raise_err(PyExc_ValueError, e.what());
387  return;
388  } catch (const std::length_error &e) {
390  raise_err(PyExc_ValueError, e.what());
391  return;
392  } catch (const std::out_of_range &e) {
394  raise_err(PyExc_IndexError, e.what());
395  return;
396  } catch (const std::range_error &e) {
398  raise_err(PyExc_ValueError, e.what());
399  return;
400  } catch (const std::overflow_error &e) {
402  raise_err(PyExc_OverflowError, e.what());
403  return;
404  } catch (const std::exception &e) {
406  raise_err(PyExc_RuntimeError, e.what());
407  return;
408  } catch (const std::nested_exception &e) {
410  raise_err(PyExc_RuntimeError, "Caught an unknown nested exception!");
411  return;
412  } catch (...) {
413  raise_err(PyExc_RuntimeError, "Caught an unknown exception!");
414  return;
415  }
416 }
417 
418 #if !defined(__GLIBCXX__)
419 inline void translate_local_exception(std::exception_ptr p) {
420  try {
421  if (p) {
422  std::rethrow_exception(p);
423  }
424  } catch (error_already_set &e) {
425  e.restore();
426  return;
427  } catch (const builtin_exception &e) {
428  e.set_error();
429  return;
430  }
431 }
432 #endif
433 
434 inline object get_python_state_dict() {
435  object state_dict;
436 #if PYBIND11_INTERNALS_VERSION <= 4 || PY_VERSION_HEX < 0x03080000 || defined(PYPY_VERSION)
437  state_dict = reinterpret_borrow<object>(PyEval_GetBuiltins());
438 #else
439 # if PY_VERSION_HEX < 0x03090000
440  PyInterpreterState *istate = _PyInterpreterState_Get();
441 # else
442  PyInterpreterState *istate = PyInterpreterState_Get();
443 # endif
444  if (istate) {
445  state_dict = reinterpret_borrow<object>(PyInterpreterState_GetDict(istate));
446  }
447 #endif
448  if (!state_dict) {
449  raise_from(PyExc_SystemError, "pybind11::detail::get_python_state_dict() FAILED");
450  }
451  return state_dict;
452 }
453 
454 inline object get_internals_obj_from_state_dict(handle state_dict) {
455  return reinterpret_borrow<object>(dict_getitemstring(state_dict.ptr(), PYBIND11_INTERNALS_ID));
456 }
457 
459  void *raw_ptr = PyCapsule_GetPointer(obj.ptr(), /*name=*/nullptr);
460  if (raw_ptr == nullptr) {
461  raise_from(PyExc_SystemError, "pybind11::detail::get_internals_pp_from_capsule() FAILED");
462  }
463  return static_cast<internals **>(raw_ptr);
464 }
465 
468  auto **&internals_pp = get_internals_pp();
469  if (internals_pp && *internals_pp) {
470  return **internals_pp;
471  }
472 
473 #if defined(WITH_THREAD)
474 # if defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
475  gil_scoped_acquire gil;
476 # else
477  // Ensure that the GIL is held since we will need to make Python calls.
478  // Cannot use py::gil_scoped_acquire here since that constructor calls get_internals.
479  struct gil_scoped_acquire_local {
480  gil_scoped_acquire_local() : state(PyGILState_Ensure()) {}
481  gil_scoped_acquire_local(const gil_scoped_acquire_local &) = delete;
482  gil_scoped_acquire_local &operator=(const gil_scoped_acquire_local &) = delete;
483  ~gil_scoped_acquire_local() { PyGILState_Release(state); }
484  const PyGILState_STATE state;
485  } gil;
486 # endif
487 #endif
488  error_scope err_scope;
489 
490  dict state_dict = get_python_state_dict();
491  if (object internals_obj = get_internals_obj_from_state_dict(state_dict)) {
492  internals_pp = get_internals_pp_from_capsule(internals_obj);
493  }
494  if (internals_pp && *internals_pp) {
495  // We loaded the internals through `state_dict`, which means that our `error_already_set`
496  // and `builtin_exception` may be different local classes than the ones set up in the
497  // initial exception translator, below, so add another for our local exception classes.
498  //
499  // libstdc++ doesn't require this (types there are identified only by name)
500  // libc++ with CPython doesn't require this (types are explicitly exported)
501  // libc++ with PyPy still need it, awaiting further investigation
502 #if !defined(__GLIBCXX__)
503  (*internals_pp)->registered_exception_translators.push_front(&translate_local_exception);
504 #endif
505  } else {
506  if (!internals_pp) {
507  internals_pp = new internals *();
508  }
509  auto *&internals_ptr = *internals_pp;
510  internals_ptr = new internals();
511 #if defined(WITH_THREAD)
512 
513  PyThreadState *tstate = PyThreadState_Get();
514  // NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
515  if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->tstate)) {
516  pybind11_fail("get_internals: could not successfully initialize the tstate TSS key!");
517  }
518  PYBIND11_TLS_REPLACE_VALUE(internals_ptr->tstate, tstate);
519 
520 # if PYBIND11_INTERNALS_VERSION > 4
521  // NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
522  if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->loader_life_support_tls_key)) {
523  pybind11_fail("get_internals: could not successfully initialize the "
524  "loader_life_support TSS key!");
525  }
526 # endif
527  internals_ptr->istate = tstate->interp;
528 #endif
529  state_dict[PYBIND11_INTERNALS_ID] = capsule(internals_pp);
530  internals_ptr->registered_exception_translators.push_front(&translate_exception);
531  internals_ptr->static_property_type = make_static_property_type();
532  internals_ptr->default_metaclass = make_default_metaclass();
533  internals_ptr->instance_base = make_object_base_type(internals_ptr->default_metaclass);
534  }
535  return **internals_pp;
536 }
537 
538 // the internals struct (above) is shared between all the modules. local_internals are only
539 // for a single module. Any changes made to internals may require an update to
540 // PYBIND11_INTERNALS_VERSION, breaking backwards compatibility. local_internals is, by design,
541 // restricted to a single module. Whether a module has local internals or not should not
542 // impact any other modules, because the only things accessing the local internals is the
543 // module that contains them.
546  std::forward_list<ExceptionTranslator> registered_exception_translators;
547 #if defined(WITH_THREAD) && PYBIND11_INTERNALS_VERSION == 4
548 
549  // For ABI compatibility, we can't store the loader_life_support TLS key in
550  // the `internals` struct directly. Instead, we store it in `shared_data` and
551  // cache a copy in `local_internals`. If we allocated a separate TLS key for
552  // each instance of `local_internals`, we could end up allocating hundreds of
553  // TLS keys if hundreds of different pybind11 modules are loaded (which is a
554  // plausible number).
555  PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
556 
557  // Holds the shared TLS key for the loader_life_support stack.
558  struct shared_loader_life_support_data {
559  PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
560  shared_loader_life_support_data() {
561  // NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
562  if (!PYBIND11_TLS_KEY_CREATE(loader_life_support_tls_key)) {
563  pybind11_fail("local_internals: could not successfully initialize the "
564  "loader_life_support TLS key!");
565  }
566  }
567  // We can't help but leak the TLS key, because Python never unloads extension modules.
568  };
569 
570  local_internals() {
571  auto &internals = get_internals();
572  // Get or create the `loader_life_support_stack_key`.
573  auto &ptr = internals.shared_data["_life_support"];
574  if (!ptr) {
575  ptr = new shared_loader_life_support_data;
576  }
577  loader_life_support_tls_key
578  = static_cast<shared_loader_life_support_data *>(ptr)->loader_life_support_tls_key;
579  }
580 #endif // defined(WITH_THREAD) && PYBIND11_INTERNALS_VERSION == 4
581 };
582 
585  // Current static can be created in the interpreter finalization routine. If the later will be
586  // destroyed in another static variable destructor, creation of this static there will cause
587  // static deinitialization fiasco. In order to avoid it we avoid destruction of the
588  // local_internals static. One can read more about the problem and current solution here:
589  // https://google.github.io/styleguide/cppguide.html#Static_and_Global_Variables
590  static auto *locals = new local_internals();
591  return *locals;
592 }
593 
598 template <typename... Args>
599 const char *c_str(Args &&...args) {
600  auto &strings = get_internals().static_strings;
601  strings.emplace_front(std::forward<Args>(args)...);
602  return strings.front().c_str();
603 }
604 
605 inline const char *get_function_record_capsule_name() {
606 #if PYBIND11_INTERNALS_VERSION > 4
607  return get_internals().function_record_capsule_name.c_str();
608 #else
609  return nullptr;
610 #endif
611 }
612 
613 // Determine whether or not the following capsule contains a pybind11 function record.
614 // Note that we use `internals` to make sure that only ABI compatible records are touched.
615 //
616 // This check is currently used in two places:
617 // - An important optimization in functional.h to avoid overhead in C++ -> Python -> C++
618 // - The sibling feature of cpp_function to allow overloads
619 inline bool is_function_record_capsule(const capsule &cap) {
620  // Pointer equality as we rely on internals() to ensure unique pointers
621  return cap.name() == get_function_record_capsule_name();
622 }
623 
625 
626 PYBIND11_NOINLINE void *get_shared_data(const std::string &name) {
631  auto it = internals.shared_data.find(name);
632  return it != internals.shared_data.end() ? it->second : nullptr;
633 }
634 
636 PYBIND11_NOINLINE void *set_shared_data(const std::string &name, void *data) {
638  return data;
639 }
640 
644 template <typename T>
645 T &get_or_create_shared_data(const std::string &name) {
647  auto it = internals.shared_data.find(name);
648  T *ptr = (T *) (it != internals.shared_data.end() ? it->second : nullptr);
649  if (!ptr) {
650  ptr = new T();
651  internals.shared_data[name] = ptr;
652  }
653  return *ptr;
654 }
655 
handle_nested_exception
bool handle_nested_exception(const T &exc, const std::exception_ptr &p)
Definition: internals.h:332
ExceptionTranslator
void(*)(std::exception_ptr) ExceptionTranslator
Definition: internals.h:51
error_scope
RAII wrapper that temporarily clears any Python error state.
Definition: wrap/pybind11/include/pybind11/detail/common.h:1076
translate_exception
void translate_exception(std::exception_ptr)
Definition: internals.h:359
internals::shared_data
std::unordered_map< std::string, void * > shared_data
Definition: internals.h:179
name
Annotation for function names.
Definition: attr.h:51
internals
Definition: internals.h:168
type_hash::operator()
size_t operator()(const std::type_index &t) const
Definition: internals.h:137
type_info::implicit_conversions
std::vector< PyObject *(*)(PyObject *, PyTypeObject *)> implicit_conversions
Definition: internals.h:233
error_already_set
Definition: pytypes.h:722
type_info
Definition: internals.h:226
e
Array< double, 1, 3 > e(1./3., 0.5, 2.)
type_info::simple_type
bool simple_type
Definition: internals.h:243
type_info::type
PyTypeObject * type
Definition: internals.h:227
internals::registered_types_cpp
type_map< type_info * > registered_types_cpp
Definition: internals.h:170
type_info::implicit_casts
std::vector< std::pair< const std::type_info *, void *(*)(void *)> > implicit_casts
Definition: internals.h:234
c
Scalar Scalar * c
Definition: benchVecAdd.cpp:17
internals::unused_loader_patient_stack_remove_at_v5
std::vector< PyObject * > unused_loader_patient_stack_remove_at_v5
Definition: internals.h:182
make_static_property_type
PyTypeObject * make_static_property_type()
Definition: class.h:64
type_info::get_buffer_data
void * get_buffer_data
Definition: internals.h:237
type_info::default_holder
bool default_holder
Definition: internals.h:247
local_internals::registered_exception_translators
std::forward_list< ExceptionTranslator > registered_exception_translators
Definition: internals.h:546
type_info::type_size
size_t type_size
Definition: internals.h:229
PYBIND11_NAMESPACE_END
#define PYBIND11_NAMESPACE_END(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:80
capsule
Definition: pytypes.h:1909
PYBIND11_NOINLINE
#define PYBIND11_NOINLINE
Definition: wrap/pybind11/include/pybind11/detail/common.h:186
value_and_holder
Definition: type_caster_base.h:253
T
Eigen::Triplet< double > T
Definition: Tutorial_sparse_example.cpp:6
detail
Definition: testSerializationNonlinear.cpp:70
internals::static_property_type
PyTypeObject * static_property_type
Definition: internals.h:186
make_object_base_type
PyObject * make_object_base_type(PyTypeObject *metaclass)
Definition: class.h:481
dict_getitemstring
PyObject * dict_getitemstring(PyObject *v, const char *key)
Definition: pytypes.h:943
get_internals_pp_from_capsule
internals ** get_internals_pp_from_capsule(handle obj)
Definition: internals.h:458
get_internals
PYBIND11_NOINLINE internals & get_internals()
Return a reference to the current internals data.
Definition: internals.h:467
PYBIND11_NAMESPACE_BEGIN
#define PYBIND11_NAMESPACE_BEGIN(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:76
type_info::dealloc
void(* dealloc)(value_and_holder &v_h)
Definition: internals.h:232
type_hash
Definition: internals.h:136
internals::registered_exception_translators
std::forward_list< ExceptionTranslator > registered_exception_translators
Definition: internals.h:178
type_info::cpptype
const std::type_info * cpptype
Definition: internals.h:228
type_info::type_align
size_t type_align
Definition: internals.h:229
hash
ssize_t hash(handle obj)
Definition: pytypes.h:917
name
static char name[]
Definition: rgamma.c:72
internals::registered_instances
std::unordered_multimap< const void *, instance * > registered_instances
Definition: internals.h:173
internals::instance_base
PyObject * instance_base
Definition: internals.h:188
get_or_create_shared_data
T & get_or_create_shared_data(const std::string &name)
Definition: internals.h:645
instance
The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
Definition: wrap/pybind11/include/pybind11/detail/common.h:569
same_type
bool same_type(const std::type_info &lhs, const std::type_info &rhs)
Definition: internals.h:132
PYBIND11_TLS_REPLACE_VALUE
#define PYBIND11_TLS_REPLACE_VALUE(key, value)
Definition: internals.h:115
dict
Definition: pytypes.h:2065
raise_from
void raise_from(PyObject *type, const char *message)
Definition: pytypes.h:780
get_function_record_capsule_name
const char * get_function_record_capsule_name()
Definition: internals.h:605
data
int data[]
Definition: Map_placement_new.cpp:1
handle
Definition: pytypes.h:217
PYBIND11_TLS_KEY_REF
#define PYBIND11_TLS_KEY_REF
Definition: internals.h:98
raise_err
bool raise_err(PyObject *exc_type, const char *msg)
Definition: internals.h:350
internals::inactive_override_cache
std::unordered_set< std::pair< const PyObject *, const char * >, override_hash > inactive_override_cache
Definition: internals.h:175
PYBIND11_INTERNALS_ID
#define PYBIND11_INTERNALS_ID
Definition: internals.h:310
set_shared_data
PYBIND11_NOINLINE void * set_shared_data(const std::string &name, void *data)
Set the shared data that can be later recovered by get_shared_data().
Definition: internals.h:636
metaclass
Annotation which requests that a special metaclass is created for a type.
Definition: attr.h:85
local_internals::registered_types_cpp
type_map< type_info * > registered_types_cpp
Definition: internals.h:545
local_internals
Definition: internals.h:544
override_hash
Definition: internals.h:157
internals_function_record_capsule_name
constexpr const char * internals_function_record_capsule_name
Definition: internals.h:55
PYBIND11_TLS_KEY_CREATE
#define PYBIND11_TLS_KEY_CREATE(var)
Definition: internals.h:100
PYBIND11_NAMESPACE
Definition: test_custom_type_casters.cpp:24
Eigen::Triplet
A small structure to hold a non zero as a triplet (i,j,value).
Definition: SparseUtil.h:162
common.h
gil_scoped_acquire
Definition: gil.h:215
pybind11_fail
PyExc_RuntimeError PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
Definition: wrap/pybind11/include/pybind11/detail/common.h:1013
size_t
std::size_t size_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:476
translate_local_exception
void translate_local_exception(std::exception_ptr p)
Definition: internals.h:419
type_info::direct_conversions
std::vector< bool(*)(PyObject *, void *&)> * direct_conversions
Definition: internals.h:235
is_function_record_capsule
bool is_function_record_capsule(const capsule &cap)
Definition: internals.h:619
internals::static_strings
std::forward_list< std::string > static_strings
Definition: internals.h:184
key
const gtsam::Symbol key('X', 0)
type_equal_to
Definition: internals.h:147
get_python_state_dict
object get_python_state_dict()
Definition: internals.h:434
internals::direct_conversions
type_map< std::vector< bool(*)(PyObject *, void *&)> > direct_conversions
Definition: internals.h:176
handle::ptr
PyObject * ptr() const
Return the underlying PyObject * pointer.
Definition: pytypes.h:241
internals::patients
std::unordered_map< const PyObject *, std::vector< PyObject * > > patients
Definition: internals.h:177
get_internals_obj_from_state_dict
object get_internals_obj_from_state_dict(handle state_dict)
Definition: internals.h:454
std
Definition: BFloat16.h:88
args
Definition: pytypes.h:2163
buffer_info
Information record describing a Python buffer object.
Definition: buffer_info.h:46
p
float * p
Definition: Tutorial_Map_using.cpp:9
c_str
const char * c_str(Args &&...args)
Definition: internals.h:599
get_local_internals
local_internals & get_local_internals()
Works like get_internals, but for things which are locally registered.
Definition: internals.h:584
type_info::module_local
bool module_local
Definition: internals.h:249
v
Array< int, Dynamic, 1 > v
Definition: Array_initializer_list_vector_cxx11.cpp:1
type_info::init_instance
void(* init_instance)(instance *, const void *)
Definition: internals.h:231
PYBIND11_TLS_KEY_INIT
#define PYBIND11_TLS_KEY_INIT(var)
Definition: internals.h:99
override_hash::operator()
size_t operator()(const std::pair< const PyObject *, const char * > &v) const
Definition: internals.h:158
internals::default_metaclass
PyTypeObject * default_metaclass
Definition: internals.h:187
type_equal_to::operator()
bool operator()(const std::type_index &lhs, const std::type_index &rhs) const
Definition: internals.h:148
internals::registered_types_py
std::unordered_map< PyTypeObject *, std::vector< type_info * > > registered_types_py
Definition: internals.h:172
get_internals_pp
internals **& get_internals_pp()
Definition: internals.h:322
PYBIND11_TLS_FREE
#define PYBIND11_TLS_FREE(key)
Definition: internals.h:117
get_shared_data
PYBIND11_NOINLINE void * get_shared_data(const std::string &name)
Definition: internals.h:629
builtin_exception
C++ bindings of builtin Python exceptions.
Definition: wrap/pybind11/include/pybind11/detail/common.h:985
type_info::simple_ancestors
bool simple_ancestors
Definition: internals.h:245
align_3::t
Point2 t(10, 10)
enable_if_t
typename std::enable_if< B, T >::type enable_if_t
from cpp_future import (convenient aliases from C++14/17)
Definition: wrap/pybind11/include/pybind11/detail/common.h:640
make_default_metaclass
PyTypeObject * make_default_metaclass()
Definition: class.h:251
test_callbacks.value
value
Definition: test_callbacks.py:158
pybind_wrapper_test_script.other
other
Definition: pybind_wrapper_test_script.py:42
type_map
std::unordered_map< std::type_index, value_type, type_hash, type_equal_to > type_map
Definition: internals.h:155
make_changelog.state
state
Definition: make_changelog.py:28
pybind11.msg
msg
Definition: wrap/pybind11/pybind11/__init__.py:4
type_info::holder_size_in_ptrs
size_t holder_size_in_ptrs
Definition: internals.h:229


gtsam
Author(s):
autogenerated on Sat Jun 1 2024 03:01:44