cppyabm  1.0.17
An agent-based library to integrate C++ and Python
cast.h
Go to the documentation of this file.
1 /*
2  pybind11/cast.h: Partial template specializations to cast between
3  C++ and Python types
4 
5  Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
6 
7  All rights reserved. Use of this source code is governed by a
8  BSD-style license that can be found in the LICENSE file.
9 */
10 
11 #pragma once
12 
13 #include "pytypes.h"
14 #include "detail/typeid.h"
15 #include "detail/descr.h"
16 #include "detail/internals.h"
17 #include <array>
18 #include <limits>
19 #include <tuple>
20 #include <type_traits>
21 
22 #if defined(PYBIND11_CPP17)
23 # if defined(__has_include)
24 # if __has_include(<string_view>)
25 # define PYBIND11_HAS_STRING_VIEW
26 # endif
27 # elif defined(_MSC_VER)
28 # define PYBIND11_HAS_STRING_VIEW
29 # endif
30 #endif
31 #ifdef PYBIND11_HAS_STRING_VIEW
32 #include <string_view>
33 #endif
34 
35 #if defined(__cpp_lib_char8_t) && __cpp_lib_char8_t >= 201811L
36 # define PYBIND11_HAS_U8STRING
37 #endif
38 
41 
42 /// A life support system for temporary objects created by `type_caster::load()`.
43 /// Adding a patient will keep it alive up until the enclosing function returns.
45 public:
46  /// A new patient frame is created when a function is entered
48  get_internals().loader_patient_stack.push_back(nullptr);
49  }
50 
51  /// ... and destroyed after it returns
53  auto &stack = get_internals().loader_patient_stack;
54  if (stack.empty())
55  pybind11_fail("loader_life_support: internal error");
56 
57  auto ptr = stack.back();
58  stack.pop_back();
59  Py_CLEAR(ptr);
60 
61  // A heuristic to reduce the stack's capacity (e.g. after long recursive calls)
62  if (stack.capacity() > 16 && !stack.empty() && stack.capacity() / stack.size() > 2)
63  stack.shrink_to_fit();
64  }
65 
66  /// This can only be used inside a pybind11-bound function, either by `argument_loader`
67  /// at argument preparation time or by `py::cast()` at execution time.
69  auto &stack = get_internals().loader_patient_stack;
70  if (stack.empty())
71  throw cast_error("When called outside a bound function, py::cast() cannot "
72  "do Python -> C++ conversions which require the creation "
73  "of temporary values");
74 
75  auto &list_ptr = stack.back();
76  if (list_ptr == nullptr) {
77  list_ptr = PyList_New(1);
78  if (!list_ptr)
79  pybind11_fail("loader_life_support: error allocating list");
80  PyList_SET_ITEM(list_ptr, 0, h.inc_ref().ptr());
81  } else {
82  auto result = PyList_Append(list_ptr, h.ptr());
83  if (result == -1)
84  pybind11_fail("loader_life_support: error adding patient");
85  }
86  }
87 };
88 
89 // Gets the cache entry for the given type, creating it if necessary. The return value is the pair
90 // returned by emplace, i.e. an iterator for the entry and a bool set to `true` if the entry was
91 // just created.
92 inline std::pair<decltype(internals::registered_types_py)::iterator, bool> all_type_info_get_cache(PyTypeObject *type);
93 
94 // Populates a just-created cache entry.
95 PYBIND11_NOINLINE inline void all_type_info_populate(PyTypeObject *t, std::vector<type_info *> &bases) {
96  std::vector<PyTypeObject *> check;
97  for (handle parent : reinterpret_borrow<tuple>(t->tp_bases))
98  check.push_back((PyTypeObject *) parent.ptr());
99 
100  auto const &type_dict = get_internals().registered_types_py;
101  for (size_t i = 0; i < check.size(); i++) {
102  auto type = check[i];
103  // Ignore Python2 old-style class super type:
104  if (!PyType_Check((PyObject *) type)) continue;
105 
106  // Check `type` in the current set of registered python types:
107  auto it = type_dict.find(type);
108  if (it != type_dict.end()) {
109  // We found a cache entry for it, so it's either pybind-registered or has pre-computed
110  // pybind bases, but we have to make sure we haven't already seen the type(s) before: we
111  // want to follow Python/virtual C++ rules that there should only be one instance of a
112  // common base.
113  for (auto *tinfo : it->second) {
114  // NB: Could use a second set here, rather than doing a linear search, but since
115  // having a large number of immediate pybind11-registered types seems fairly
116  // unlikely, that probably isn't worthwhile.
117  bool found = false;
118  for (auto *known : bases) {
119  if (known == tinfo) { found = true; break; }
120  }
121  if (!found) bases.push_back(tinfo);
122  }
123  }
124  else if (type->tp_bases) {
125  // It's some python type, so keep follow its bases classes to look for one or more
126  // registered types
127  if (i + 1 == check.size()) {
128  // When we're at the end, we can pop off the current element to avoid growing
129  // `check` when adding just one base (which is typical--i.e. when there is no
130  // multiple inheritance)
131  check.pop_back();
132  i--;
133  }
134  for (handle parent : reinterpret_borrow<tuple>(type->tp_bases))
135  check.push_back((PyTypeObject *) parent.ptr());
136  }
137  }
138 }
139 
140 /**
141  * Extracts vector of type_info pointers of pybind-registered roots of the given Python type. Will
142  * be just 1 pybind type for the Python type of a pybind-registered class, or for any Python-side
143  * derived class that uses single inheritance. Will contain as many types as required for a Python
144  * class that uses multiple inheritance to inherit (directly or indirectly) from multiple
145  * pybind-registered classes. Will be empty if neither the type nor any base classes are
146  * pybind-registered.
147  *
148  * The value is cached for the lifetime of the Python type.
149  */
150 inline const std::vector<detail::type_info *> &all_type_info(PyTypeObject *type) {
151  auto ins = all_type_info_get_cache(type);
152  if (ins.second)
153  // New cache entry: populate it
154  all_type_info_populate(type, ins.first->second);
155 
156  return ins.first->second;
157 }
158 
159 /**
160  * Gets a single pybind11 type info for a python type. Returns nullptr if neither the type nor any
161  * ancestors are pybind11-registered. Throws an exception if there are multiple bases--use
162  * `all_type_info` instead if you want to support multiple bases.
163  */
164 PYBIND11_NOINLINE inline detail::type_info* get_type_info(PyTypeObject *type) {
165  auto &bases = all_type_info(type);
166  if (bases.empty())
167  return nullptr;
168  if (bases.size() > 1)
169  pybind11_fail("pybind11::detail::get_type_info: type has multiple pybind11-registered bases");
170  return bases.front();
171 }
172 
173 inline detail::type_info *get_local_type_info(const std::type_index &tp) {
174  auto &locals = registered_local_types_cpp();
175  auto it = locals.find(tp);
176  if (it != locals.end())
177  return it->second;
178  return nullptr;
179 }
180 
181 inline detail::type_info *get_global_type_info(const std::type_index &tp) {
182  auto &types = get_internals().registered_types_cpp;
183  auto it = types.find(tp);
184  if (it != types.end())
185  return it->second;
186  return nullptr;
187 }
188 
189 /// Return the type info for a given C++ type; on lookup failure can either throw or return nullptr.
190 PYBIND11_NOINLINE inline detail::type_info *get_type_info(const std::type_index &tp,
191  bool throw_if_missing = false) {
192  if (auto ltype = get_local_type_info(tp))
193  return ltype;
194  if (auto gtype = get_global_type_info(tp))
195  return gtype;
196 
197  if (throw_if_missing) {
198  std::string tname = tp.name();
199  detail::clean_type_id(tname);
200  pybind11_fail("pybind11::detail::get_type_info: unable to find type info for \"" + tname + "\"");
201  }
202  return nullptr;
203 }
204 
205 PYBIND11_NOINLINE inline handle get_type_handle(const std::type_info &tp, bool throw_if_missing) {
206  detail::type_info *type_info = get_type_info(tp, throw_if_missing);
207  return handle(type_info ? ((PyObject *) type_info->type) : nullptr);
208 }
209 
210 // Searches the inheritance graph for a registered Python instance, using all_type_info().
212  const detail::type_info *tinfo) {
213  auto it_instances = get_internals().registered_instances.equal_range(src);
214  for (auto it_i = it_instances.first; it_i != it_instances.second; ++it_i) {
215  for (auto instance_type : detail::all_type_info(Py_TYPE(it_i->second))) {
216  if (instance_type && same_type(*instance_type->cpptype, *tinfo->cpptype))
217  return handle((PyObject *) it_i->second).inc_ref();
218  }
219  }
220  return handle();
221 }
222 
224  instance *inst = nullptr;
225  size_t index = 0u;
226  const detail::type_info *type = nullptr;
227  void **vh = nullptr;
228 
229  // Main constructor for a found value/holder:
230  value_and_holder(instance *i, const detail::type_info *type, size_t vpos, size_t index) :
231  inst{i}, index{index}, type{type},
233  {}
234 
235  // Default constructor (used to signal a value-and-holder not found by get_value_and_holder())
236  value_and_holder() = default;
237 
238  // Used for past-the-end iterator
240 
241  template <typename V = void> V *&value_ptr() const {
242  return reinterpret_cast<V *&>(vh[0]);
243  }
244  // True if this `value_and_holder` has a non-null value pointer
245  explicit operator bool() const { return value_ptr(); }
246 
247  template <typename H> H &holder() const {
248  return reinterpret_cast<H &>(vh[1]);
249  }
250  bool holder_constructed() const {
251  return inst->simple_layout
254  }
255  void set_holder_constructed(bool v = true) {
256  if (inst->simple_layout)
258  else if (v)
260  else
262  }
263  bool instance_registered() const {
264  return inst->simple_layout
267  }
268  void set_instance_registered(bool v = true) {
269  if (inst->simple_layout)
271  else if (v)
273  else
275  }
276 };
277 
278 // Container for accessing and iterating over an instance's values/holders
280 private:
281  instance *inst;
282  using type_vec = std::vector<detail::type_info *>;
283  const type_vec &tinfo;
284 
285 public:
286  values_and_holders(instance *inst) : inst{inst}, tinfo(all_type_info(Py_TYPE(inst))) {}
287 
288  struct iterator {
289  private:
290  instance *inst = nullptr;
291  const type_vec *types = nullptr;
292  value_and_holder curr;
293  friend struct values_and_holders;
294  iterator(instance *inst, const type_vec *tinfo)
295  : inst{inst}, types{tinfo},
296  curr(inst /* instance */,
297  types->empty() ? nullptr : (*types)[0] /* type info */,
298  0, /* vpos: (non-simple types only): the first vptr comes first */
299  0 /* index */)
300  {}
301  // Past-the-end iterator:
302  iterator(size_t end) : curr(end) {}
303  public:
304  bool operator==(const iterator &other) const { return curr.index == other.curr.index; }
305  bool operator!=(const iterator &other) const { return curr.index != other.curr.index; }
307  if (!inst->simple_layout)
308  curr.vh += 1 + (*types)[curr.index]->holder_size_in_ptrs;
309  ++curr.index;
310  curr.type = curr.index < types->size() ? (*types)[curr.index] : nullptr;
311  return *this;
312  }
313  value_and_holder &operator*() { return curr; }
314  value_and_holder *operator->() { return &curr; }
315  };
316 
317  iterator begin() { return iterator(inst, &tinfo); }
318  iterator end() { return iterator(tinfo.size()); }
319 
320  iterator find(const type_info *find_type) {
321  auto it = begin(), endit = end();
322  while (it != endit && it->type != find_type) ++it;
323  return it;
324  }
325 
326  size_t size() { return tinfo.size(); }
327 };
328 
329 /**
330  * Extracts C++ value and holder pointer references from an instance (which may contain multiple
331  * values/holders for python-side multiple inheritance) that match the given type. Throws an error
332  * if the given type (or ValueType, if omitted) is not a pybind11 base of the given instance. If
333  * `find_type` is omitted (or explicitly specified as nullptr) the first value/holder are returned,
334  * regardless of type (and the resulting .type will be nullptr).
335  *
336  * The returned object should be short-lived: in particular, it must not outlive the called-upon
337  * instance.
338  */
339 PYBIND11_NOINLINE inline value_and_holder instance::get_value_and_holder(const type_info *find_type /*= nullptr default in common.h*/, bool throw_if_missing /*= true in common.h*/) {
340  // Optimize common case:
341  if (!find_type || Py_TYPE(this) == find_type->type)
342  return value_and_holder(this, find_type, 0, 0);
343 
344  detail::values_and_holders vhs(this);
345  auto it = vhs.find(find_type);
346  if (it != vhs.end())
347  return *it;
348 
349  if (!throw_if_missing)
350  return value_and_holder();
351 
352 #if defined(NDEBUG)
353  pybind11_fail("pybind11::detail::instance::get_value_and_holder: "
354  "type is not a pybind11 base of the given instance "
355  "(compile in debug mode for type details)");
356 #else
357  pybind11_fail("pybind11::detail::instance::get_value_and_holder: `" +
358  get_fully_qualified_tp_name(find_type->type) + "' is not a pybind11 base of the given `" +
359  get_fully_qualified_tp_name(Py_TYPE(this)) + "' instance");
360 #endif
361 }
362 
364  auto &tinfo = all_type_info(Py_TYPE(this));
365 
366  const size_t n_types = tinfo.size();
367 
368  if (n_types == 0)
369  pybind11_fail("instance allocation failed: new instance has no pybind11-registered base types");
370 
371  simple_layout =
372  n_types == 1 && tinfo.front()->holder_size_in_ptrs <= instance_simple_holder_in_ptrs();
373 
374  // Simple path: no python-side multiple inheritance, and a small-enough holder
375  if (simple_layout) {
376  simple_value_holder[0] = nullptr;
379  }
380  else { // multiple base types or a too-large holder
381  // Allocate space to hold: [v1*][h1][v2*][h2]...[bb...] where [vN*] is a value pointer,
382  // [hN] is the (uninitialized) holder instance for value N, and [bb...] is a set of bool
383  // values that tracks whether each associated holder has been initialized. Each [block] is
384  // padded, if necessary, to an integer multiple of sizeof(void *).
385  size_t space = 0;
386  for (auto t : tinfo) {
387  space += 1; // value pointer
388  space += t->holder_size_in_ptrs; // holder instance
389  }
390  size_t flags_at = space;
391  space += size_in_ptrs(n_types); // status bytes (holder_constructed and instance_registered)
392 
393  // Allocate space for flags, values, and holders, and initialize it to 0 (flags and values,
394  // in particular, need to be 0). Use Python's memory allocation functions: in Python 3.6
395  // they default to using pymalloc, which is designed to be efficient for small allocations
396  // like the one we're doing here; in earlier versions (and for larger allocations) they are
397  // just wrappers around malloc.
398 #if PY_VERSION_HEX >= 0x03050000
399  nonsimple.values_and_holders = (void **) PyMem_Calloc(space, sizeof(void *));
400  if (!nonsimple.values_and_holders) throw std::bad_alloc();
401 #else
402  nonsimple.values_and_holders = (void **) PyMem_New(void *, space);
403  if (!nonsimple.values_and_holders) throw std::bad_alloc();
404  std::memset(nonsimple.values_and_holders, 0, space * sizeof(void *));
405 #endif
406  nonsimple.status = reinterpret_cast<uint8_t *>(&nonsimple.values_and_holders[flags_at]);
407  }
408  owned = true;
409 }
410 
412  if (!simple_layout)
413  PyMem_Free(nonsimple.values_and_holders);
414 }
415 
416 PYBIND11_NOINLINE inline bool isinstance_generic(handle obj, const std::type_info &tp) {
417  handle type = detail::get_type_handle(tp, false);
418  if (!type)
419  return false;
420  return isinstance(obj, type);
421 }
422 
423 PYBIND11_NOINLINE inline std::string error_string() {
424  if (!PyErr_Occurred()) {
425  PyErr_SetString(PyExc_RuntimeError, "Unknown internal error occurred");
426  return "Unknown internal error occurred";
427  }
428 
429  error_scope scope; // Preserve error state
430 
431  std::string errorString;
432  if (scope.type) {
433  errorString += handle(scope.type).attr("__name__").cast<std::string>();
434  errorString += ": ";
435  }
436  if (scope.value)
437  errorString += (std::string) str(scope.value);
438 
439  PyErr_NormalizeException(&scope.type, &scope.value, &scope.trace);
440 
441 #if PY_MAJOR_VERSION >= 3
442  if (scope.trace != nullptr)
443  PyException_SetTraceback(scope.value, scope.trace);
444 #endif
445 
446 #if !defined(PYPY_VERSION)
447  if (scope.trace) {
448  auto *trace = (PyTracebackObject *) scope.trace;
449 
450  /* Get the deepest trace possible */
451  while (trace->tb_next)
452  trace = trace->tb_next;
453 
454  PyFrameObject *frame = trace->tb_frame;
455  errorString += "\n\nAt:\n";
456  while (frame) {
457  int lineno = PyFrame_GetLineNumber(frame);
458  errorString +=
459  " " + handle(frame->f_code->co_filename).cast<std::string>() +
460  "(" + std::to_string(lineno) + "): " +
461  handle(frame->f_code->co_name).cast<std::string>() + "\n";
462  frame = frame->f_back;
463  }
464  }
465 #endif
466 
467  return errorString;
468 }
469 
470 PYBIND11_NOINLINE inline handle get_object_handle(const void *ptr, const detail::type_info *type ) {
471  auto &instances = get_internals().registered_instances;
472  auto range = instances.equal_range(ptr);
473  for (auto it = range.first; it != range.second; ++it) {
474  for (const auto &vh : values_and_holders(it->second)) {
475  if (vh.type == type)
476  return handle((PyObject *) it->second);
477  }
478  }
479  return handle();
480 }
481 
482 inline PyThreadState *get_thread_state_unchecked() {
483 #if defined(PYPY_VERSION)
484  return PyThreadState_GET();
485 #elif PY_VERSION_HEX < 0x03000000
486  return _PyThreadState_Current;
487 #elif PY_VERSION_HEX < 0x03050000
488  return (PyThreadState*) _Py_atomic_load_relaxed(&_PyThreadState_Current);
489 #elif PY_VERSION_HEX < 0x03050200
490  return (PyThreadState*) _PyThreadState_Current.value;
491 #else
492  return _PyThreadState_UncheckedGet();
493 #endif
494 }
495 
496 // Forward declarations
497 inline void keep_alive_impl(handle nurse, handle patient);
498 inline PyObject *make_new_instance(PyTypeObject *type);
499 
501 public:
504 
506  : typeinfo(typeinfo), cpptype(typeinfo ? typeinfo->cpptype : nullptr) { }
507 
508  bool load(handle src, bool convert) {
509  return load_impl<type_caster_generic>(src, convert);
510  }
511 
512  PYBIND11_NOINLINE static handle cast(const void *_src, return_value_policy policy, handle parent,
513  const detail::type_info *tinfo,
514  void *(*copy_constructor)(const void *),
515  void *(*move_constructor)(const void *),
516  const void *existing_holder = nullptr) {
517  if (!tinfo) // no type info: error will be set already
518  return handle();
519 
520  void *src = const_cast<void *>(_src);
521  if (src == nullptr)
522  return none().release();
523 
524  if (handle registered_inst = find_registered_python_instance(src, tinfo))
525  return registered_inst;
526 
527  auto inst = reinterpret_steal<object>(make_new_instance(tinfo->type));
528  auto wrapper = reinterpret_cast<instance *>(inst.ptr());
529  wrapper->owned = false;
530  void *&valueptr = values_and_holders(wrapper).begin()->value_ptr();
531 
532  switch (policy) {
533  case return_value_policy::automatic:
534  case return_value_policy::take_ownership:
535  valueptr = src;
536  wrapper->owned = true;
537  break;
538 
539  case return_value_policy::automatic_reference:
541  valueptr = src;
542  wrapper->owned = false;
543  break;
544 
545  case return_value_policy::copy:
546  if (copy_constructor)
547  valueptr = copy_constructor(src);
548  else {
549 #if defined(NDEBUG)
550  throw cast_error("return_value_policy = copy, but type is "
551  "non-copyable! (compile in debug mode for details)");
552 #else
553  std::string type_name(tinfo->cpptype->name());
554  detail::clean_type_id(type_name);
555  throw cast_error("return_value_policy = copy, but type " +
556  type_name + " is non-copyable!");
557 #endif
558  }
559  wrapper->owned = true;
560  break;
561 
563  if (move_constructor)
564  valueptr = move_constructor(src);
565  else if (copy_constructor)
566  valueptr = copy_constructor(src);
567  else {
568 #if defined(NDEBUG)
569  throw cast_error("return_value_policy = move, but type is neither "
570  "movable nor copyable! "
571  "(compile in debug mode for details)");
572 #else
573  std::string type_name(tinfo->cpptype->name());
574  detail::clean_type_id(type_name);
575  throw cast_error("return_value_policy = move, but type " +
576  type_name + " is neither movable nor copyable!");
577 #endif
578  }
579  wrapper->owned = true;
580  break;
581 
583  valueptr = src;
584  wrapper->owned = false;
585  keep_alive_impl(inst, parent);
586  break;
587 
588  default:
589  throw cast_error("unhandled return_value_policy: should not happen!");
590  }
591 
592  tinfo->init_instance(wrapper, existing_holder);
593 
594  return inst.release();
595  }
596 
597  // Base methods for generic caster; there are overridden in copyable_holder_caster
599  auto *&vptr = v_h.value_ptr();
600  // Lazy allocation for unallocated values:
601  if (vptr == nullptr) {
602  auto *type = v_h.type ? v_h.type : typeinfo;
603  if (type->operator_new) {
604  vptr = type->operator_new(type->type_size);
605  } else {
606  #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
607  if (type->type_align > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
608  vptr = ::operator new(type->type_size,
609  std::align_val_t(type->type_align));
610  else
611  #endif
612  vptr = ::operator new(type->type_size);
613  }
614  }
615  value = vptr;
616  }
617  bool try_implicit_casts(handle src, bool convert) {
618  for (auto &cast : typeinfo->implicit_casts) {
619  type_caster_generic sub_caster(*cast.first);
620  if (sub_caster.load(src, convert)) {
621  value = cast.second(sub_caster.value);
622  return true;
623  }
624  }
625  return false;
626  }
628  for (auto &converter : *typeinfo->direct_conversions) {
629  if (converter(src.ptr(), value))
630  return true;
631  }
632  return false;
633  }
635 
636  PYBIND11_NOINLINE static void *local_load(PyObject *src, const type_info *ti) {
637  auto caster = type_caster_generic(ti);
638  if (caster.load(src, false))
639  return caster.value;
640  return nullptr;
641  }
642 
643  /// Try to load with foreign typeinfo, if available. Used when there is no
644  /// native typeinfo, or when the native one wasn't able to produce a value.
646  constexpr auto *local_key = PYBIND11_MODULE_LOCAL_ID;
647  const auto pytype = type::handle_of(src);
648  if (!hasattr(pytype, local_key))
649  return false;
650 
651  type_info *foreign_typeinfo = reinterpret_borrow<capsule>(getattr(pytype, local_key));
652  // Only consider this foreign loader if actually foreign and is a loader of the correct cpp type
653  if (foreign_typeinfo->module_local_load == &local_load
654  || (cpptype && !same_type(*cpptype, *foreign_typeinfo->cpptype)))
655  return false;
656 
657  if (auto result = foreign_typeinfo->module_local_load(src.ptr(), foreign_typeinfo)) {
658  value = result;
659  return true;
660  }
661  return false;
662  }
663 
664  // Implementation of `load`; this takes the type of `this` so that it can dispatch the relevant
665  // bits of code between here and copyable_holder_caster where the two classes need different
666  // logic (without having to resort to virtual inheritance).
667  template <typename ThisT>
668  PYBIND11_NOINLINE bool load_impl(handle src, bool convert) {
669  if (!src) return false;
670  if (!typeinfo) return try_load_foreign_module_local(src);
671  if (src.is_none()) {
672  // Defer accepting None to other overloads (if we aren't in convert mode):
673  if (!convert) return false;
674  value = nullptr;
675  return true;
676  }
677 
678  auto &this_ = static_cast<ThisT &>(*this);
679  this_.check_holder_compat();
680 
681  PyTypeObject *srctype = Py_TYPE(src.ptr());
682 
683  // Case 1: If src is an exact type match for the target type then we can reinterpret_cast
684  // the instance's value pointer to the target type:
685  if (srctype == typeinfo->type) {
686  this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
687  return true;
688  }
689  // Case 2: We have a derived class
690  else if (PyType_IsSubtype(srctype, typeinfo->type)) {
691  auto &bases = all_type_info(srctype);
692  bool no_cpp_mi = typeinfo->simple_type;
693 
694  // Case 2a: the python type is a Python-inherited derived class that inherits from just
695  // one simple (no MI) pybind11 class, or is an exact match, so the C++ instance is of
696  // the right type and we can use reinterpret_cast.
697  // (This is essentially the same as case 2b, but because not using multiple inheritance
698  // is extremely common, we handle it specially to avoid the loop iterator and type
699  // pointer lookup overhead)
700  if (bases.size() == 1 && (no_cpp_mi || bases.front()->type == typeinfo->type)) {
701  this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
702  return true;
703  }
704  // Case 2b: the python type inherits from multiple C++ bases. Check the bases to see if
705  // we can find an exact match (or, for a simple C++ type, an inherited match); if so, we
706  // can safely reinterpret_cast to the relevant pointer.
707  else if (bases.size() > 1) {
708  for (auto base : bases) {
709  if (no_cpp_mi ? PyType_IsSubtype(base->type, typeinfo->type) : base->type == typeinfo->type) {
710  this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder(base));
711  return true;
712  }
713  }
714  }
715 
716  // Case 2c: C++ multiple inheritance is involved and we couldn't find an exact type match
717  // in the registered bases, above, so try implicit casting (needed for proper C++ casting
718  // when MI is involved).
719  if (this_.try_implicit_casts(src, convert))
720  return true;
721  }
722 
723  // Perform an implicit conversion
724  if (convert) {
725  for (auto &converter : typeinfo->implicit_conversions) {
726  auto temp = reinterpret_steal<object>(converter(src.ptr(), typeinfo->type));
727  if (load_impl<ThisT>(temp, false)) {
729  return true;
730  }
731  }
732  if (this_.try_direct_conversions(src))
733  return true;
734  }
735 
736  // Failed to match local typeinfo. Try again with global.
737  if (typeinfo->module_local) {
738  if (auto gtype = get_global_type_info(*typeinfo->cpptype)) {
739  typeinfo = gtype;
740  return load(src, false);
741  }
742  }
743 
744  // Global typeinfo has precedence over foreign module_local
745  return try_load_foreign_module_local(src);
746  }
747 
748 
749  // Called to do type lookup and wrap the pointer and type in a pair when a dynamic_cast
750  // isn't needed or can't be used. If the type is unknown, sets the error and returns a pair
751  // with .second = nullptr. (p.first = nullptr is not an error: it becomes None).
752  PYBIND11_NOINLINE static std::pair<const void *, const type_info *> src_and_type(
753  const void *src, const std::type_info &cast_type, const std::type_info *rtti_type = nullptr) {
754  if (auto *tpi = get_type_info(cast_type))
755  return {src, const_cast<const type_info *>(tpi)};
756 
757  // Not found, set error:
758  std::string tname = rtti_type ? rtti_type->name() : cast_type.name();
759  detail::clean_type_id(tname);
760  std::string msg = "Unregistered type : " + tname;
761  PyErr_SetString(PyExc_TypeError, msg.c_str());
762  return {nullptr, nullptr};
763  }
764 
765  const type_info *typeinfo = nullptr;
766  const std::type_info *cpptype = nullptr;
767  void *value = nullptr;
768 };
769 
770 /**
771  * Determine suitable casting operator for pointer-or-lvalue-casting type casters. The type caster
772  * needs to provide `operator T*()` and `operator T&()` operators.
773  *
774  * If the type supports moving the value away via an `operator T&&() &&` method, it should use
775  * `movable_cast_op_type` instead.
776  */
777 template <typename T>
780  typename std::add_pointer<intrinsic_t<T>>::type,
781  typename std::add_lvalue_reference<intrinsic_t<T>>::type>;
782 
783 /**
784  * Determine suitable casting operator for a type caster with a movable value. Such a type caster
785  * needs to provide `operator T*()`, `operator T&()`, and `operator T&&() &&`. The latter will be
786  * called in appropriate contexts where the value can be moved rather than copied.
787  *
788  * These operator are automatically provided when using the PYBIND11_TYPE_CASTER macro.
789  */
790 template <typename T>
793  typename std::add_pointer<intrinsic_t<T>>::type,
795  typename std::add_rvalue_reference<intrinsic_t<T>>::type,
796  typename std::add_lvalue_reference<intrinsic_t<T>>::type>>;
797 
798 // std::is_copy_constructible isn't quite enough: it lets std::vector<T> (and similar) through when
799 // T is non-copyable, but code containing such a copy constructor fails to actually compile.
800 template <typename T, typename SFINAE = void> struct is_copy_constructible : std::is_copy_constructible<T> {};
801 
802 // Specialization for types that appear to be copy constructible but also look like stl containers
803 // (we specifically check for: has `value_type` and `reference` with `reference = value_type&`): if
804 // so, copy constructability depends on whether the value_type is copy constructible.
805 template <typename Container> struct is_copy_constructible<Container, enable_if_t<all_of<
806  std::is_copy_constructible<Container>,
807  std::is_same<typename Container::value_type &, typename Container::reference>,
808  // Avoid infinite recursion
809  negation<std::is_same<Container, typename Container::value_type>>
810  >::value>> : is_copy_constructible<typename Container::value_type> {};
811 
812 // Likewise for std::pair
813 // (after C++17 it is mandatory that the copy constructor not exist when the two types aren't themselves
814 // copy constructible, but this can not be relied upon when T1 or T2 are themselves containers).
815 template <typename T1, typename T2> struct is_copy_constructible<std::pair<T1, T2>>
816  : all_of<is_copy_constructible<T1>, is_copy_constructible<T2>> {};
817 
818 // The same problems arise with std::is_copy_assignable, so we use the same workaround.
819 template <typename T, typename SFINAE = void> struct is_copy_assignable : std::is_copy_assignable<T> {};
820 template <typename Container> struct is_copy_assignable<Container, enable_if_t<all_of<
821  std::is_copy_assignable<Container>,
822  std::is_same<typename Container::value_type &, typename Container::reference>
823  >::value>> : is_copy_assignable<typename Container::value_type> {};
824 template <typename T1, typename T2> struct is_copy_assignable<std::pair<T1, T2>>
825  : all_of<is_copy_assignable<T1>, is_copy_assignable<T2>> {};
826 
828 
829 // polymorphic_type_hook<itype>::get(src, tinfo) determines whether the object pointed
830 // to by `src` actually is an instance of some class derived from `itype`.
831 // If so, it sets `tinfo` to point to the std::type_info representing that derived
832 // type, and returns a pointer to the start of the most-derived object of that type
833 // (in which `src` is a subobject; this will be the same address as `src` in most
834 // single inheritance cases). If not, or if `src` is nullptr, it simply returns `src`
835 // and leaves `tinfo` at its default value of nullptr.
836 //
837 // The default polymorphic_type_hook just returns src. A specialization for polymorphic
838 // types determines the runtime type of the passed object and adjusts the this-pointer
839 // appropriately via dynamic_cast<void*>. This is what enables a C++ Animal* to appear
840 // to Python as a Dog (if Dog inherits from Animal, Animal is polymorphic, Dog is
841 // registered with pybind11, and this Animal is in fact a Dog).
842 //
843 // You may specialize polymorphic_type_hook yourself for types that want to appear
844 // polymorphic to Python but do not use C++ RTTI. (This is a not uncommon pattern
845 // in performance-sensitive applications, used most notably in LLVM.)
846 //
847 // polymorphic_type_hook_base allows users to specialize polymorphic_type_hook with
848 // std::enable_if. User provided specializations will always have higher priority than
849 // the default implementation and specialization provided in polymorphic_type_hook_base.
850 template <typename itype, typename SFINAE = void>
852 {
853  static const void *get(const itype *src, const std::type_info*&) { return src; }
854 };
855 template <typename itype>
856 struct polymorphic_type_hook_base<itype, detail::enable_if_t<std::is_polymorphic<itype>::value>>
857 {
858  static const void *get(const itype *src, const std::type_info*& type) {
859  type = src ? &typeid(*src) : nullptr;
860  return dynamic_cast<const void*>(src);
861  }
862 };
863 template <typename itype, typename SFINAE = void>
865 
867 
868 /// Generic type caster for objects stored on the heap
869 template <typename type> class type_caster_base : public type_caster_generic {
870  using itype = intrinsic_t<type>;
871 
872 public:
873  static constexpr auto name = _<type>();
874 
876  explicit type_caster_base(const std::type_info &info) : type_caster_generic(info) { }
877 
878  static handle cast(const itype &src, return_value_policy policy, handle parent) {
879  if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference)
880  policy = return_value_policy::copy;
881  return cast(&src, policy, parent);
882  }
883 
884  static handle cast(itype &&src, return_value_policy, handle parent) {
885  return cast(&src, return_value_policy::move, parent);
886  }
887 
888  // Returns a (pointer, type_info) pair taking care of necessary type lookup for a
889  // polymorphic type (using RTTI by default, but can be overridden by specializing
890  // polymorphic_type_hook). If the instance isn't derived, returns the base version.
891  static std::pair<const void *, const type_info *> src_and_type(const itype *src) {
892  auto &cast_type = typeid(itype);
893  const std::type_info *instance_type = nullptr;
894  const void *vsrc = polymorphic_type_hook<itype>::get(src, instance_type);
895  if (instance_type && !same_type(cast_type, *instance_type)) {
896  // This is a base pointer to a derived type. If the derived type is registered
897  // with pybind11, we want to make the full derived object available.
898  // In the typical case where itype is polymorphic, we get the correct
899  // derived pointer (which may be != base pointer) by a dynamic_cast to
900  // most derived type. If itype is not polymorphic, we won't get here
901  // except via a user-provided specialization of polymorphic_type_hook,
902  // and the user has promised that no this-pointer adjustment is
903  // required in that case, so it's OK to use static_cast.
904  if (const auto *tpi = get_type_info(*instance_type))
905  return {vsrc, tpi};
906  }
907  // Otherwise we have either a nullptr, an `itype` pointer, or an unknown derived pointer, so
908  // don't do a cast
909  return type_caster_generic::src_and_type(src, cast_type, instance_type);
910  }
911 
912  static handle cast(const itype *src, return_value_policy policy, handle parent) {
913  auto st = src_and_type(src);
915  st.first, policy, parent, st.second,
916  make_copy_constructor(src), make_move_constructor(src));
917  }
918 
919  static handle cast_holder(const itype *src, const void *holder) {
920  auto st = src_and_type(src);
922  st.first, return_value_policy::take_ownership, {}, st.second,
923  nullptr, nullptr, holder);
924  }
925 
926  template <typename T> using cast_op_type = detail::cast_op_type<T>;
927 
928  operator itype*() { return (type *) value; }
929  operator itype&() { if (!value) throw reference_cast_error(); return *((itype *) value); }
930 
931 protected:
932  using Constructor = void *(*)(const void *);
933 
934  /* Only enabled when the types are {copy,move}-constructible *and* when the type
935  does not have a private operator new implementation. */
937  static auto make_copy_constructor(const T *x) -> decltype(new T(*x), Constructor{}) {
938  return [](const void *arg) -> void * {
939  return new T(*reinterpret_cast<const T *>(arg));
940  };
941  }
942 
944  static auto make_move_constructor(const T *x) -> decltype(new T(std::move(*const_cast<T *>(x))), Constructor{}) {
945  return [](const void *arg) -> void * {
946  return new T(std::move(*const_cast<T *>(reinterpret_cast<const T *>(arg))));
947  };
948  }
949 
950  static Constructor make_copy_constructor(...) { return nullptr; }
951  static Constructor make_move_constructor(...) { return nullptr; }
952 };
953 
954 template <typename type, typename SFINAE = void> class type_caster : public type_caster_base<type> { };
955 template <typename type> using make_caster = type_caster<intrinsic_t<type>>;
956 
957 // Shortcut for calling a caster's `cast_op_type` cast operator for casting a type_caster to a T
958 template <typename T> typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) {
959  return caster.operator typename make_caster<T>::template cast_op_type<T>();
960 }
963  return std::move(caster).operator
965 }
966 
967 template <typename type> class type_caster<std::reference_wrapper<type>> {
968 private:
969  using caster_t = make_caster<type>;
970  caster_t subcaster;
971  using reference_t = type&;
972  using subcaster_cast_op_type =
973  typename caster_t::template cast_op_type<reference_t>;
974 
975  static_assert(std::is_same<typename std::remove_const<type>::type &, subcaster_cast_op_type>::value ||
977  "std::reference_wrapper<T> caster requires T to have a caster with an "
978  "`operator T &()` or `operator const T &()`");
979 public:
980  bool load(handle src, bool convert) { return subcaster.load(src, convert); }
981  static constexpr auto name = caster_t::name;
982  static handle cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) {
983  // It is definitely wrong to take ownership of this pointer, so mask that rvp
984  if (policy == return_value_policy::take_ownership || policy == return_value_policy::automatic)
985  policy = return_value_policy::automatic_reference;
986  return caster_t::cast(&src.get(), policy, parent);
987  }
988  template <typename T> using cast_op_type = std::reference_wrapper<type>;
989  operator std::reference_wrapper<type>() { return cast_op<type &>(subcaster); }
990 };
991 
992 #define PYBIND11_TYPE_CASTER(type, py_name) \
993  protected: \
994  type value; \
995  public: \
996  static constexpr auto name = py_name; \
997  template <typename T_, enable_if_t<std::is_same<type, remove_cv_t<T_>>::value, int> = 0> \
998  static handle cast(T_ *src, return_value_policy policy, handle parent) { \
999  if (!src) return none().release(); \
1000  if (policy == return_value_policy::take_ownership) { \
1001  auto h = cast(std::move(*src), policy, parent); delete src; return h; \
1002  } else { \
1003  return cast(*src, policy, parent); \
1004  } \
1005  } \
1006  operator type*() { return &value; } \
1007  operator type&() { return value; } \
1008  operator type&&() && { return std::move(value); } \
1009  template <typename T_> using cast_op_type = pybind11::detail::movable_cast_op_type<T_>
1010 
1011 
1012 template <typename CharT> using is_std_char_type = any_of<
1013  std::is_same<CharT, char>, /* std::string */
1014 #if defined(PYBIND11_HAS_U8STRING)
1015  std::is_same<CharT, char8_t>, /* std::u8string */
1016 #endif
1017  std::is_same<CharT, char16_t>, /* std::u16string */
1018  std::is_same<CharT, char32_t>, /* std::u32string */
1019  std::is_same<CharT, wchar_t> /* std::wstring */
1020 >;
1021 
1022 
1023 template <typename T>
1024 struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_type<T>::value>> {
1025  using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>;
1026  using _py_type_1 = conditional_t<std::is_signed<T>::value, _py_type_0, typename std::make_unsigned<_py_type_0>::type>;
1028 public:
1029 
1030  bool load(handle src, bool convert) {
1031  py_type py_value;
1032 
1033  if (!src)
1034  return false;
1035 
1036 #if !defined(PYPY_VERSION)
1037  auto index_check = [](PyObject *o) { return PyIndex_Check(o); };
1038 #else
1039  // In PyPy 7.3.3, `PyIndex_Check` is implemented by calling `__index__`,
1040  // while CPython only considers the existence of `nb_index`/`__index__`.
1041  auto index_check = [](PyObject *o) { return hasattr(o, "__index__"); };
1042 #endif
1043 
1045  if (convert || PyFloat_Check(src.ptr()))
1046  py_value = (py_type) PyFloat_AsDouble(src.ptr());
1047  else
1048  return false;
1049  } else if (PyFloat_Check(src.ptr())) {
1050  return false;
1051  } else if (!convert && !PYBIND11_LONG_CHECK(src.ptr()) && !index_check(src.ptr())) {
1052  return false;
1053  } else {
1054  handle src_or_index = src;
1055 #if PY_VERSION_HEX < 0x03080000
1056  object index;
1057  if (!PYBIND11_LONG_CHECK(src.ptr())) { // So: index_check(src.ptr())
1058  index = reinterpret_steal<object>(PyNumber_Index(src.ptr()));
1059  if (!index) {
1060  PyErr_Clear();
1061  if (!convert)
1062  return false;
1063  }
1064  else {
1065  src_or_index = index;
1066  }
1067  }
1068 #endif
1070  py_value = as_unsigned<py_type>(src_or_index.ptr());
1071  } else { // signed integer:
1072  py_value = sizeof(T) <= sizeof(long)
1073  ? (py_type) PyLong_AsLong(src_or_index.ptr())
1074  : (py_type) PYBIND11_LONG_AS_LONGLONG(src_or_index.ptr());
1075  }
1076  }
1077 
1078  // Python API reported an error
1079  bool py_err = py_value == (py_type) -1 && PyErr_Occurred();
1080 
1081  // Check to see if the conversion is valid (integers should match exactly)
1082  // Signed/unsigned checks happen elsewhere
1083  if (py_err || (std::is_integral<T>::value && sizeof(py_type) != sizeof(T) && py_value != (py_type) (T) py_value)) {
1084  PyErr_Clear();
1085  if (py_err && convert && PyNumber_Check(src.ptr())) {
1086  auto tmp = reinterpret_steal<object>(std::is_floating_point<T>::value
1087  ? PyNumber_Float(src.ptr())
1088  : PyNumber_Long(src.ptr()));
1089  PyErr_Clear();
1090  return load(tmp, false);
1091  }
1092  return false;
1093  }
1094 
1095  value = (T) py_value;
1096  return true;
1097  }
1098 
1099  template<typename U = T>
1101  cast(U src, return_value_policy /* policy */, handle /* parent */) {
1102  return PyFloat_FromDouble((double) src);
1103  }
1104 
1105  template<typename U = T>
1106  static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value && (sizeof(U) <= sizeof(long)), handle>::type
1107  cast(U src, return_value_policy /* policy */, handle /* parent */) {
1108  return PYBIND11_LONG_FROM_SIGNED((long) src);
1109  }
1110 
1111  template<typename U = T>
1112  static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value && (sizeof(U) <= sizeof(unsigned long)), handle>::type
1113  cast(U src, return_value_policy /* policy */, handle /* parent */) {
1114  return PYBIND11_LONG_FROM_UNSIGNED((unsigned long) src);
1115  }
1116 
1117  template<typename U = T>
1118  static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value && (sizeof(U) > sizeof(long)), handle>::type
1119  cast(U src, return_value_policy /* policy */, handle /* parent */) {
1120  return PyLong_FromLongLong((long long) src);
1121  }
1122 
1123  template<typename U = T>
1124  static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value && (sizeof(U) > sizeof(unsigned long)), handle>::type
1125  cast(U src, return_value_policy /* policy */, handle /* parent */) {
1126  return PyLong_FromUnsignedLongLong((unsigned long long) src);
1127  }
1128 
1130 };
1131 
1132 template<typename T> struct void_caster {
1133 public:
1134  bool load(handle src, bool) {
1135  if (src && src.is_none())
1136  return true;
1137  return false;
1138  }
1139  static handle cast(T, return_value_policy /* policy */, handle /* parent */) {
1140  return none().inc_ref();
1141  }
1143 };
1144 
1145 template <> class type_caster<void_type> : public void_caster<void_type> {};
1146 
1147 template <> class type_caster<void> : public type_caster<void_type> {
1148 public:
1150 
1151  bool load(handle h, bool) {
1152  if (!h) {
1153  return false;
1154  } else if (h.is_none()) {
1155  value = nullptr;
1156  return true;
1157  }
1158 
1159  /* Check if this is a capsule */
1160  if (isinstance<capsule>(h)) {
1161  value = reinterpret_borrow<capsule>(h);
1162  return true;
1163  }
1164 
1165  /* Check if this is a C++ type */
1166  auto &bases = all_type_info((PyTypeObject *) type::handle_of(h).ptr());
1167  if (bases.size() == 1) { // Only allowing loading from a single-value type
1168  value = values_and_holders(reinterpret_cast<instance *>(h.ptr())).begin()->value_ptr();
1169  return true;
1170  }
1171 
1172  /* Fail */
1173  return false;
1174  }
1175 
1176  static handle cast(const void *ptr, return_value_policy /* policy */, handle /* parent */) {
1177  if (ptr)
1178  return capsule(ptr).release();
1179  else
1180  return none().inc_ref();
1181  }
1182 
1183  template <typename T> using cast_op_type = void*&;
1184  operator void *&() { return value; }
1185  static constexpr auto name = _("capsule");
1186 private:
1187  void *value = nullptr;
1188 };
1189 
1190 template <> class type_caster<std::nullptr_t> : public void_caster<std::nullptr_t> { };
1191 
1192 template <> class type_caster<bool> {
1193 public:
1194  bool load(handle src, bool convert) {
1195  if (!src) return false;
1196  else if (src.ptr() == Py_True) { value = true; return true; }
1197  else if (src.ptr() == Py_False) { value = false; return true; }
1198  else if (convert || !strcmp("numpy.bool_", Py_TYPE(src.ptr())->tp_name)) {
1199  // (allow non-implicit conversion for numpy booleans)
1200 
1201  Py_ssize_t res = -1;
1202  if (src.is_none()) {
1203  res = 0; // None is implicitly converted to False
1204  }
1205  #if defined(PYPY_VERSION)
1206  // On PyPy, check that "__bool__" (or "__nonzero__" on Python 2.7) attr exists
1207  else if (hasattr(src, PYBIND11_BOOL_ATTR)) {
1208  res = PyObject_IsTrue(src.ptr());
1209  }
1210  #else
1211  // Alternate approach for CPython: this does the same as the above, but optimized
1212  // using the CPython API so as to avoid an unneeded attribute lookup.
1213  else if (auto tp_as_number = src.ptr()->ob_type->tp_as_number) {
1214  if (PYBIND11_NB_BOOL(tp_as_number)) {
1215  res = (*PYBIND11_NB_BOOL(tp_as_number))(src.ptr());
1216  }
1217  }
1218  #endif
1219  if (res == 0 || res == 1) {
1220  value = (bool) res;
1221  return true;
1222  } else {
1223  PyErr_Clear();
1224  }
1225  }
1226  return false;
1227  }
1228  static handle cast(bool src, return_value_policy /* policy */, handle /* parent */) {
1229  return handle(src ? Py_True : Py_False).inc_ref();
1230  }
1231  PYBIND11_TYPE_CASTER(bool, _("bool"));
1232 };
1233 
1234 // Helper class for UTF-{8,16,32} C++ stl strings:
1235 template <typename StringType, bool IsView = false> struct string_caster {
1236  using CharT = typename StringType::value_type;
1237 
1238  // Simplify life by being able to assume standard char sizes (the standard only guarantees
1239  // minimums, but Python requires exact sizes)
1240  static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1, "Unsupported char size != 1");
1241 #if defined(PYBIND11_HAS_U8STRING)
1242  static_assert(!std::is_same<CharT, char8_t>::value || sizeof(CharT) == 1, "Unsupported char8_t size != 1");
1243 #endif
1244  static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2, "Unsupported char16_t size != 2");
1245  static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4, "Unsupported char32_t size != 4");
1246  // wchar_t can be either 16 bits (Windows) or 32 (everywhere else)
1247  static_assert(!std::is_same<CharT, wchar_t>::value || sizeof(CharT) == 2 || sizeof(CharT) == 4,
1248  "Unsupported wchar_t size != 2/4");
1249  static constexpr size_t UTF_N = 8 * sizeof(CharT);
1250 
1251  bool load(handle src, bool) {
1252 #if PY_MAJOR_VERSION < 3
1253  object temp;
1254 #endif
1255  handle load_src = src;
1256  if (!src) {
1257  return false;
1258  } else if (!PyUnicode_Check(load_src.ptr())) {
1259 #if PY_MAJOR_VERSION >= 3
1260  return load_bytes(load_src);
1261 #else
1263  return load_bytes(load_src);
1264  }
1265 
1266  // The below is a guaranteed failure in Python 3 when PyUnicode_Check returns false
1267  if (!PYBIND11_BYTES_CHECK(load_src.ptr()))
1268  return false;
1269 
1270  temp = reinterpret_steal<object>(PyUnicode_FromObject(load_src.ptr()));
1271  if (!temp) { PyErr_Clear(); return false; }
1272  load_src = temp;
1273 #endif
1274  }
1275 
1276  auto utfNbytes = reinterpret_steal<object>(PyUnicode_AsEncodedString(
1277  load_src.ptr(), UTF_N == 8 ? "utf-8" : UTF_N == 16 ? "utf-16" : "utf-32", nullptr));
1278  if (!utfNbytes) { PyErr_Clear(); return false; }
1279 
1280  const auto *buffer = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
1281  size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.ptr()) / sizeof(CharT);
1282  if (UTF_N > 8) { buffer++; length--; } // Skip BOM for UTF-16/32
1283  value = StringType(buffer, length);
1284 
1285  // If we're loading a string_view we need to keep the encoded Python object alive:
1286  if (IsView)
1288 
1289  return true;
1290  }
1291 
1292  static handle cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) {
1293  const char *buffer = reinterpret_cast<const char *>(src.data());
1294  auto nbytes = ssize_t(src.size() * sizeof(CharT));
1295  handle s = decode_utfN(buffer, nbytes);
1296  if (!s) throw error_already_set();
1297  return s;
1298  }
1299 
1301 
1302 private:
1303  static handle decode_utfN(const char *buffer, ssize_t nbytes) {
1304 #if !defined(PYPY_VERSION)
1305  return
1306  UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr) :
1307  UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr) :
1308  PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);
1309 #else
1310  // PyPy segfaults when on PyUnicode_DecodeUTF16 (and possibly on PyUnicode_DecodeUTF32 as well),
1311  // so bypass the whole thing by just passing the encoding as a string value, which works properly:
1312  return PyUnicode_Decode(buffer, nbytes, UTF_N == 8 ? "utf-8" : UTF_N == 16 ? "utf-16" : "utf-32", nullptr);
1313 #endif
1314  }
1315 
1316  // When loading into a std::string or char*, accept a bytes object as-is (i.e.
1317  // without any encoding/decoding attempt). For other C++ char sizes this is a no-op.
1318  // which supports loading a unicode from a str, doesn't take this path.
1319  template <typename C = CharT>
1320  bool load_bytes(enable_if_t<std::is_same<C, char>::value, handle> src) {
1321  if (PYBIND11_BYTES_CHECK(src.ptr())) {
1322  // We were passed a Python 3 raw bytes; accept it into a std::string or char*
1323  // without any encoding attempt.
1324  const char *bytes = PYBIND11_BYTES_AS_STRING(src.ptr());
1325  if (bytes) {
1326  value = StringType(bytes, (size_t) PYBIND11_BYTES_SIZE(src.ptr()));
1327  return true;
1328  }
1329  }
1330 
1331  return false;
1332  }
1333 
1334  template <typename C = CharT>
1335  bool load_bytes(enable_if_t<!std::is_same<C, char>::value, handle>) { return false; }
1336 };
1337 
1338 template <typename CharT, class Traits, class Allocator>
1339 struct type_caster<std::basic_string<CharT, Traits, Allocator>, enable_if_t<is_std_char_type<CharT>::value>>
1340  : string_caster<std::basic_string<CharT, Traits, Allocator>> {};
1341 
1342 #ifdef PYBIND11_HAS_STRING_VIEW
1343 template <typename CharT, class Traits>
1344 struct type_caster<std::basic_string_view<CharT, Traits>, enable_if_t<is_std_char_type<CharT>::value>>
1345  : string_caster<std::basic_string_view<CharT, Traits>, true> {};
1346 #endif
1347 
1348 // Type caster for C-style strings. We basically use a std::string type caster, but also add the
1349 // ability to use None as a nullptr char* (which the string caster doesn't allow).
1350 template <typename CharT> struct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> {
1351  using StringType = std::basic_string<CharT>;
1354  bool none = false;
1355  CharT one_char = 0;
1356 public:
1357  bool load(handle src, bool convert) {
1358  if (!src) return false;
1359  if (src.is_none()) {
1360  // Defer accepting None to other overloads (if we aren't in convert mode):
1361  if (!convert) return false;
1362  none = true;
1363  return true;
1364  }
1365  return str_caster.load(src, convert);
1366  }
1367 
1368  static handle cast(const CharT *src, return_value_policy policy, handle parent) {
1369  if (src == nullptr) return pybind11::none().inc_ref();
1370  return StringCaster::cast(StringType(src), policy, parent);
1371  }
1372 
1373  static handle cast(CharT src, return_value_policy policy, handle parent) {
1375  handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr);
1376  if (!s) throw error_already_set();
1377  return s;
1378  }
1379  return StringCaster::cast(StringType(1, src), policy, parent);
1380  }
1381 
1382  operator CharT*() { return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str()); }
1383  operator CharT&() {
1384  if (none)
1385  throw value_error("Cannot convert None to a character");
1386 
1387  auto &value = static_cast<StringType &>(str_caster);
1388  size_t str_len = value.size();
1389  if (str_len == 0)
1390  throw value_error("Cannot convert empty string to a character");
1391 
1392  // If we're in UTF-8 mode, we have two possible failures: one for a unicode character that
1393  // is too high, and one for multiple unicode characters (caught later), so we need to figure
1394  // out how long the first encoded character is in bytes to distinguish between these two
1395  // errors. We also allow want to allow unicode characters U+0080 through U+00FF, as those
1396  // can fit into a single char value.
1397  if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) {
1398  auto v0 = static_cast<unsigned char>(value[0]);
1399  size_t char0_bytes = !(v0 & 0x80) ? 1 : // low bits only: 0-127
1400  (v0 & 0xE0) == 0xC0 ? 2 : // 0b110xxxxx - start of 2-byte sequence
1401  (v0 & 0xF0) == 0xE0 ? 3 : // 0b1110xxxx - start of 3-byte sequence
1402  4; // 0b11110xxx - start of 4-byte sequence
1403 
1404  if (char0_bytes == str_len) {
1405  // If we have a 128-255 value, we can decode it into a single char:
1406  if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) { // 0x110000xx 0x10xxxxxx
1407  one_char = static_cast<CharT>(((v0 & 3) << 6) + (static_cast<unsigned char>(value[1]) & 0x3F));
1408  return one_char;
1409  }
1410  // Otherwise we have a single character, but it's > U+00FF
1411  throw value_error("Character code point not in range(0x100)");
1412  }
1413  }
1414 
1415  // UTF-16 is much easier: we can only have a surrogate pair for values above U+FFFF, thus a
1416  // surrogate pair with total length 2 instantly indicates a range error (but not a "your
1417  // string was too long" error).
1418  else if (StringCaster::UTF_N == 16 && str_len == 2) {
1419  one_char = static_cast<CharT>(value[0]);
1420  if (one_char >= 0xD800 && one_char < 0xE000)
1421  throw value_error("Character code point not in range(0x10000)");
1422  }
1423 
1424  if (str_len != 1)
1425  throw value_error("Expected a character, but multi-character string found");
1426 
1427  one_char = value[0];
1428  return one_char;
1429  }
1430 
1431  static constexpr auto name = _(PYBIND11_STRING_NAME);
1432  template <typename _T> using cast_op_type = pybind11::detail::cast_op_type<_T>;
1433 };
1434 
1435 // Base implementation for std::tuple and std::pair
1436 template <template<typename...> class Tuple, typename... Ts> class tuple_caster {
1437  using type = Tuple<Ts...>;
1438  static constexpr auto size = sizeof...(Ts);
1439  using indices = make_index_sequence<size>;
1440 public:
1441 
1442  bool load(handle src, bool convert) {
1443  if (!isinstance<sequence>(src))
1444  return false;
1445  const auto seq = reinterpret_borrow<sequence>(src);
1446  if (seq.size() != size)
1447  return false;
1448  return load_impl(seq, convert, indices{});
1449  }
1450 
1451  template <typename T>
1452  static handle cast(T &&src, return_value_policy policy, handle parent) {
1453  return cast_impl(std::forward<T>(src), policy, parent, indices{});
1454  }
1455 
1456  // copied from the PYBIND11_TYPE_CASTER macro
1457  template <typename T>
1458  static handle cast(T *src, return_value_policy policy, handle parent) {
1459  if (!src) return none().release();
1460  if (policy == return_value_policy::take_ownership) {
1461  auto h = cast(std::move(*src), policy, parent); delete src; return h;
1462  } else {
1463  return cast(*src, policy, parent);
1464  }
1465  }
1466 
1467  static constexpr auto name = _("Tuple[") + concat(make_caster<Ts>::name...) + _("]");
1468 
1469  template <typename T> using cast_op_type = type;
1470 
1471  operator type() & { return implicit_cast(indices{}); }
1472  operator type() && { return std::move(*this).implicit_cast(indices{}); }
1473 
1474 protected:
1475  template <size_t... Is>
1476  type implicit_cast(index_sequence<Is...>) & { return type(cast_op<Ts>(std::get<Is>(subcasters))...); }
1477  template <size_t... Is>
1478  type implicit_cast(index_sequence<Is...>) && { return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...); }
1479 
1480  static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; }
1481 
1482  template <size_t... Is>
1483  bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {
1484 #ifdef __cpp_fold_expressions
1485  if ((... || !std::get<Is>(subcasters).load(seq[Is], convert)))
1486  return false;
1487 #else
1488  for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...})
1489  if (!r)
1490  return false;
1491 #endif
1492  return true;
1493  }
1494 
1495  /* Implementation: Convert a C++ tuple into a Python tuple */
1496  template <typename T, size_t... Is>
1498  std::array<object, size> entries{{
1499  reinterpret_steal<object>(make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...
1500  }};
1501  for (const auto &entry: entries)
1502  if (!entry)
1503  return handle();
1504  tuple result(size);
1505  int counter = 0;
1506  for (auto & entry: entries)
1507  PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());
1508  return result.release();
1509  }
1510 
1511  Tuple<make_caster<Ts>...> subcasters;
1512 };
1513 
1514 template <typename T1, typename T2> class type_caster<std::pair<T1, T2>>
1515  : public tuple_caster<std::pair, T1, T2> {};
1516 
1517 template <typename... Ts> class type_caster<std::tuple<Ts...>>
1518  : public tuple_caster<std::tuple, Ts...> {};
1519 
1520 /// Helper class which abstracts away certain actions. Users can provide specializations for
1521 /// custom holders, but it's only necessary if the type has a non-standard interface.
1522 template <typename T>
1524  static auto get(const T &p) -> decltype(p.get()) { return p.get(); }
1525 };
1526 
1527 /// Type caster for holder types like std::shared_ptr, etc.
1528 /// The SFINAE hook is provided to help work around the current lack of support
1529 /// for smart-pointer interoperability. Please consider it an implementation
1530 /// detail that may change in the future, as formal support for smart-pointer
1531 /// interoperability is added into pybind11.
1532 template <typename type, typename holder_type, typename SFINAE = void>
1534 public:
1536  static_assert(std::is_base_of<base, type_caster<type>>::value,
1537  "Holder classes are only supported for custom types");
1538  using base::base;
1539  using base::cast;
1540  using base::typeinfo;
1541  using base::value;
1542 
1543  bool load(handle src, bool convert) {
1544  return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
1545  }
1546 
1547  explicit operator type*() { return this->value; }
1548  // static_cast works around compiler error with MSVC 17 and CUDA 10.2
1549  // see issue #2180
1550  explicit operator type&() { return *(static_cast<type *>(this->value)); }
1551  explicit operator holder_type*() { return std::addressof(holder); }
1552  explicit operator holder_type&() { return holder; }
1553 
1554  static handle cast(const holder_type &src, return_value_policy, handle) {
1555  const auto *ptr = holder_helper<holder_type>::get(src);
1556  return type_caster_base<type>::cast_holder(ptr, &src);
1557  }
1558 
1559 protected:
1560  friend class type_caster_generic;
1562  if (typeinfo->default_holder)
1563  throw cast_error("Unable to load a custom holder type from a default-holder instance");
1564  }
1565 
1567  if (v_h.holder_constructed()) {
1568  value = v_h.value_ptr();
1569  holder = v_h.template holder<holder_type>();
1570  return true;
1571  } else {
1572  throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
1573 #if defined(NDEBUG)
1574  "(compile in debug mode for type information)");
1575 #else
1576  "of type '" + type_id<holder_type>() + "''");
1577 #endif
1578  }
1579  }
1580 
1582  bool try_implicit_casts(handle, bool) { return false; }
1583 
1585  bool try_implicit_casts(handle src, bool convert) {
1586  for (auto &cast : typeinfo->implicit_casts) {
1587  copyable_holder_caster sub_caster(*cast.first);
1588  if (sub_caster.load(src, convert)) {
1589  value = cast.second(sub_caster.value);
1590  holder = holder_type(sub_caster.holder, (type *) value);
1591  return true;
1592  }
1593  }
1594  return false;
1595  }
1596 
1597  static bool try_direct_conversions(handle) { return false; }
1598 
1599 
1600  holder_type holder;
1601 };
1602 
1603 /// Specialize for the common std::shared_ptr, so users don't need to
1604 template <typename T>
1605 class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> { };
1606 
1607 /// Type caster for holder types like std::unique_ptr.
1608 /// Please consider the SFINAE hook an implementation detail, as explained
1609 /// in the comment for the copyable_holder_caster.
1610 template <typename type, typename holder_type, typename SFINAE = void>
1612  static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value,
1613  "Holder classes are only supported for custom types");
1614 
1615  static handle cast(holder_type &&src, return_value_policy, handle) {
1616  auto *ptr = holder_helper<holder_type>::get(src);
1617  return type_caster_base<type>::cast_holder(ptr, std::addressof(src));
1618  }
1619  static constexpr auto name = type_caster_base<type>::name;
1620 };
1621 
1622 template <typename type, typename deleter>
1623 class type_caster<std::unique_ptr<type, deleter>>
1624  : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> { };
1625 
1626 template <typename type, typename holder_type>
1630 
1631 template <typename T, bool Value = false> struct always_construct_holder { static constexpr bool value = Value; };
1632 
1633 /// Create a specialization for custom holder types (silently ignores std::shared_ptr)
1634 #define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
1635  namespace pybind11 { namespace detail { \
1636  template <typename type> \
1637  struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__> { }; \
1638  template <typename type> \
1639  class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
1640  : public type_caster_holder<type, holder_type> { }; \
1641  }}
1642 
1643 // PYBIND11_DECLARE_HOLDER_TYPE holder types:
1644 template <typename base, typename holder> struct is_holder_type :
1645  std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
1646 // Specialization for always-supported unique_ptr holders:
1647 template <typename base, typename deleter> struct is_holder_type<base, std::unique_ptr<base, deleter>> :
1648  std::true_type {};
1649 
1650 template <typename T> struct handle_type_name { static constexpr auto name = _<T>(); };
1651 template <> struct handle_type_name<bytes> { static constexpr auto name = _(PYBIND11_BYTES_NAME); };
1652 template <> struct handle_type_name<int_> { static constexpr auto name = _("int"); };
1653 template <> struct handle_type_name<iterable> { static constexpr auto name = _("Iterable"); };
1654 template <> struct handle_type_name<iterator> { static constexpr auto name = _("Iterator"); };
1655 template <> struct handle_type_name<none> { static constexpr auto name = _("None"); };
1656 template <> struct handle_type_name<args> { static constexpr auto name = _("*args"); };
1657 template <> struct handle_type_name<kwargs> { static constexpr auto name = _("**kwargs"); };
1658 
1659 template <typename type>
1662  bool load(handle src, bool /* convert */) { value = src; return static_cast<bool>(value); }
1663 
1665  bool load(handle src, bool /* convert */) {
1666 #if PY_MAJOR_VERSION < 3 && !defined(PYBIND11_STR_LEGACY_PERMISSIVE)
1667  // For Python 2, without this implicit conversion, Python code would
1668  // need to be cluttered with six.ensure_text() or similar, only to be
1669  // un-cluttered later after Python 2 support is dropped.
1670  if (std::is_same<T, str>::value && isinstance<bytes>(src)) {
1671  PyObject *str_from_bytes = PyUnicode_FromEncodedObject(src.ptr(), "utf-8", nullptr);
1672  if (!str_from_bytes) throw error_already_set();
1673  value = reinterpret_steal<type>(str_from_bytes);
1674  return true;
1675  }
1676 #endif
1677  if (!isinstance<type>(src))
1678  return false;
1679  value = reinterpret_borrow<type>(src);
1680  return true;
1681  }
1682 
1683  static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
1684  return src.inc_ref();
1685  }
1687 };
1688 
1689 template <typename T>
1691 
1692 // Our conditions for enabling moving are quite restrictive:
1693 // At compile time:
1694 // - T needs to be a non-const, non-pointer, non-reference type
1695 // - type_caster<T>::operator T&() must exist
1696 // - the type must be move constructible (obviously)
1697 // At run-time:
1698 // - if the type is non-copy-constructible, the object must be the sole owner of the type (i.e. it
1699 // must have ref_count() == 1)h
1700 // If any of the above are not satisfied, we fall back to copying.
1701 template <typename T> using move_is_plain_type = satisfies_none_of<T,
1702  std::is_void, std::is_pointer, std::is_reference, std::is_const
1703 >;
1704 template <typename T, typename SFINAE = void> struct move_always : std::false_type {};
1705 template <typename T> struct move_always<T, enable_if_t<all_of<
1706  move_is_plain_type<T>,
1708  std::is_move_constructible<T>,
1709  std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&>
1710 >::value>> : std::true_type {};
1711 template <typename T, typename SFINAE = void> struct move_if_unreferenced : std::false_type {};
1712 template <typename T> struct move_if_unreferenced<T, enable_if_t<all_of<
1713  move_is_plain_type<T>,
1714  negation<move_always<T>>,
1715  std::is_move_constructible<T>,
1716  std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&>
1717 >::value>> : std::true_type {};
1719 
1720 // Detect whether returning a `type` from a cast on type's type_caster is going to result in a
1721 // reference or pointer to a local variable of the type_caster. Basically, only
1722 // non-reference/pointer `type`s and reference/pointers from a type_caster_generic are safe;
1723 // everything else returns a reference/pointer to a local variable.
1724 template <typename type> using cast_is_temporary_value_reference = bool_constant<
1726  !std::is_base_of<type_caster_generic, make_caster<type>>::value &&
1727  !std::is_same<intrinsic_t<type>, void>::value
1728 >;
1729 
1730 // When a value returned from a C++ function is being cast back to Python, we almost always want to
1731 // force `policy = move`, regardless of the return value policy the function/method was declared
1732 // with.
1733 template <typename Return, typename SFINAE = void> struct return_value_policy_override {
1735 };
1736 
1737 template <typename Return> struct return_value_policy_override<Return,
1738  detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
1743  }
1744 };
1745 
1746 // Basic python -> C++ casting; throws if casting fails
1747 template <typename T, typename SFINAE> type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {
1748  if (!conv.load(handle, true)) {
1749 #if defined(NDEBUG)
1750  throw cast_error("Unable to cast Python instance to C++ type (compile in debug mode for details)");
1751 #else
1752  throw cast_error("Unable to cast Python instance of type " +
1753  (std::string) str(type::handle_of(handle)) + " to C++ type '" + type_id<T>() + "'");
1754 #endif
1755  }
1756  return conv;
1757 }
1758 // Wrapper around the above that also constructs and returns a type_caster
1759 template <typename T> make_caster<T> load_type(const handle &handle) {
1760  make_caster<T> conv;
1761  load_type(conv, handle);
1762  return conv;
1763 }
1764 
1765 PYBIND11_NAMESPACE_END(detail)
1766 
1767 // pytype -> C++ type
1769 T cast(const handle &handle) {
1770  using namespace detail;
1772  "Unable to cast type to reference: value is local to type caster");
1773  return cast_op<T>(load_type<T>(handle));
1774 }
1775 
1776 // pytype -> pytype (calls converting constructor)
1778 T cast(const handle &handle) { return T(reinterpret_borrow<object>(handle)); }
1779 
1780 // C++ type -> py::object
1782 object cast(T &&value, return_value_policy policy = return_value_policy::automatic_reference,
1783  handle parent = handle()) {
1784  using no_ref_T = typename std::remove_reference<T>::type;
1785  if (policy == return_value_policy::automatic)
1786  policy = std::is_pointer<no_ref_T>::value ? return_value_policy::take_ownership :
1787  std::is_lvalue_reference<T>::value ? return_value_policy::copy : return_value_policy::move;
1788  else if (policy == return_value_policy::automatic_reference)
1790  std::is_lvalue_reference<T>::value ? return_value_policy::copy : return_value_policy::move;
1791  return reinterpret_steal<object>(detail::make_caster<T>::cast(std::forward<T>(value), policy, parent));
1792 }
1793 
1794 template <typename T> T handle::cast() const { return pybind11::cast<T>(*this); }
1795 template <> inline void handle::cast() const { return; }
1796 
1797 template <typename T>
1799  if (obj.ref_count() > 1)
1800 #if defined(NDEBUG)
1801  throw cast_error("Unable to cast Python instance to C++ rvalue: instance has multiple references"
1802  " (compile in debug mode for details)");
1803 #else
1804  throw cast_error("Unable to move from Python " + (std::string) str(type::handle_of(obj)) +
1805  " instance to C++ " + type_id<T>() + " instance: instance has multiple references");
1806 #endif
1807 
1808  // Move into a temporary and return that, because the reference may be a local value of `conv`
1809  T ret = std::move(detail::load_type<T>(obj).operator T&());
1810  return ret;
1811 }
1812 
1813 // Calling cast() on an rvalue calls pybind11::cast with the object rvalue, which does:
1814 // - If we have to move (because T has no copy constructor), do it. This will fail if the moved
1815 // object has multiple references, but trying to copy will fail to compile.
1816 // - If both movable and copyable, check ref count: if 1, move; otherwise copy
1817 // - Otherwise (not movable), copy.
1818 template <typename T> detail::enable_if_t<detail::move_always<T>::value, T> cast(object &&object) {
1819  return move<T>(std::move(object));
1820 }
1821 template <typename T> detail::enable_if_t<detail::move_if_unreferenced<T>::value, T> cast(object &&object) {
1822  if (object.ref_count() > 1)
1823  return cast<T>(object);
1824  else
1825  return move<T>(std::move(object));
1826 }
1827 template <typename T> detail::enable_if_t<detail::move_never<T>::value, T> cast(object &&object) {
1828  return cast<T>(object);
1829 }
1830 
1831 template <typename T> T object::cast() const & { return pybind11::cast<T>(*this); }
1832 template <typename T> T object::cast() && { return pybind11::cast<T>(std::move(*this)); }
1833 template <> inline void object::cast() const & { return; }
1834 template <> inline void object::cast() && { return; }
1835 
1837 
1838 // Declared in pytypes.h:
1840 object object_or_cast(T &&o) { return pybind11::cast(std::forward<T>(o)); }
1841 
1842 struct override_unused {}; // Placeholder type for the unneeded (and dead code) static variable in the PYBIND11_OVERRIDE_OVERRIDE macro
1843 template <typename ret_type> using override_caster_t = conditional_t<
1845 
1846 // Trampoline use: for reference/pointer types to value-converted values, we do a value cast, then
1847 // store the result in the given variable. For other types, this is a no-op.
1849  return cast_op<T>(load_type(caster, o));
1850 }
1852  pybind11_fail("Internal error: cast_ref fallback invoked"); }
1853 
1854 // Trampoline use: Having a pybind11::cast with an invalid reference type is going to static_assert, even
1855 // though if it's in dead code, so we provide a "trampoline" to pybind11::cast that only does anything in
1856 // cases where pybind11::cast is valid.
1858  return pybind11::cast<T>(std::move(o)); }
1860  pybind11_fail("Internal error: cast_safe fallback invoked"); }
1861 template <> inline void cast_safe<void>(object &&) {}
1862 
1863 PYBIND11_NAMESPACE_END(detail)
1864 
1865 template <return_value_policy policy = return_value_policy::automatic_reference>
1866 tuple make_tuple() { return tuple(0); }
1867 
1868 template <return_value_policy policy = return_value_policy::automatic_reference,
1869  typename... Args> tuple make_tuple(Args&&... args_) {
1870  constexpr size_t size = sizeof...(Args);
1871  std::array<object, size> args {
1872  { reinterpret_steal<object>(detail::make_caster<Args>::cast(
1873  std::forward<Args>(args_), policy, nullptr))... }
1874  };
1875  for (size_t i = 0; i < args.size(); i++) {
1876  if (!args[i]) {
1877 #if defined(NDEBUG)
1878  throw cast_error("make_tuple(): unable to convert arguments to Python object (compile in debug mode for details)");
1879 #else
1880  std::array<std::string, size> argtypes { {type_id<Args>()...} };
1881  throw cast_error("make_tuple(): unable to convert argument of type '" +
1882  argtypes[i] + "' to Python object");
1883 #endif
1884  }
1885  }
1886  tuple result(size);
1887  int counter = 0;
1888  for (auto &arg_value : args)
1889  PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());
1890  return result;
1891 }
1892 
1893 /// \ingroup annotations
1894 /// Annotation for arguments
1895 struct arg {
1896  /// Constructs an argument with the name of the argument; if null or omitted, this is a positional argument.
1897  constexpr explicit arg(const char *name = nullptr) : name(name), flag_noconvert(false), flag_none(true) { }
1898  /// Assign a value to this argument
1899  template <typename T> arg_v operator=(T &&value) const;
1900  /// Indicate that the type should not be converted in the type caster
1901  arg &noconvert(bool flag = true) { flag_noconvert = flag; return *this; }
1902  /// Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args)
1903  arg &none(bool flag = true) { flag_none = flag; return *this; }
1904 
1905  const char *name; ///< If non-null, this is a named kwargs argument
1906  bool flag_noconvert : 1; ///< If set, do not allow conversion (requires a supporting type caster!)
1907  bool flag_none : 1; ///< If set (the default), allow None to be passed to this argument
1908 };
1909 
1910 /// \ingroup annotations
1911 /// Annotation for arguments with values
1912 struct arg_v : arg {
1913 private:
1914  template <typename T>
1915  arg_v(arg &&base, T &&x, const char *descr = nullptr)
1916  : arg(base),
1917  value(reinterpret_steal<object>(
1918  detail::make_caster<T>::cast(x, return_value_policy::automatic, {})
1919  )),
1920  descr(descr)
1921 #if !defined(NDEBUG)
1922  , type(type_id<T>())
1923 #endif
1924  {
1925  // Workaround! See:
1926  // https://github.com/pybind/pybind11/issues/2336
1927  // https://github.com/pybind/pybind11/pull/2685#issuecomment-731286700
1928  if (PyErr_Occurred()) {
1929  PyErr_Clear();
1930  }
1931  }
1932 
1933 public:
1934  /// Direct construction with name, default, and description
1935  template <typename T>
1936  arg_v(const char *name, T &&x, const char *descr = nullptr)
1937  : arg_v(arg(name), std::forward<T>(x), descr) { }
1938 
1939  /// Called internally when invoking `py::arg("a") = value`
1940  template <typename T>
1941  arg_v(const arg &base, T &&x, const char *descr = nullptr)
1942  : arg_v(arg(base), std::forward<T>(x), descr) { }
1943 
1944  /// Same as `arg::noconvert()`, but returns *this as arg_v&, not arg&
1945  arg_v &noconvert(bool flag = true) { arg::noconvert(flag); return *this; }
1946 
1947  /// Same as `arg::nonone()`, but returns *this as arg_v&, not arg&
1948  arg_v &none(bool flag = true) { arg::none(flag); return *this; }
1949 
1950  /// The default value
1951  object value;
1952  /// The (optional) description of the default value
1953  const char *descr;
1954 #if !defined(NDEBUG)
1955  /// The C++ type name of the default value (only available when compiled in debug mode)
1956  std::string type;
1957 #endif
1958 };
1959 
1960 /// \ingroup annotations
1961 /// Annotation indicating that all following arguments are keyword-only; the is the equivalent of an
1962 /// unnamed '*' argument (in Python 3)
1963 struct kw_only {};
1964 
1965 /// \ingroup annotations
1966 /// Annotation indicating that all previous arguments are positional-only; the is the equivalent of an
1967 /// unnamed '/' argument (in Python 3.8)
1968 struct pos_only {};
1969 
1970 template <typename T>
1971 arg_v arg::operator=(T &&value) const { return {std::move(*this), std::forward<T>(value)}; }
1972 
1973 /// Alias for backward compatibility -- to be removed in version 2.0
1974 template <typename /*unused*/> using arg_t = arg_v;
1975 
1976 inline namespace literals {
1977 /** \rst
1978  String literal version of `arg`
1979  \endrst */
1980 constexpr arg operator"" _a(const char *name, size_t) { return arg(name); }
1981 } // namespace literals
1982 
1984 
1985 // forward declaration (definition in attr.h)
1986 struct function_record;
1987 
1988 /// Internal data associated with a single function call
1990  function_call(const function_record &f, handle p); // Implementation in attr.h
1991 
1992  /// The function data:
1994 
1995  /// Arguments passed to the function:
1996  std::vector<handle> args;
1997 
1998  /// The `convert` value the arguments should be loaded with
1999  std::vector<bool> args_convert;
2000 
2001  /// Extra references for the optional `py::args` and/or `py::kwargs` arguments (which, if
2002  /// present, are also in `args` but without a reference).
2004 
2005  /// The parent, if any
2007 
2008  /// If this is a call to an initializer, this argument contains `self`
2010 };
2011 
2012 
2013 /// Helper class which loads arguments for C++ functions called from Python
2014 template <typename... Args>
2016  using indices = make_index_sequence<sizeof...(Args)>;
2017 
2018  template <typename Arg> using argument_is_args = std::is_same<intrinsic_t<Arg>, args>;
2019  template <typename Arg> using argument_is_kwargs = std::is_same<intrinsic_t<Arg>, kwargs>;
2020  // Get args/kwargs argument positions relative to the end of the argument list:
2021  static constexpr auto args_pos = constexpr_first<argument_is_args, Args...>() - (int) sizeof...(Args),
2022  kwargs_pos = constexpr_first<argument_is_kwargs, Args...>() - (int) sizeof...(Args);
2023 
2024  static constexpr bool args_kwargs_are_last = kwargs_pos >= - 1 && args_pos >= kwargs_pos - 1;
2025 
2026  static_assert(args_kwargs_are_last, "py::args/py::kwargs are only permitted as the last argument(s) of a function");
2027 
2028 public:
2029  static constexpr bool has_kwargs = kwargs_pos < 0;
2030  static constexpr bool has_args = args_pos < 0;
2031 
2032  static constexpr auto arg_names = concat(type_descr(make_caster<Args>::name)...);
2033 
2035  return load_impl_sequence(call, indices{});
2036  }
2037 
2038  template <typename Return, typename Guard, typename Func>
2040  return std::move(*this).template call_impl<Return>(std::forward<Func>(f), indices{}, Guard{});
2041  }
2042 
2043  template <typename Return, typename Guard, typename Func>
2045  std::move(*this).template call_impl<Return>(std::forward<Func>(f), indices{}, Guard{});
2046  return void_type();
2047  }
2048 
2049 private:
2050 
2051  static bool load_impl_sequence(function_call &, index_sequence<>) { return true; }
2052 
2053  template <size_t... Is>
2054  bool load_impl_sequence(function_call &call, index_sequence<Is...>) {
2055 #ifdef __cpp_fold_expressions
2056  if ((... || !std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])))
2057  return false;
2058 #else
2059  for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...})
2060  if (!r)
2061  return false;
2062 #endif
2063  return true;
2064  }
2065 
2066  template <typename Return, typename Func, size_t... Is, typename Guard>
2067  Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) && {
2068  return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...);
2069  }
2070 
2071  std::tuple<make_caster<Args>...> argcasters;
2072 };
2073 
2074 /// Helper class which collects only positional arguments for a Python function call.
2075 /// A fancier version below can collect any argument, but this one is optimal for simple calls.
2076 template <return_value_policy policy>
2078 public:
2079  template <typename... Ts>
2080  explicit simple_collector(Ts &&...values)
2081  : m_args(pybind11::make_tuple<policy>(std::forward<Ts>(values)...)) { }
2082 
2083  const tuple &args() const & { return m_args; }
2084  dict kwargs() const { return {}; }
2085 
2086  tuple args() && { return std::move(m_args); }
2087 
2088  /// Call a Python function and pass the collected arguments
2089  object call(PyObject *ptr) const {
2090  PyObject *result = PyObject_CallObject(ptr, m_args.ptr());
2091  if (!result)
2092  throw error_already_set();
2093  return reinterpret_steal<object>(result);
2094  }
2095 
2096 private:
2097  tuple m_args;
2098 };
2099 
2100 /// Helper class which collects positional, keyword, * and ** arguments for a Python function call
2101 template <return_value_policy policy>
2103 public:
2104  template <typename... Ts>
2105  explicit unpacking_collector(Ts &&...values) {
2106  // Tuples aren't (easily) resizable so a list is needed for collection,
2107  // but the actual function call strictly requires a tuple.
2108  auto args_list = list();
2109  int _[] = { 0, (process(args_list, std::forward<Ts>(values)), 0)... };
2110  ignore_unused(_);
2111 
2112  m_args = std::move(args_list);
2113  }
2114 
2115  const tuple &args() const & { return m_args; }
2116  const dict &kwargs() const & { return m_kwargs; }
2117 
2118  tuple args() && { return std::move(m_args); }
2119  dict kwargs() && { return std::move(m_kwargs); }
2120 
2121  /// Call a Python function and pass the collected arguments
2122  object call(PyObject *ptr) const {
2123  PyObject *result = PyObject_Call(ptr, m_args.ptr(), m_kwargs.ptr());
2124  if (!result)
2125  throw error_already_set();
2126  return reinterpret_steal<object>(result);
2127  }
2128 
2129 private:
2130  template <typename T>
2131  void process(list &args_list, T &&x) {
2132  auto o = reinterpret_steal<object>(detail::make_caster<T>::cast(std::forward<T>(x), policy, {}));
2133  if (!o) {
2134 #if defined(NDEBUG)
2135  argument_cast_error();
2136 #else
2137  argument_cast_error(std::to_string(args_list.size()), type_id<T>());
2138 #endif
2139  }
2140  args_list.append(o);
2141  }
2142 
2143  void process(list &args_list, detail::args_proxy ap) {
2144  for (auto a : ap)
2145  args_list.append(a);
2146  }
2147 
2148  void process(list &/*args_list*/, arg_v a) {
2149  if (!a.name)
2150 #if defined(NDEBUG)
2151  nameless_argument_error();
2152 #else
2153  nameless_argument_error(a.type);
2154 #endif
2155 
2156  if (m_kwargs.contains(a.name)) {
2157 #if defined(NDEBUG)
2158  multiple_values_error();
2159 #else
2160  multiple_values_error(a.name);
2161 #endif
2162  }
2163  if (!a.value) {
2164 #if defined(NDEBUG)
2165  argument_cast_error();
2166 #else
2167  argument_cast_error(a.name, a.type);
2168 #endif
2169  }
2170  m_kwargs[a.name] = a.value;
2171  }
2172 
2173  void process(list &/*args_list*/, detail::kwargs_proxy kp) {
2174  if (!kp)
2175  return;
2176  for (auto k : reinterpret_borrow<dict>(kp)) {
2177  if (m_kwargs.contains(k.first)) {
2178 #if defined(NDEBUG)
2179  multiple_values_error();
2180 #else
2181  multiple_values_error(str(k.first));
2182 #endif
2183  }
2184  m_kwargs[k.first] = k.second;
2185  }
2186  }
2187 
2188  [[noreturn]] static void nameless_argument_error() {
2189  throw type_error("Got kwargs without a name; only named arguments "
2190  "may be passed via py::arg() to a python function call. "
2191  "(compile in debug mode for details)");
2192  }
2193  [[noreturn]] static void nameless_argument_error(std::string type) {
2194  throw type_error("Got kwargs without a name of type '" + type + "'; only named "
2195  "arguments may be passed via py::arg() to a python function call. ");
2196  }
2197  [[noreturn]] static void multiple_values_error() {
2198  throw type_error("Got multiple values for keyword argument "
2199  "(compile in debug mode for details)");
2200  }
2201 
2202  [[noreturn]] static void multiple_values_error(std::string name) {
2203  throw type_error("Got multiple values for keyword argument '" + name + "'");
2204  }
2205 
2206  [[noreturn]] static void argument_cast_error() {
2207  throw cast_error("Unable to convert call argument to Python object "
2208  "(compile in debug mode for details)");
2209  }
2210 
2211  [[noreturn]] static void argument_cast_error(std::string name, std::string type) {
2212  throw cast_error("Unable to convert call argument '" + name
2213  + "' of type '" + type + "' to Python object");
2214  }
2215 
2216 private:
2217  tuple m_args;
2218  dict m_kwargs;
2219 };
2220 
2221 // [workaround(intel)] Separate function required here
2222 // We need to put this into a separate function because the Intel compiler
2223 // fails to compile enable_if_t<!all_of<is_positional<Args>...>::value>
2224 // (tested with ICC 2021.1 Beta 20200827).
2225 template <typename... Args>
2226 constexpr bool args_are_all_positional()
2227 {
2229 }
2230 
2231 /// Collect only positional arguments for a Python function call
2232 template <return_value_policy policy, typename... Args,
2233  typename = enable_if_t<args_are_all_positional<Args...>()>>
2235  return simple_collector<policy>(std::forward<Args>(args)...);
2236 }
2237 
2238 /// Collect all arguments, including keywords and unpacking (only instantiated when needed)
2239 template <return_value_policy policy, typename... Args,
2240  typename = enable_if_t<!args_are_all_positional<Args...>()>>
2242  // Following argument order rules for generalized unpacking according to PEP 448
2243  static_assert(
2244  constexpr_last<is_positional, Args...>() < constexpr_first<is_keyword_or_ds, Args...>()
2245  && constexpr_last<is_s_unpacking, Args...>() < constexpr_first<is_ds_unpacking, Args...>(),
2246  "Invalid function call: positional args must precede keywords and ** unpacking; "
2247  "* unpacking must precede ** unpacking"
2248  );
2249  return unpacking_collector<policy>(std::forward<Args>(args)...);
2250 }
2251 
2252 template <typename Derived>
2253 template <return_value_policy policy, typename... Args>
2254 object object_api<Derived>::operator()(Args &&...args) const {
2255  return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
2256 }
2257 
2258 template <typename Derived>
2259 template <return_value_policy policy, typename... Args>
2260 object object_api<Derived>::call(Args &&...args) const {
2261  return operator()<policy>(std::forward<Args>(args)...);
2262 }
2263 
2264 PYBIND11_NAMESPACE_END(detail)
2265 
2266 
2267 template<typename T>
2269  static_assert(
2270  std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value,
2271  "py::type::of<T> only supports the case where T is a registered C++ types."
2272  );
2273 
2274  return detail::get_type_handle(typeid(T), true);
2275 }
2276 
2277 
2278 #define PYBIND11_MAKE_OPAQUE(...) \
2279  namespace pybind11 { namespace detail { \
2280  template<> class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> { }; \
2281  }}
2282 
2283 /// Lets you pass a type containing a `,` through a macro parameter without needing a separate
2284 /// typedef, e.g.: `PYBIND11_OVERRIDE(PYBIND11_TYPE(ReturnType<A, B>), PYBIND11_TYPE(Parent<C, D>), f, arg)`
2285 #define PYBIND11_TYPE(...) __VA_ARGS__
type_caster_base::make_copy_constructor
static auto make_copy_constructor(const T *x) -> decltype(new T(*x), Constructor
Definition: cast.h:937
tuple_caster::cast
static handle cast(T *src, return_value_policy policy, handle parent)
Definition: cast.h:1458
int_
Definition: pytypes.h:1126
enable_if_t
typename std::enable_if< B, T >::type enable_if_t
from cpp_future import (convenient aliases from C++14/17)
Definition: common.h:504
load_type
type_caster< T, SFINAE > & load_type(type_caster< T, SFINAE > &conv, const handle &handle)
Definition: cast.h:1747
test_multiple_inheritance.i
i
Definition: test_multiple_inheritance.py:22
unpacking_collector::args
tuple args() &&
Definition: cast.h:2118
error_scope
RAII wrapper that temporarily clears any Python error state.
Definition: common.h:785
type_caster_generic::try_direct_conversions
bool try_direct_conversions(handle src)
Definition: cast.h:627
PYBIND11_MODULE_LOCAL_ID
#define PYBIND11_MODULE_LOCAL_ID
Definition: internals.h:216
polymorphic_type_hook_base::get
static const void * get(const itype *src, const std::type_info *&)
Definition: cast.h:853
PYBIND11_BYTES_SIZE
#define PYBIND11_BYTES_SIZE
Definition: common.h:221
name
Annotation for function names.
Definition: attr.h:36
return_value_policy_override
Definition: cast.h:1733
function_record
Internal data structure which holds metadata about a bound function (signature, overloads,...
Definition: attr.h:141
type_caster< T, enable_if_t< std::is_arithmetic< T >::value &&!is_std_char_type< T >::value > >::_py_type_1
conditional_t< std::is_signed< T >::value, _py_type_0, typename std::make_unsigned< _py_type_0 >::type > _py_type_1
Definition: cast.h:1026
type_caster_base::cast
static handle cast(itype &&src, return_value_policy, handle parent)
Definition: cast.h:884
cast
T cast(const handle &handle)
Definition: cast.h:1769
PYBIND11_NAMESPACE_BEGIN
#define PYBIND11_NAMESPACE_BEGIN(name)
Definition: common.h:16
string_caster::UTF_N
static constexpr size_t UTF_N
Definition: cast.h:1249
type_info::module_local_load
void *(* module_local_load)(PyObject *, const type_info *)
Definition: internals.h:140
value_and_holder::value_and_holder
value_and_holder(size_t index)
Definition: cast.h:239
base
Annotation indicating that a class derives from another given type.
Definition: attr.h:42
type_caster_base< T >::Constructor
void *(*)(const void *) Constructor
Definition: cast.h:932
bytes
Definition: pytypes.h:1013
type_caster< void >::cast
static handle cast(const void *ptr, return_value_policy, handle)
Definition: cast.h:1176
test_builtin_casters.x
x
Definition: test_builtin_casters.py:467
PYBIND11_NAMESPACE_END
#define PYBIND11_NAMESPACE_END(name)
Definition: common.h:17
ignore_unused
void ignore_unused(const int *)
Ignore that a variable is unused in compiler warnings.
Definition: common.h:712
get_thread_state_unchecked
PyThreadState * get_thread_state_unchecked()
Definition: cast.h:482
index_sequence
Index sequences.
Definition: common.h:515
argument_loader::load_args
bool load_args(function_call &call)
Definition: cast.h:2034
arg::arg
constexpr arg(const char *name=nullptr)
Constructs an argument with the name of the argument; if null or omitted, this is a positional argume...
Definition: cast.h:1897
instance::simple_layout
bool simple_layout
Definition: common.h:471
type_caster< bool >::cast
static handle cast(bool src, return_value_policy, handle)
Definition: cast.h:1228
scope
Annotation for parent scope.
Definition: attr.h:30
error_already_set
Definition: pytypes.h:326
type_info
Definition: internals.h:128
kwargs
Definition: pytypes.h:1367
PYBIND11_NAMESPACE
#define PYBIND11_NAMESPACE
Definition: common.h:26
type_caster< CharT, enable_if_t< is_std_char_type< CharT >::value > >::cast
static handle cast(const CharT *src, return_value_policy policy, handle parent)
Definition: cast.h:1368
space
Definition: mesh.h:18
tuple_caster
Definition: cast.h:1436
instance::nonsimple
nonsimple_values_and_holders nonsimple
Definition: common.h:442
type_info::simple_type
bool simple_type
Definition: internals.h:143
value_and_holder::index
size_t index
Definition: cast.h:225
void_caster::load
bool load(handle src, bool)
Definition: cast.h:1134
list
Definition: pytypes.h:1345
type_info::type
PyTypeObject * type
Definition: internals.h:129
loader_life_support::loader_life_support
loader_life_support()
A new patient frame is created when a function is entered.
Definition: cast.h:47
internals::registered_types_cpp
type_map< type_info * > registered_types_cpp
Definition: internals.h:97
internals::loader_patient_stack
std::vector< PyObject * > loader_patient_stack
Definition: internals.h:105
instance::get_value_and_holder
value_and_holder get_value_and_holder(const type_info *find_type=nullptr, bool throw_if_missing=true)
Definition: cast.h:339
cast_safe< void >
void cast_safe< void >(object &&)
Definition: cast.h:1861
copyable_holder_caster::cast
static handle cast(const holder_type &src, return_value_policy, handle)
Definition: cast.h:1554
object_api
Definition: pytypes.h:55
instance::status_instance_registered
static constexpr uint8_t status_instance_registered
Definition: common.h:492
type_caster_generic::value
void * value
Definition: cast.h:767
clean_type_id
PYBIND11_NOINLINE void clean_type_id(std::string &name)
Definition: typeid.h:32
type_caster< T, enable_if_t< std::is_arithmetic< T >::value &&!is_std_char_type< T >::value > >::cast
static std::enable_if<!std::is_floating_point< U >::value &&std::is_unsigned< U >::value &&(sizeof(U) > sizeof(unsigned long)), handle >::type cast(U src, return_value_policy, handle)
Definition: cast.h:1125
PYBIND11_BYTES_AS_STRING
#define PYBIND11_BYTES_AS_STRING
Definition: common.h:220
type_caster< T, enable_if_t< std::is_arithmetic< T >::value &&!is_std_char_type< T >::value > >::py_type
conditional_t< std::is_floating_point< T >::value, double, _py_type_1 > py_type
Definition: cast.h:1027
PYBIND11_BYTES_CHECK
#define PYBIND11_BYTES_CHECK
Definition: common.h:216
literals
Definition: cast.h:1976
argument_loader::call
enable_if_t<!std::is_void< Return >::value, Return > call(Func &&f) &&
Definition: cast.h:2039
handle::inc_ref
const handle & inc_ref() const &
Definition: pytypes.h:192
function_call::func
const function_record & func
The function data:
Definition: cast.h:1993
type_info::default_holder
bool default_holder
Definition: internals.h:147
values_and_holders::begin
iterator begin()
Definition: cast.h:317
PYBIND11_NOINLINE
#define PYBIND11_NOINLINE
Definition: common.h:88
values_and_holders::iterator::operator++
iterator & operator++()
Definition: cast.h:306
simple_collector::args
tuple args() &&
Definition: cast.h:2086
bool_constant
std::integral_constant< bool, B > bool_constant
Backports of std::bool_constant and std::negation to accommodate older compilers.
Definition: common.h:528
hasattr
bool hasattr(handle obj, handle name)
Definition: pytypes.h:405
type_caster_generic::type_caster_generic
PYBIND11_NOINLINE type_caster_generic(const std::type_info &type_info)
Definition: cast.h:502
internals::registered_instances
std::unordered_multimap< const void *, instance * > registered_instances
Definition: internals.h:99
capsule
Definition: pytypes.h:1211
type_info::implicit_conversions
std::vector< PyObject *(*)(PyObject *, PyTypeObject *)> implicit_conversions
Definition: internals.h:135
internals.h
move_only_holder_caster::cast
static handle cast(holder_type &&src, return_value_policy, handle)
Definition: cast.h:1615
PYBIND11_LONG_FROM_SIGNED
#define PYBIND11_LONG_FROM_SIGNED(o)
Definition: common.h:224
all_of
std::is_same< bools< Ts::value..., true >, bools< true, Ts::value... > > all_of
Definition: common.h:550
void_caster
Definition: cast.h:1132
type
Definition: pytypes.h:915
keep_alive_impl
void keep_alive_impl(handle nurse, handle patient)
Definition: pybind11.h:1819
_
constexpr descr< N - 1 > _(char const(&text)[N])
Definition: descr.h:54
getattr
object getattr(handle obj, handle name)
Definition: pytypes.h:421
type_caster< T, enable_if_t< std::is_arithmetic< T >::value &&!is_std_char_type< T >::value > >::_py_type_0
conditional_t< sizeof(T)<=sizeof(long), long, long long > _py_type_0
Definition: cast.h:1025
move_always
Definition: cast.h:1704
value_and_holder
Definition: cast.h:223
object_api::operator()
object operator()(Args &&...args) const
Definition: cast.h:2254
argument_loader::arg_names
static constexpr auto arg_names
Definition: cast.h:2032
type_caster_base::make_move_constructor
static Constructor make_move_constructor(...)
Definition: cast.h:951
cast_ref
enable_if_t< cast_is_temporary_value_reference< T >::value, T > cast_ref(object &&o, make_caster< T > &caster)
Definition: cast.h:1848
function_call::function_call
function_call(const function_record &f, handle p)
Definition: attr.h:308
type_caster_base< T >::cast_op_type
detail::cast_op_type< T > cast_op_type
Definition: cast.h:926
is_holder_type
Definition: cast.h:1645
type_caster_base::make_copy_constructor
static Constructor make_copy_constructor(...)
Definition: cast.h:950
buffer
Definition: pytypes.h:1403
nonsimple_values_and_holders::values_and_holders
void ** values_and_holders
Definition: common.h:432
get_internals
PYBIND11_NOINLINE internals & get_internals()
Return a reference to the current internals data.
Definition: internals.h:256
collect_arguments
simple_collector< policy > collect_arguments(Args &&...args)
Collect only positional arguments for a Python function call.
Definition: cast.h:2234
iterator
Definition: pytypes.h:854
is_copy_assignable
Definition: cast.h:819
instance::simple_value_holder
void * simple_value_holder[1+instance_simple_holder_in_ptrs()]
Definition: common.h:441
type_caster_base::src_and_type
static std::pair< const void *, const type_info * > src_and_type(const itype *src)
Definition: cast.h:891
PYBIND11_LONG_FROM_UNSIGNED
#define PYBIND11_LONG_FROM_UNSIGNED(o)
Definition: common.h:225
type_caster_base::make_move_constructor
static auto make_move_constructor(const T *x) -> decltype(new T(std::move(*const_cast< T * >(x))), Constructor
Definition: cast.h:944
arg::operator=
arg_v operator=(T &&value) const
Assign a value to this argument.
Definition: cast.h:1971
nonsimple_values_and_holders::status
uint8_t * status
Definition: common.h:433
always_construct_holder
Definition: cast.h:1631
type_caster_generic::try_implicit_casts
bool try_implicit_casts(handle src, bool convert)
Definition: cast.h:617
values_and_holders::iterator::operator!=
bool operator!=(const iterator &other) const
Definition: cast.h:305
type_info::cpptype
const std::type_info * cpptype
Definition: internals.h:130
tuple_caster::cast_impl
static handle cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence< Is... >)
Definition: cast.h:1497
descr
Definition: descr.h:25
type_caster< std::reference_wrapper< type > >::cast_op_type
std::reference_wrapper< type > cast_op_type
Definition: cast.h:988
string_caster::cast
static handle cast(const StringType &src, return_value_policy, handle)
Definition: cast.h:1292
argument_loader::call
enable_if_t< std::is_void< Return >::value, void_type > call(Func &&f) &&
Definition: cast.h:2044
conditional_t
typename std::conditional< B, T, F >::type conditional_t
Definition: common.h:505
copyable_holder_caster::try_direct_conversions
static bool try_direct_conversions(handle)
Definition: cast.h:1597
tuple_caster::implicit_cast
type implicit_cast(index_sequence< Is... >) &&
Definition: cast.h:1478
function_call::parent
handle parent
The parent, if any.
Definition: cast.h:2006
instance::allocate_layout
void allocate_layout()
Initializes all of the above type/values/holders data (but not the instance values themselves)
Definition: cast.h:363
find_registered_python_instance
PYBIND11_NOINLINE handle find_registered_python_instance(void *src, const detail::type_info *tinfo)
Definition: cast.h:211
tuple_caster< std::pair, T1, T2 >::cast_op_type
type cast_op_type
Definition: cast.h:1469
error_string
PYBIND11_NOINLINE std::string error_string()
Definition: cast.h:423
type_caster< CharT, enable_if_t< is_std_char_type< CharT >::value > >::load
bool load(handle src, bool convert)
Definition: cast.h:1357
instance
The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
Definition: common.h:437
function_call
Internal data associated with a single function call.
Definition: cast.h:1989
type_caster_generic::load_value
void load_value(value_and_holder &&v_h)
Definition: cast.h:598
type_caster< std::reference_wrapper< type > >::load
bool load(handle src, bool convert)
Definition: cast.h:980
override_unused
Definition: cast.h:1842
simple_collector::simple_collector
simple_collector(Ts &&...values)
Definition: cast.h:2080
type_caster< T, enable_if_t< std::is_arithmetic< T >::value &&!is_std_char_type< T >::value > >::cast
static std::enable_if<!std::is_floating_point< U >::value &&std::is_unsigned< U >::value &&(sizeof(U)<=sizeof(unsigned long)), handle >::type cast(U src, return_value_policy, handle)
Definition: cast.h:1113
values_and_holders::find
iterator find(const type_info *find_type)
Definition: cast.h:320
arg_v::type
std::string type
The C++ type name of the default value (only available when compiled in debug mode)
Definition: cast.h:1956
always_construct_holder::value
static constexpr bool value
Definition: cast.h:1631
type_caster_base::cast
static handle cast(const itype &src, return_value_policy policy, handle parent)
Definition: cast.h:878
value_and_holder::set_instance_registered
void set_instance_registered(bool v=true)
Definition: cast.h:268
value_and_holder::set_holder_constructed
void set_holder_constructed(bool v=true)
Definition: cast.h:255
same_type
bool same_type(const std::type_info &lhs, const std::type_info &rhs)
Definition: internals.h:61
copyable_holder_caster::check_holder_compat
void check_holder_compat()
Definition: cast.h:1561
registered_local_types_cpp
type_map< type_info * > & registered_local_types_cpp()
Works like internals.registered_types_cpp, but for module-local registered types:
Definition: internals.h:315
list::size
size_t size() const
Definition: pytypes.h:1351
simple_collector::call
object call(PyObject *ptr) const
Call a Python function and pass the collected arguments.
Definition: cast.h:2089
arg::name
const char * name
If non-null, this is a named kwargs argument.
Definition: cast.h:1905
simple_collector::args
const tuple & args() const &
Definition: cast.h:2083
pyobject_caster::PYBIND11_TYPE_CASTER
PYBIND11_TYPE_CASTER(type, handle_type_name< type >::name)
dict
Definition: pytypes.h:1299
arg_v::arg_v
arg_v(const char *name, T &&x, const char *descr=nullptr)
Direct construction with name, default, and description.
Definition: cast.h:1936
get_fully_qualified_tp_name
std::string get_fully_qualified_tp_name(PyTypeObject *type)
Definition: class.h:27
value_and_holder::vh
void ** vh
Definition: cast.h:227
isinstance
bool isinstance(handle obj)
Definition: pytypes.h:386
tuple_caster::load
bool load(handle src, bool convert)
Definition: cast.h:1442
handle
Definition: pytypes.h:176
type_caster
Definition: cast.h:954
type_caster_base::type_caster_base
type_caster_base(const std::type_info &info)
Definition: cast.h:876
sequence
Definition: pytypes.h:1329
handle::cast
T cast() const
Definition: cast.h:1794
arg_v::value
object value
The default value.
Definition: cast.h:1951
type::handle_of
static handle handle_of()
Definition: cast.h:2268
make_tuple
tuple make_tuple()
Definition: cast.h:1866
function_call::init_self
handle init_self
If this is a call to an initializer, this argument contains self
Definition: cast.h:2009
make_new_instance
PyObject * make_new_instance(PyTypeObject *type)
Definition: class.h:329
arg_v
Definition: cast.h:1912
type_caster< CharT, enable_if_t< is_std_char_type< CharT >::value > >::StringType
std::basic_string< CharT > StringType
Definition: cast.h:1351
value_and_holder::inst
instance * inst
Definition: cast.h:224
polymorphic_type_hook
Definition: cast.h:864
return_value_policy_override::policy
static return_value_policy policy(return_value_policy p)
Definition: cast.h:1734
get_object_handle
PYBIND11_NOINLINE handle get_object_handle(const void *ptr, const detail::type_info *type)
Definition: cast.h:470
object::release
handle release()
Definition: pytypes.h:249
return_value_policy_override< Return, detail::enable_if_t< std::is_base_of< type_caster_generic, make_caster< Return > >::value, void > >::policy
static return_value_policy policy(return_value_policy p)
Definition: cast.h:1739
values_and_holders::iterator::operator*
value_and_holder & operator*()
Definition: cast.h:313
void_caster::cast
static handle cast(T, return_value_policy, handle)
Definition: cast.h:1139
arg::flag_noconvert
bool flag_noconvert
If set, do not allow conversion (requires a supporting type caster!)
Definition: cast.h:1906
typeid.h
value_and_holder::value_and_holder
value_and_holder(instance *i, const detail::type_info *type, size_t vpos, size_t index)
Definition: cast.h:230
type_caster_generic::load_impl
PYBIND11_NOINLINE bool load_impl(handle src, bool convert)
Definition: cast.h:668
get_type_handle
PYBIND11_NOINLINE handle get_type_handle(const std::type_info &tp, bool throw_if_missing)
Definition: cast.h:205
instance::simple_instance_registered
bool simple_instance_registered
For simple layout, tracks whether the instance is registered in registered_instances
Definition: common.h:475
copyable_holder_caster::load
bool load(handle src, bool convert)
Definition: cast.h:1543
instance::deallocate_layout
void deallocate_layout()
Destroys/deallocates all of the above.
Definition: cast.h:411
PYBIND11_NB_BOOL
#define PYBIND11_NB_BOOL(ptr)
Definition: common.h:232
arg
Definition: cast.h:1895
type_caster< T, enable_if_t< std::is_arithmetic< T >::value &&!is_std_char_type< T >::value > >::PYBIND11_TYPE_CASTER
PYBIND11_TYPE_CASTER(T, _< std::is_integral< T >::value >("int", "float"))
intrinsic_t
typename intrinsic_type< T >::type intrinsic_t
Definition: common.h:577
string_caster
Definition: cast.h:1235
tuple_caster::subcasters
Tuple< make_caster< Ts >... > subcasters
Definition: cast.h:1511
unpacking_collector::kwargs
dict kwargs() &&
Definition: cast.h:2119
negation
Definition: common.h:529
pyobject_caster::load
bool load(handle src, bool)
Definition: cast.h:1662
arg::flag_none
bool flag_none
If set (the default), allow None to be passed to this argument.
Definition: cast.h:1907
policy
Definition: policy.py:1
unpacking_collector::unpacking_collector
unpacking_collector(Ts &&...values)
Definition: cast.h:2105
unpacking_collector::kwargs
const dict & kwargs() const &
Definition: cast.h:2116
constexpr_first
constexpr int constexpr_first()
Definition: common.h:608
string_caster::PYBIND11_TYPE_CASTER
PYBIND11_TYPE_CASTER(StringType, _(PYBIND11_STRING_NAME))
type_caster< T, enable_if_t< std::is_arithmetic< T >::value &&!is_std_char_type< T >::value > >::cast
static std::enable_if< std::is_floating_point< U >::value, handle >::type cast(U src, return_value_policy, handle)
Definition: cast.h:1101
holder_helper
Definition: cast.h:1523
instance::owned
bool owned
If true, the pointer is owned which means we're free to manage it with a holder.
Definition: common.h:447
is_copy_constructible
Definition: cast.h:800
ssize_t
Py_ssize_t ssize_t
Definition: common.h:353
move_if_unreferenced
Definition: cast.h:1711
concat
constexpr descr< 0 > concat()
Definition: descr.h:83
pyobject_caster
Definition: cast.h:1660
instance::status_holder_constructed
static constexpr uint8_t status_holder_constructed
Bit values for the non-simple status flags.
Definition: common.h:491
simple_collector
Definition: cast.h:2077
kw_only
Definition: cast.h:1963
test_numpy_dtypes.scope
scope
Definition: test_numpy_dtypes.py:13
value_and_holder::value_ptr
V *& value_ptr() const
Definition: cast.h:241
type_caster< void >::load
bool load(handle h, bool)
Definition: cast.h:1151
size_t
std::size_t size_t
Definition: common.h:354
function_call::args_ref
object args_ref
Definition: cast.h:2003
values_and_holders::iterator
Definition: cast.h:288
type_caster< T, enable_if_t< std::is_arithmetic< T >::value &&!is_std_char_type< T >::value > >::load
bool load(handle src, bool convert)
Definition: cast.h:1030
copyable_holder_caster::cast
static handle cast(const itype &src, return_value_policy policy, handle parent)
Definition: cast.h:878
type_info::direct_conversions
std::vector< bool(*)(PyObject *, void *&)> * direct_conversions
Definition: internals.h:137
arg_v::noconvert
arg_v & noconvert(bool flag=true)
Same as arg::noconvert(), but returns *this as arg_v&, not arg&.
Definition: cast.h:1945
type_descr
constexpr descr< N+2, Ts... > type_descr(const descr< N, Ts... > &descr)
Definition: descr.h:95
cast_safe
enable_if_t<!cast_is_temporary_value_reference< T >::value, T > cast_safe(object &&o)
Definition: cast.h:1857
override_caster_t
conditional_t< cast_is_temporary_value_reference< ret_type >::value, make_caster< ret_type >, override_unused > override_caster_t
Definition: cast.h:1844
pytypes.h
descr.h
type_caster_generic
Definition: cast.h:500
pybind11_fail
PyExc_RuntimeError PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
Definition: common.h:751
str
Definition: pytypes.h:946
PYBIND11_LONG_AS_LONGLONG
#define PYBIND11_LONG_AS_LONGLONG(o)
Definition: common.h:223
copyable_holder_caster::load_value
bool load_value(value_and_holder &&v_h)
Definition: cast.h:1566
PYBIND11_BOOL_ATTR
#define PYBIND11_BOOL_ATTR
Definition: common.h:231
type_caster< std::reference_wrapper< type > >::cast
static handle cast(const std::reference_wrapper< type > &src, return_value_policy policy, handle parent)
Definition: cast.h:982
type_info::implicit_casts
std::vector< std::pair< const std::type_info *, void *(*)(void *)> > implicit_casts
Definition: internals.h:136
arg::none
arg & none(bool flag=true)
Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args)
Definition: cast.h:1903
unpacking_collector
Helper class which collects positional, keyword, * and ** arguments for a Python function call.
Definition: cast.h:2102
arg_v::descr
const char * descr
The (optional) description of the default value.
Definition: cast.h:1953
move
detail::enable_if_t<!detail::move_never< T >::value, T > move(object &&obj)
Definition: cast.h:1798
instance_simple_holder_in_ptrs
constexpr size_t instance_simple_holder_in_ptrs()
Definition: common.h:421
list::append
void append(T &&val) const
Definition: pytypes.h:1357
copyable_holder_caster::holder
holder_type holder
Definition: cast.h:1600
dict::contains
bool contains(T &&key) const
Definition: pytypes.h:1316
type_caster_generic::local_load
static PYBIND11_NOINLINE void * local_load(PyObject *src, const type_info *ti)
Definition: cast.h:636
handle_type_name
Definition: cast.h:1650
handle::ptr
PyObject * ptr() const
Return the underlying PyObject * pointer.
Definition: pytypes.h:184
tuple::size
size_t size() const
Definition: pytypes.h:1282
loader_life_support::~loader_life_support
~loader_life_support()
... and destroyed after it returns
Definition: cast.h:52
benchmark.size
size
Definition: benchmark.py:90
type_caster_generic::src_and_type
static PYBIND11_NOINLINE std::pair< const void *, const type_info * > src_and_type(const void *src, const std::type_info &cast_type, const std::type_info *rtti_type=nullptr)
Definition: cast.h:752
value_and_holder::value_and_holder
value_and_holder()=default
instance::simple_holder_constructed
bool simple_holder_constructed
For simple layout, tracks whether the holder has been constructed.
Definition: common.h:473
type_caster_generic::check_holder_compat
void check_holder_compat()
Definition: cast.h:634
tuple_caster::load_impl
static constexpr bool load_impl(const sequence &, bool, index_sequence<>)
Definition: cast.h:1480
type_caster_holder
conditional_t< is_copy_constructible< holder_type >::value, copyable_holder_caster< type, holder_type >, move_only_holder_caster< type, holder_type > > type_caster_holder
Definition: cast.h:1629
make_index_sequence
typename make_index_sequence_impl< N >::type make_index_sequence
Definition: common.h:518
argument_loader
Helper class which loads arguments for C++ functions called from Python.
Definition: cast.h:2015
iterable
Definition: pytypes.h:939
copyable_holder_caster::try_implicit_casts
bool try_implicit_casts(handle, bool)
Definition: cast.h:1582
value_and_holder::instance_registered
bool instance_registered() const
Definition: cast.h:263
void_type
Helper type to replace 'void' in some expressions.
Definition: common.h:580
value_and_holder::holder
H & holder() const
Definition: cast.h:247
all_type_info_populate
PYBIND11_NOINLINE void all_type_info_populate(PyTypeObject *t, std::vector< type_info * > &bases)
Definition: cast.h:95
args
Definition: pytypes.h:1366
type_caster< CharT, enable_if_t< is_std_char_type< CharT >::value > >::str_caster
StringCaster str_caster
Definition: cast.h:1353
value_and_holder::holder_constructed
bool holder_constructed() const
Definition: cast.h:250
type_caster< void >::cast_op_type
void *& cast_op_type
Definition: cast.h:1183
base::base
base()
Definition: attr.h:45
unpacking_collector::call
object call(PyObject *ptr) const
Call a Python function and pass the collected arguments.
Definition: cast.h:2122
move_only_holder_caster
Definition: cast.h:1611
return_value_policy
return_value_policy
Approach used to cast a previously unknown C++ instance into a Python object.
Definition: common.h:357
type_caster< T, enable_if_t< std::is_arithmetic< T >::value &&!is_std_char_type< T >::value > >::cast
static std::enable_if<!std::is_floating_point< U >::value &&std::is_signed< U >::value &&(sizeof(U)<=sizeof(long)), handle >::type cast(U src, return_value_policy, handle)
Definition: cast.h:1107
c_str
const char * c_str(Args &&...args)
Definition: internals.h:325
holder_helper::get
static auto get(const T &p) -> decltype(p.get())
Definition: cast.h:1524
tuple
Definition: pytypes.h:1276
type_info::module_local
bool module_local
Definition: internals.h:149
is_pyobject
std::is_base_of< pyobject_tag, remove_reference_t< T > > is_pyobject
Definition: pytypes.h:48
values_and_holders::size
size_t size()
Definition: cast.h:326
tuple_caster::load_impl
bool load_impl(const sequence &seq, bool convert, index_sequence< Is... >)
Definition: cast.h:1483
type_caster_generic::try_load_foreign_module_local
PYBIND11_NOINLINE bool try_load_foreign_module_local(handle src)
Definition: cast.h:645
cast_op
make_caster< T >::template cast_op_type< T > cast_op(make_caster< T > &caster)
Definition: cast.h:958
pos_only
Definition: cast.h:1968
pybind11
Definition: __init__.py:1
PYBIND11_BYTES_NAME
#define PYBIND11_BYTES_NAME
Definition: common.h:226
return_value_policy::move
@ move
internals::registered_types_py
std::unordered_map< PyTypeObject *, std::vector< type_info * > > registered_types_py
Definition: internals.h:98
cast_op_type
conditional_t< std::is_pointer< remove_reference_t< T > >::value, typename std::add_pointer< intrinsic_t< T > >::type, typename std::add_lvalue_reference< intrinsic_t< T > >::type > cast_op_type
Definition: cast.h:781
type_caster< bool >::load
bool load(handle src, bool convert)
Definition: cast.h:1194
type_caster_generic::cpptype
const std::type_info * cpptype
Definition: cast.h:766
type_caster_generic::typeinfo
const type_info * typeinfo
Definition: cast.h:765
type_caster_generic::load
bool load(handle src, bool convert)
Definition: cast.h:508
function_call::args
std::vector< handle > args
Arguments passed to the function:
Definition: cast.h:1996
type_caster_base::cast
static handle cast(const itype *src, return_value_policy policy, handle parent)
Definition: cast.h:912
object_or_cast
object object_or_cast(T &&o)
Definition: cast.h:1840
type_caster_base::cast_holder
static handle cast_holder(const itype *src, const void *holder)
Definition: cast.h:919
pyobject_caster::cast
static handle cast(const handle &src, return_value_policy, handle)
Definition: cast.h:1683
type_caster< CharT, enable_if_t< is_std_char_type< CharT >::value > >::cast_op_type
pybind11::detail::cast_op_type< _T > cast_op_type
Definition: cast.h:1432
all_type_info_get_cache
std::pair< decltype(internals::registered_types_py)::iterator, bool > all_type_info_get_cache(PyTypeObject *type)
Definition: pybind11.h:1860
type_caster_generic::cast
static PYBIND11_NOINLINE handle cast(const void *_src, return_value_policy policy, handle parent, const detail::type_info *tinfo, void *(*copy_constructor)(const void *), void *(*move_constructor)(const void *), const void *existing_holder=nullptr)
Definition: cast.h:512
polymorphic_type_hook_base
Definition: cast.h:852
movable_cast_op_type
conditional_t< std::is_pointer< typename std::remove_reference< T >::type >::value, typename std::add_pointer< intrinsic_t< T > >::type, conditional_t< std::is_rvalue_reference< T >::value, typename std::add_rvalue_reference< intrinsic_t< T > >::type, typename std::add_lvalue_reference< intrinsic_t< T > >::type > > movable_cast_op_type
Definition: cast.h:796
argument_loader::has_args
static constexpr bool has_args
Definition: cast.h:2030
copyable_holder_caster
Definition: cast.h:1533
scope::value
handle value
Definition: attr.h:30
void_caster::PYBIND11_TYPE_CASTER
PYBIND11_TYPE_CASTER(T, _("None"))
values_and_holders::values_and_holders
values_and_holders(instance *inst)
Definition: cast.h:286
simple_collector::kwargs
dict kwargs() const
Definition: cast.h:2084
PYBIND11_LONG_CHECK
#define PYBIND11_LONG_CHECK(o)
Definition: common.h:222
none
Definition: pytypes.h:1075
arg::noconvert
arg & noconvert(bool flag=true)
Indicate that the type should not be converted in the type caster.
Definition: cast.h:1901
loader_life_support
Definition: cast.h:44
function_call::kwargs_ref
object kwargs_ref
Definition: cast.h:2003
all_type_info
const std::vector< detail::type_info * > & all_type_info(PyTypeObject *type)
Definition: cast.h:150
copyable_holder_caster::try_implicit_casts
bool try_implicit_casts(handle src, bool convert)
Definition: cast.h:1585
unpacking_collector::args
const tuple & args() const &
Definition: cast.h:2115
type_caster< CharT, enable_if_t< is_std_char_type< CharT >::value > >::cast
static handle cast(CharT src, return_value_policy policy, handle parent)
Definition: cast.h:1373
tuple_caster::implicit_cast
type implicit_cast(index_sequence< Is... >) &
Definition: cast.h:1476
isinstance_generic
PYBIND11_NOINLINE bool isinstance_generic(handle obj, const std::type_info &tp)
Definition: cast.h:416
type_caster_base::type_caster_base
type_caster_base()
Definition: cast.h:875
values_and_holders
Definition: cast.h:279
values_and_holders::iterator::operator->
value_and_holder * operator->()
Definition: cast.h:314
argument_loader::has_kwargs
static constexpr bool has_kwargs
Definition: cast.h:2029
values_and_holders::iterator::operator==
bool operator==(const iterator &other) const
Definition: cast.h:304
type_caster< T, enable_if_t< std::is_arithmetic< T >::value &&!is_std_char_type< T >::value > >::cast
static std::enable_if<!std::is_floating_point< U >::value &&std::is_signed< U >::value &&(sizeof(U) > sizeof(long)), handle >::type cast(U src, return_value_policy, handle)
Definition: cast.h:1119
get_global_type_info
detail::type_info * get_global_type_info(const std::type_index &tp)
Definition: cast.h:181
type_caster< bool >::PYBIND11_TYPE_CASTER
PYBIND11_TYPE_CASTER(bool, _("bool"))
value_and_holder::type
const detail::type_info * type
Definition: cast.h:226
values_and_holders::end
iterator end()
Definition: cast.h:318
test_callbacks.value
value
Definition: test_callbacks.py:126
return_value_policy::automatic
@ automatic
arg_v::arg_v
arg_v(const arg &base, T &&x, const char *descr=nullptr)
Called internally when invoking py::arg("a") = value
Definition: cast.h:1941
loader_life_support::add_patient
static PYBIND11_NOINLINE void add_patient(handle h)
Definition: cast.h:68
function_call::args_convert
std::vector< bool > args_convert
The convert value the arguments should be loaded with.
Definition: cast.h:1999
string_caster< std::basic_string< CharT, Traits, Allocator > >::CharT
typename StringType::value_type CharT
Definition: cast.h:1236
PYBIND11_STRING_NAME
#define PYBIND11_STRING_NAME
Definition: common.h:227
return_value_policy::reference
@ reference
args_are_all_positional
constexpr bool args_are_all_positional()
Definition: cast.h:2226
polymorphic_type_hook_base< itype, detail::enable_if_t< std::is_polymorphic< itype >::value > >::get
static const void * get(const itype *src, const std::type_info *&type)
Definition: cast.h:858
tuple_caster::cast
static handle cast(T &&src, return_value_policy policy, handle parent)
Definition: cast.h:1452
arg_v::none
arg_v & none(bool flag=true)
Same as arg::nonone(), but returns *this as arg_v&, not arg&.
Definition: cast.h:1948
get_type_info
PYBIND11_NOINLINE detail::type_info * get_type_info(PyTypeObject *type)
Definition: cast.h:164
string_caster::load
bool load(handle src, bool)
Definition: cast.h:1251
get_local_type_info
detail::type_info * get_local_type_info(const std::type_index &tp)
Definition: cast.h:173
type_caster_base
Generic type caster for objects stored on the heap.
Definition: cast.h:869
setup.msg
msg
Definition: setup.py:47
cast_is_temporary_value_reference
bool_constant<(std::is_reference< type >::value||std::is_pointer< type >::value) &&!std::is_base_of< type_caster_generic, make_caster< type > >::value &&!std::is_same< intrinsic_t< type >, void >::value > cast_is_temporary_value_reference
Definition: cast.h:1728
type_caster_generic::type_caster_generic
type_caster_generic(const type_info *typeinfo)
Definition: cast.h:505