Warning, file /sdk/codevis/thirdparty/pybind11/detail/internals.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/internals.h: Internal data structure and related functions 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 "../pytypes.h" 0013 #include <exception> 0014 0015 /// Tracks the `internals` and `type_info` ABI version independent of the main library version. 0016 /// 0017 /// Some portions of the code use an ABI that is conditional depending on this 0018 /// version number. That allows ABI-breaking changes to be "pre-implemented". 0019 /// Once the default version number is incremented, the conditional logic that 0020 /// no longer applies can be removed. Additionally, users that need not 0021 /// maintain ABI compatibility can increase the version number in order to take 0022 /// advantage of any functionality/efficiency improvements that depend on the 0023 /// newer ABI. 0024 /// 0025 /// WARNING: If you choose to manually increase the ABI version, note that 0026 /// pybind11 may not be tested as thoroughly with a non-default ABI version, and 0027 /// further ABI-incompatible changes may be made before the ABI is officially 0028 /// changed to the new version. 0029 #ifndef PYBIND11_INTERNALS_VERSION 0030 # define PYBIND11_INTERNALS_VERSION 4 0031 #endif 0032 0033 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 0034 0035 using ExceptionTranslator = void (*)(std::exception_ptr); 0036 0037 PYBIND11_NAMESPACE_BEGIN(detail) 0038 0039 // Forward declarations 0040 inline PyTypeObject *make_static_property_type(); 0041 inline PyTypeObject *make_default_metaclass(); 0042 inline PyObject *make_object_base_type(PyTypeObject *metaclass); 0043 0044 // The old Python Thread Local Storage (TLS) API is deprecated in Python 3.7 in favor of the new 0045 // Thread Specific Storage (TSS) API. 0046 #if PY_VERSION_HEX >= 0x03070000 0047 // Avoid unnecessary allocation of `Py_tss_t`, since we cannot use 0048 // `Py_LIMITED_API` anyway. 0049 # if PYBIND11_INTERNALS_VERSION > 4 0050 # define PYBIND11_TLS_KEY_REF Py_tss_t & 0051 # ifdef __GNUC__ 0052 // Clang on macOS warns due to `Py_tss_NEEDS_INIT` not specifying an initializer 0053 // for every field. 0054 # define PYBIND11_TLS_KEY_INIT(var) \ 0055 _Pragma("GCC diagnostic push") /**/ \ 0056 _Pragma("GCC diagnostic ignored \"-Wmissing-field-initializers\"") /**/ \ 0057 Py_tss_t var \ 0058 = Py_tss_NEEDS_INIT; \ 0059 _Pragma("GCC diagnostic pop") 0060 # else 0061 # define PYBIND11_TLS_KEY_INIT(var) Py_tss_t var = Py_tss_NEEDS_INIT; 0062 # endif 0063 # define PYBIND11_TLS_KEY_CREATE(var) (PyThread_tss_create(&(var)) == 0) 0064 # define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get(&(key)) 0065 # define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set(&(key), (value)) 0066 # define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set(&(key), nullptr) 0067 # define PYBIND11_TLS_FREE(key) PyThread_tss_delete(&(key)) 0068 # else 0069 # define PYBIND11_TLS_KEY_REF Py_tss_t * 0070 # define PYBIND11_TLS_KEY_INIT(var) Py_tss_t *var = nullptr; 0071 # define PYBIND11_TLS_KEY_CREATE(var) \ 0072 (((var) = PyThread_tss_alloc()) != nullptr && (PyThread_tss_create((var)) == 0)) 0073 # define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get((key)) 0074 # define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set((key), (value)) 0075 # define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set((key), nullptr) 0076 # define PYBIND11_TLS_FREE(key) PyThread_tss_free(key) 0077 # endif 0078 #else 0079 // Usually an int but a long on Cygwin64 with Python 3.x 0080 # define PYBIND11_TLS_KEY_REF decltype(PyThread_create_key()) 0081 # define PYBIND11_TLS_KEY_INIT(var) PYBIND11_TLS_KEY_REF var = 0; 0082 # define PYBIND11_TLS_KEY_CREATE(var) (((var) = PyThread_create_key()) != -1) 0083 # define PYBIND11_TLS_GET_VALUE(key) PyThread_get_key_value((key)) 0084 # if PY_MAJOR_VERSION < 3 || defined(PYPY_VERSION) 0085 // On CPython < 3.4 and on PyPy, `PyThread_set_key_value` strangely does not set 0086 // the value if it has already been set. Instead, it must first be deleted and 0087 // then set again. 0088 inline void tls_replace_value(PYBIND11_TLS_KEY_REF key, void *value) { 0089 PyThread_delete_key_value(key); 0090 PyThread_set_key_value(key, value); 0091 } 0092 # define PYBIND11_TLS_DELETE_VALUE(key) PyThread_delete_key_value(key) 0093 # define PYBIND11_TLS_REPLACE_VALUE(key, value) \ 0094 ::pybind11::detail::tls_replace_value((key), (value)) 0095 # else 0096 # define PYBIND11_TLS_DELETE_VALUE(key) PyThread_set_key_value((key), nullptr) 0097 # define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_set_key_value((key), (value)) 0098 # endif 0099 # define PYBIND11_TLS_FREE(key) (void) key 0100 #endif 0101 0102 // Python loads modules by default with dlopen with the RTLD_LOCAL flag; under libc++ and possibly 0103 // other STLs, this means `typeid(A)` from one module won't equal `typeid(A)` from another module 0104 // even when `A` is the same, non-hidden-visibility type (e.g. from a common include). Under 0105 // libstdc++, this doesn't happen: equality and the type_index hash are based on the type name, 0106 // which works. If not under a known-good stl, provide our own name-based hash and equality 0107 // functions that use the type name. 0108 #if defined(__GLIBCXX__) 0109 inline bool same_type(const std::type_info &lhs, const std::type_info &rhs) { return lhs == rhs; } 0110 using type_hash = std::hash<std::type_index>; 0111 using type_equal_to = std::equal_to<std::type_index>; 0112 #else 0113 inline bool same_type(const std::type_info &lhs, const std::type_info &rhs) { 0114 return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0; 0115 } 0116 0117 struct type_hash { 0118 size_t operator()(const std::type_index &t) const { 0119 size_t hash = 5381; 0120 const char *ptr = t.name(); 0121 while (auto c = static_cast<unsigned char>(*ptr++)) 0122 hash = (hash * 33) ^ c; 0123 return hash; 0124 } 0125 }; 0126 0127 struct type_equal_to { 0128 bool operator()(const std::type_index &lhs, const std::type_index &rhs) const { 0129 return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0; 0130 } 0131 }; 0132 #endif 0133 0134 template <typename value_type> 0135 using type_map = std::unordered_map<std::type_index, value_type, type_hash, type_equal_to>; 0136 0137 struct override_hash { 0138 inline size_t operator()(const std::pair<const PyObject *, const char *>& v) const { 0139 size_t value = std::hash<const void *>()(v.first); 0140 value ^= std::hash<const void *>()(v.second) + 0x9e3779b9 + (value<<6) + (value>>2); 0141 return value; 0142 } 0143 }; 0144 0145 /// Internal data structure used to track registered instances and types. 0146 /// Whenever binary incompatible changes are made to this structure, 0147 /// `PYBIND11_INTERNALS_VERSION` must be incremented. 0148 struct internals { 0149 type_map<type_info *> registered_types_cpp; // std::type_index -> pybind11's type information 0150 std::unordered_map<PyTypeObject *, std::vector<type_info *>> registered_types_py; // PyTypeObject* -> base type_info(s) 0151 std::unordered_multimap<const void *, instance*> registered_instances; // void * -> instance* 0152 std::unordered_set<std::pair<const PyObject *, const char *>, override_hash> inactive_override_cache; 0153 type_map<std::vector<bool (*)(PyObject *, void *&)>> direct_conversions; 0154 std::unordered_map<const PyObject *, std::vector<PyObject *>> patients; 0155 std::forward_list<ExceptionTranslator> registered_exception_translators; 0156 std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across extensions 0157 #if PYBIND11_INTERNALS_VERSION == 4 0158 std::vector<PyObject *> unused_loader_patient_stack_remove_at_v5; 0159 #endif 0160 std::forward_list<std::string> static_strings; // Stores the std::strings backing detail::c_str() 0161 PyTypeObject *static_property_type; 0162 PyTypeObject *default_metaclass; 0163 PyObject *instance_base; 0164 #if defined(WITH_THREAD) 0165 PYBIND11_TLS_KEY_INIT(tstate) 0166 # if PYBIND11_INTERNALS_VERSION > 4 0167 PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key) 0168 # endif // PYBIND11_INTERNALS_VERSION > 4 0169 PyInterpreterState *istate = nullptr; 0170 ~internals() { 0171 # if PYBIND11_INTERNALS_VERSION > 4 0172 PYBIND11_TLS_FREE(loader_life_support_tls_key); 0173 # endif // PYBIND11_INTERNALS_VERSION > 4 0174 0175 // This destructor is called *after* Py_Finalize() in finalize_interpreter(). 0176 // That *SHOULD BE* fine. The following details what happens when PyThread_tss_free is 0177 // called. PYBIND11_TLS_FREE is PyThread_tss_free on python 3.7+. On older python, it does 0178 // nothing. PyThread_tss_free calls PyThread_tss_delete and PyMem_RawFree. 0179 // PyThread_tss_delete just calls TlsFree (on Windows) or pthread_key_delete (on *NIX). 0180 // Neither of those have anything to do with CPython internals. PyMem_RawFree *requires* 0181 // that the `tstate` be allocated with the CPython allocator. 0182 PYBIND11_TLS_FREE(tstate); 0183 } 0184 #endif 0185 }; 0186 0187 /// Additional type information which does not fit into the PyTypeObject. 0188 /// Changes to this struct also require bumping `PYBIND11_INTERNALS_VERSION`. 0189 struct type_info { 0190 PyTypeObject *type; 0191 const std::type_info *cpptype; 0192 size_t type_size, type_align, holder_size_in_ptrs; 0193 void *(*operator_new)(size_t); 0194 void (*init_instance)(instance *, const void *); 0195 void (*dealloc)(value_and_holder &v_h); 0196 std::vector<PyObject *(*)(PyObject *, PyTypeObject *)> implicit_conversions; 0197 std::vector<std::pair<const std::type_info *, void *(*)(void *)>> implicit_casts; 0198 std::vector<bool (*)(PyObject *, void *&)> *direct_conversions; 0199 buffer_info *(*get_buffer)(PyObject *, void *) = nullptr; 0200 void *get_buffer_data = nullptr; 0201 void *(*module_local_load)(PyObject *, const type_info *) = nullptr; 0202 /* A simple type never occurs as a (direct or indirect) parent 0203 * of a class that makes use of multiple inheritance. 0204 * A type can be simple even if it has non-simple ancestors as long as it has no descendants. 0205 */ 0206 bool simple_type : 1; 0207 /* True if there is no multiple inheritance in this type's inheritance tree */ 0208 bool simple_ancestors : 1; 0209 /* for base vs derived holder_type checks */ 0210 bool default_holder : 1; 0211 /* true if this is a type registered with py::module_local */ 0212 bool module_local : 1; 0213 }; 0214 0215 /// On MSVC, debug and release builds are not ABI-compatible! 0216 #if defined(_MSC_VER) && defined(_DEBUG) 0217 # define PYBIND11_BUILD_TYPE "_debug" 0218 #else 0219 # define PYBIND11_BUILD_TYPE "" 0220 #endif 0221 0222 /// Let's assume that different compilers are ABI-incompatible. 0223 /// A user can manually set this string if they know their 0224 /// compiler is compatible. 0225 #ifndef PYBIND11_COMPILER_TYPE 0226 # if defined(_MSC_VER) 0227 # define PYBIND11_COMPILER_TYPE "_msvc" 0228 # elif defined(__INTEL_COMPILER) 0229 # define PYBIND11_COMPILER_TYPE "_icc" 0230 # elif defined(__clang__) 0231 # define PYBIND11_COMPILER_TYPE "_clang" 0232 # elif defined(__PGI) 0233 # define PYBIND11_COMPILER_TYPE "_pgi" 0234 # elif defined(__MINGW32__) 0235 # define PYBIND11_COMPILER_TYPE "_mingw" 0236 # elif defined(__CYGWIN__) 0237 # define PYBIND11_COMPILER_TYPE "_gcc_cygwin" 0238 # elif defined(__GNUC__) 0239 # define PYBIND11_COMPILER_TYPE "_gcc" 0240 # else 0241 # define PYBIND11_COMPILER_TYPE "_unknown" 0242 # endif 0243 #endif 0244 0245 /// Also standard libs 0246 #ifndef PYBIND11_STDLIB 0247 # if defined(_LIBCPP_VERSION) 0248 # define PYBIND11_STDLIB "_libcpp" 0249 # elif defined(__GLIBCXX__) || defined(__GLIBCPP__) 0250 # define PYBIND11_STDLIB "_libstdcpp" 0251 # else 0252 # define PYBIND11_STDLIB "" 0253 # endif 0254 #endif 0255 0256 /// On Linux/OSX, changes in __GXX_ABI_VERSION__ indicate ABI incompatibility. 0257 #ifndef PYBIND11_BUILD_ABI 0258 # if defined(__GXX_ABI_VERSION) 0259 # define PYBIND11_BUILD_ABI "_cxxabi" PYBIND11_TOSTRING(__GXX_ABI_VERSION) 0260 # else 0261 # define PYBIND11_BUILD_ABI "" 0262 # endif 0263 #endif 0264 0265 #ifndef PYBIND11_INTERNALS_KIND 0266 # if defined(WITH_THREAD) 0267 # define PYBIND11_INTERNALS_KIND "" 0268 # else 0269 # define PYBIND11_INTERNALS_KIND "_without_thread" 0270 # endif 0271 #endif 0272 0273 #define PYBIND11_INTERNALS_ID "__pybind11_internals_v" \ 0274 PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI PYBIND11_BUILD_TYPE "__" 0275 0276 #define PYBIND11_MODULE_LOCAL_ID "__pybind11_module_local_v" \ 0277 PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI PYBIND11_BUILD_TYPE "__" 0278 0279 /// Each module locally stores a pointer to the `internals` data. The data 0280 /// itself is shared among modules with the same `PYBIND11_INTERNALS_ID`. 0281 inline internals **&get_internals_pp() { 0282 static internals **internals_pp = nullptr; 0283 return internals_pp; 0284 } 0285 0286 #if PY_VERSION_HEX >= 0x03030000 0287 // forward decl 0288 inline void translate_exception(std::exception_ptr); 0289 0290 template <class T, 0291 enable_if_t<std::is_same<std::nested_exception, remove_cvref_t<T>>::value, int> = 0> 0292 bool handle_nested_exception(const T &exc, const std::exception_ptr &p) { 0293 std::exception_ptr nested = exc.nested_ptr(); 0294 if (nested != nullptr && nested != p) { 0295 translate_exception(nested); 0296 return true; 0297 } 0298 return false; 0299 } 0300 0301 template <class T, 0302 enable_if_t<!std::is_same<std::nested_exception, remove_cvref_t<T>>::value, int> = 0> 0303 bool handle_nested_exception(const T &exc, const std::exception_ptr &p) { 0304 if (auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(exc))) { 0305 return handle_nested_exception(*nep, p); 0306 } 0307 return false; 0308 } 0309 0310 #else 0311 0312 template <class T> 0313 bool handle_nested_exception(const T &, std::exception_ptr &) { 0314 return false; 0315 } 0316 #endif 0317 0318 inline bool raise_err(PyObject *exc_type, const char *msg) { 0319 #if PY_VERSION_HEX >= 0x03030000 0320 if (PyErr_Occurred()) { 0321 raise_from(exc_type, msg); 0322 return true; 0323 } 0324 #endif 0325 PyErr_SetString(exc_type, msg); 0326 return false; 0327 } 0328 0329 inline void translate_exception(std::exception_ptr p) { 0330 if (!p) { 0331 return; 0332 } 0333 try { 0334 std::rethrow_exception(p); 0335 } catch (error_already_set &e) { 0336 handle_nested_exception(e, p); 0337 e.restore(); 0338 return; 0339 } catch (const builtin_exception &e) { 0340 // Could not use template since it's an abstract class. 0341 if (auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(e))) { 0342 handle_nested_exception(*nep, p); 0343 } 0344 e.set_error(); 0345 return; 0346 } catch (const std::bad_alloc &e) { 0347 handle_nested_exception(e, p); 0348 raise_err(PyExc_MemoryError, e.what()); 0349 return; 0350 } catch (const std::domain_error &e) { 0351 handle_nested_exception(e, p); 0352 raise_err(PyExc_ValueError, e.what()); 0353 return; 0354 } catch (const std::invalid_argument &e) { 0355 handle_nested_exception(e, p); 0356 raise_err(PyExc_ValueError, e.what()); 0357 return; 0358 } catch (const std::length_error &e) { 0359 handle_nested_exception(e, p); 0360 raise_err(PyExc_ValueError, e.what()); 0361 return; 0362 } catch (const std::out_of_range &e) { 0363 handle_nested_exception(e, p); 0364 raise_err(PyExc_IndexError, e.what()); 0365 return; 0366 } catch (const std::range_error &e) { 0367 handle_nested_exception(e, p); 0368 raise_err(PyExc_ValueError, e.what()); 0369 return; 0370 } catch (const std::overflow_error &e) { 0371 handle_nested_exception(e, p); 0372 raise_err(PyExc_OverflowError, e.what()); 0373 return; 0374 } catch (const std::exception &e) { 0375 handle_nested_exception(e, p); 0376 raise_err(PyExc_RuntimeError, e.what()); 0377 return; 0378 } catch (const std::nested_exception &e) { 0379 handle_nested_exception(e, p); 0380 raise_err(PyExc_RuntimeError, "Caught an unknown nested exception!"); 0381 return; 0382 } catch (...) { 0383 raise_err(PyExc_RuntimeError, "Caught an unknown exception!"); 0384 return; 0385 } 0386 } 0387 0388 #if !defined(__GLIBCXX__) 0389 inline void translate_local_exception(std::exception_ptr p) { 0390 try { 0391 if (p) std::rethrow_exception(p); 0392 } catch (error_already_set &e) { e.restore(); return; 0393 } catch (const builtin_exception &e) { e.set_error(); return; 0394 } 0395 } 0396 #endif 0397 0398 /// Return a reference to the current `internals` data 0399 PYBIND11_NOINLINE internals &get_internals() { 0400 auto **&internals_pp = get_internals_pp(); 0401 if (internals_pp && *internals_pp) 0402 return **internals_pp; 0403 0404 // Ensure that the GIL is held since we will need to make Python calls. 0405 // Cannot use py::gil_scoped_acquire here since that constructor calls get_internals. 0406 struct gil_scoped_acquire_local { 0407 gil_scoped_acquire_local() : state (PyGILState_Ensure()) {} 0408 ~gil_scoped_acquire_local() { PyGILState_Release(state); } 0409 const PyGILState_STATE state; 0410 } gil; 0411 0412 PYBIND11_STR_TYPE id(PYBIND11_INTERNALS_ID); 0413 auto builtins = handle(PyEval_GetBuiltins()); 0414 if (builtins.contains(id) && isinstance<capsule>(builtins[id])) { 0415 internals_pp = static_cast<internals **>(capsule(builtins[id])); 0416 0417 // We loaded builtins through python's builtins, which means that our `error_already_set` 0418 // and `builtin_exception` may be different local classes than the ones set up in the 0419 // initial exception translator, below, so add another for our local exception classes. 0420 // 0421 // libstdc++ doesn't require this (types there are identified only by name) 0422 // libc++ with CPython doesn't require this (types are explicitly exported) 0423 // libc++ with PyPy still need it, awaiting further investigation 0424 #if !defined(__GLIBCXX__) 0425 (*internals_pp)->registered_exception_translators.push_front(&translate_local_exception); 0426 #endif 0427 } else { 0428 if (!internals_pp) internals_pp = new internals*(); 0429 auto *&internals_ptr = *internals_pp; 0430 internals_ptr = new internals(); 0431 #if defined(WITH_THREAD) 0432 0433 # if PY_VERSION_HEX < 0x03090000 0434 PyEval_InitThreads(); 0435 # endif 0436 PyThreadState *tstate = PyThreadState_Get(); 0437 if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->tstate)) { 0438 pybind11_fail("get_internals: could not successfully initialize the tstate TSS key!"); 0439 } 0440 PYBIND11_TLS_REPLACE_VALUE(internals_ptr->tstate, tstate); 0441 0442 # if PYBIND11_INTERNALS_VERSION > 4 0443 if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->loader_life_support_tls_key)) { 0444 pybind11_fail("get_internals: could not successfully initialize the " 0445 "loader_life_support TSS key!"); 0446 } 0447 # endif 0448 internals_ptr->istate = tstate->interp; 0449 #endif 0450 builtins[id] = capsule(internals_pp); 0451 internals_ptr->registered_exception_translators.push_front(&translate_exception); 0452 internals_ptr->static_property_type = make_static_property_type(); 0453 internals_ptr->default_metaclass = make_default_metaclass(); 0454 internals_ptr->instance_base = make_object_base_type(internals_ptr->default_metaclass); 0455 } 0456 return **internals_pp; 0457 } 0458 0459 // the internals struct (above) is shared between all the modules. local_internals are only 0460 // for a single module. Any changes made to internals may require an update to 0461 // PYBIND11_INTERNALS_VERSION, breaking backwards compatibility. local_internals is, by design, 0462 // restricted to a single module. Whether a module has local internals or not should not 0463 // impact any other modules, because the only things accessing the local internals is the 0464 // module that contains them. 0465 struct local_internals { 0466 type_map<type_info *> registered_types_cpp; 0467 std::forward_list<ExceptionTranslator> registered_exception_translators; 0468 #if defined(WITH_THREAD) && PYBIND11_INTERNALS_VERSION == 4 0469 0470 // For ABI compatibility, we can't store the loader_life_support TLS key in 0471 // the `internals` struct directly. Instead, we store it in `shared_data` and 0472 // cache a copy in `local_internals`. If we allocated a separate TLS key for 0473 // each instance of `local_internals`, we could end up allocating hundreds of 0474 // TLS keys if hundreds of different pybind11 modules are loaded (which is a 0475 // plausible number). 0476 PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key) 0477 0478 // Holds the shared TLS key for the loader_life_support stack. 0479 struct shared_loader_life_support_data { 0480 PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key) 0481 shared_loader_life_support_data() { 0482 if (!PYBIND11_TLS_KEY_CREATE(loader_life_support_tls_key)) { 0483 pybind11_fail("local_internals: could not successfully initialize the " 0484 "loader_life_support TLS key!"); 0485 } 0486 } 0487 // We can't help but leak the TLS key, because Python never unloads extension modules. 0488 }; 0489 0490 local_internals() { 0491 auto &internals = get_internals(); 0492 // Get or create the `loader_life_support_stack_key`. 0493 auto &ptr = internals.shared_data["_life_support"]; 0494 if (!ptr) { 0495 ptr = new shared_loader_life_support_data; 0496 } 0497 loader_life_support_tls_key 0498 = static_cast<shared_loader_life_support_data *>(ptr)->loader_life_support_tls_key; 0499 } 0500 #endif // defined(WITH_THREAD) && PYBIND11_INTERNALS_VERSION == 4 0501 }; 0502 0503 /// Works like `get_internals`, but for things which are locally registered. 0504 inline local_internals &get_local_internals() { 0505 static local_internals locals; 0506 return locals; 0507 } 0508 0509 0510 /// Constructs a std::string with the given arguments, stores it in `internals`, and returns its 0511 /// `c_str()`. Such strings objects have a long storage duration -- the internal strings are only 0512 /// cleared when the program exits or after interpreter shutdown (when embedding), and so are 0513 /// suitable for c-style strings needed by Python internals (such as PyTypeObject's tp_name). 0514 template <typename... Args> 0515 const char *c_str(Args &&...args) { 0516 auto &strings = get_internals().static_strings; 0517 strings.emplace_front(std::forward<Args>(args)...); 0518 return strings.front().c_str(); 0519 } 0520 0521 PYBIND11_NAMESPACE_END(detail) 0522 0523 /// Returns a named pointer that is shared among all extension modules (using the same 0524 /// pybind11 version) running in the current interpreter. Names starting with underscores 0525 /// are reserved for internal usage. Returns `nullptr` if no matching entry was found. 0526 PYBIND11_NOINLINE void *get_shared_data(const std::string &name) { 0527 auto &internals = detail::get_internals(); 0528 auto it = internals.shared_data.find(name); 0529 return it != internals.shared_data.end() ? it->second : nullptr; 0530 } 0531 0532 /// Set the shared data that can be later recovered by `get_shared_data()`. 0533 PYBIND11_NOINLINE void *set_shared_data(const std::string &name, void *data) { 0534 detail::get_internals().shared_data[name] = data; 0535 return data; 0536 } 0537 0538 /// Returns a typed reference to a shared data entry (by using `get_shared_data()`) if 0539 /// such entry exists. Otherwise, a new object of default-constructible type `T` is 0540 /// added to the shared data under the given name and a reference to it is returned. 0541 template<typename T> 0542 T &get_or_create_shared_data(const std::string &name) { 0543 auto &internals = detail::get_internals(); 0544 auto it = internals.shared_data.find(name); 0545 T *ptr = (T *) (it != internals.shared_data.end() ? it->second : nullptr); 0546 if (!ptr) { 0547 ptr = new T(); 0548 internals.shared_data[name] = ptr; 0549 } 0550 return *ptr; 0551 } 0552 0553 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)