14 #include "detail/typeid.h"
15 #include "detail/descr.h"
16 #include "detail/internals.h"
20 #include <type_traits>
22 #if defined(PYBIND11_CPP17)
23 # if defined(__has_include)
24 # if __has_include(<string_view>)
25 # define PYBIND11_HAS_STRING_VIEW
27 # elif defined(_MSC_VER)
28 # define PYBIND11_HAS_STRING_VIEW
31 #ifdef PYBIND11_HAS_STRING_VIEW
32 #include <string_view>
35 #if defined(__cpp_lib_char8_t) && __cpp_lib_char8_t >= 201811L
36 # define PYBIND11_HAS_U8STRING
39 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
40 PYBIND11_NAMESPACE_BEGIN(detail)
48 get_internals().loader_patient_stack.push_back(
nullptr);
53 auto &stack = get_internals().loader_patient_stack;
55 pybind11_fail(
"loader_life_support: internal error");
57 auto ptr = stack.back();
62 if (stack.capacity() > 16 && !stack.empty() && stack.capacity() / stack.size() > 2)
63 stack.shrink_to_fit();
69 auto &stack = get_internals().loader_patient_stack;
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");
75 auto &list_ptr = stack.back();
76 if (list_ptr ==
nullptr) {
77 list_ptr = PyList_New(1);
79 pybind11_fail(
"loader_life_support: error allocating list");
80 PyList_SET_ITEM(list_ptr, 0, h.
inc_ref().
ptr());
82 auto result = PyList_Append(list_ptr, h.
ptr());
84 pybind11_fail(
"loader_life_support: error adding patient");
92 inline std::pair<decltype(internals::registered_types_py)::iterator, bool> all_type_info_get_cache(PyTypeObject *
type);
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());
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];
104 if (!PyType_Check((PyObject *)
type))
continue;
107 auto it = type_dict.find(
type);
108 if (it != type_dict.end()) {
113 for (
auto *tinfo : it->second) {
118 for (
auto *known : bases) {
119 if (known == tinfo) { found =
true;
break; }
121 if (!found) bases.push_back(tinfo);
124 else if (
type->tp_bases) {
127 if (i + 1 == check.size()) {
134 for (
handle parent : reinterpret_borrow<tuple>(
type->tp_bases))
135 check.push_back((PyTypeObject *) parent.ptr());
150 inline const std::vector<detail::type_info *> &all_type_info(PyTypeObject *
type) {
151 auto ins = all_type_info_get_cache(type);
154 all_type_info_populate(type, ins.first->second);
156 return ins.first->second;
164 PYBIND11_NOINLINE
inline detail::type_info* get_type_info(PyTypeObject *type) {
165 auto &bases = all_type_info(type);
168 if (bases.size() > 1)
169 pybind11_fail(
"pybind11::detail::get_type_info: type has multiple pybind11-registered bases");
170 return bases.front();
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())
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())
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))
194 if (
auto gtype = get_global_type_info(tp))
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 +
"\"");
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);
213 const detail::type_info *type =
nullptr;
218 inst{i}, index{index}, type{type},
219 vh{inst->
simple_layout ? inst->simple_value_holder : &inst->nonsimple.values_and_holders[vpos]}
228 template <
typename V =
void> V *&value_ptr()
const {
229 return reinterpret_cast<V *&
>(vh[0]);
232 explicit operator bool()
const {
return value_ptr(); }
234 template <
typename H> H &holder()
const {
235 return reinterpret_cast<H &
>(vh[1]);
237 bool holder_constructed()
const {
242 void set_holder_constructed(
bool v =
true) {
250 bool instance_registered()
const {
253 : inst->nonsimple.status[index] & instance::status_instance_registered;
255 void set_instance_registered(
bool v =
true) {
259 inst->nonsimple.status[index] |= instance::status_instance_registered;
261 inst->nonsimple.status[index] &= (uint8_t) ~instance::status_instance_registered;
269 using type_vec = std::vector<detail::type_info *>;
270 const type_vec &tinfo;
278 const type_vec *types =
nullptr;
282 : inst{inst}, types{tinfo},
284 types->empty() ?
nullptr : (*types)[0] ,
291 bool operator==(
const iterator &other)
const {
return curr.index == other.curr.index; }
292 bool operator!=(
const iterator &other)
const {
return curr.index != other.curr.index; }
295 curr.vh += 1 + (*types)[curr.index]->holder_size_in_ptrs;
297 curr.type = curr.index < types->size() ? (*types)[curr.index] :
nullptr;
307 iterator find(
const type_info *find_type) {
308 auto it = begin(), endit = end();
309 while (it != endit && it->type != find_type) ++it;
313 size_t size() {
return tinfo.size(); }
328 if (!find_type || Py_TYPE(
this) == find_type->type)
331 detail::values_and_holders vhs(
this);
332 auto it = vhs.find(find_type);
336 if (!throw_if_missing)
340 pybind11_fail(
"pybind11::detail::instance::get_value_and_holder: "
341 "type is not a pybind11 base of the given instance "
342 "(compile in debug mode for type details)");
344 pybind11_fail(
"pybind11::detail::instance::get_value_and_holder: `" +
345 get_fully_qualified_tp_name(find_type->type) +
"' is not a pybind11 base of the given `" +
346 get_fully_qualified_tp_name(Py_TYPE(
this)) +
"' instance");
351 auto &tinfo = all_type_info(Py_TYPE(
this));
353 const size_t n_types = tinfo.size();
356 pybind11_fail(
"instance allocation failed: new instance has no pybind11-registered base types");
359 n_types == 1 && tinfo.front()->holder_size_in_ptrs <= instance_simple_holder_in_ptrs();
363 simple_value_holder[0] =
nullptr;
373 for (
auto t : tinfo) {
375 space += t->holder_size_in_ptrs;
377 size_t flags_at = space;
378 space += size_in_ptrs(n_types);
385 #if PY_VERSION_HEX >= 0x03050000
386 nonsimple.values_and_holders = (
void **) PyMem_Calloc(space,
sizeof(
void *));
387 if (!nonsimple.values_and_holders)
throw std::bad_alloc();
389 nonsimple.values_and_holders = (
void **) PyMem_New(
void *, space);
390 if (!nonsimple.values_and_holders)
throw std::bad_alloc();
391 std::memset(nonsimple.values_and_holders, 0, space *
sizeof(
void *));
393 nonsimple.status =
reinterpret_cast<uint8_t *
>(&nonsimple.values_and_holders[flags_at]);
400 PyMem_Free(nonsimple.values_and_holders);
403 PYBIND11_NOINLINE
inline bool isinstance_generic(
handle obj,
const std::type_info &tp) {
404 handle type = detail::get_type_handle(tp,
false);
410 PYBIND11_NOINLINE
inline std::string error_string() {
411 if (!PyErr_Occurred()) {
412 PyErr_SetString(PyExc_RuntimeError,
"Unknown internal error occurred");
413 return "Unknown internal error occurred";
418 std::string errorString;
420 errorString +=
handle(scope.type).attr(
"__name__").
cast<std::string>();
424 errorString += (std::string)
str(scope.value);
426 PyErr_NormalizeException(&scope.type, &scope.value, &scope.trace);
428 #if PY_MAJOR_VERSION >= 3
429 if (scope.trace !=
nullptr)
430 PyException_SetTraceback(scope.value, scope.trace);
433 #if !defined(PYPY_VERSION)
435 auto *trace = (PyTracebackObject *) scope.trace;
438 while (trace->tb_next)
439 trace = trace->tb_next;
441 PyFrameObject *frame = trace->tb_frame;
442 errorString +=
"\n\nAt:\n";
444 int lineno = PyFrame_GetLineNumber(frame);
446 " " +
handle(frame->f_code->co_filename).
cast<std::string>() +
447 "(" + std::to_string(lineno) +
"): " +
448 handle(frame->f_code->co_name).
cast<std::string>() +
"\n";
449 frame = frame->f_back;
457 PYBIND11_NOINLINE
inline handle get_object_handle(
const void *ptr,
const detail::type_info *type ) {
458 auto &instances = get_internals().registered_instances;
459 auto range = instances.equal_range(ptr);
460 for (
auto it = range.first; it != range.second; ++it) {
463 return handle((PyObject *) it->second);
469 inline PyThreadState *get_thread_state_unchecked() {
470 #if defined(PYPY_VERSION)
471 return PyThreadState_GET();
472 #elif PY_VERSION_HEX < 0x03000000
473 return _PyThreadState_Current;
474 #elif PY_VERSION_HEX < 0x03050000
475 return (PyThreadState*) _Py_atomic_load_relaxed(&_PyThreadState_Current);
476 #elif PY_VERSION_HEX < 0x03050200
477 return (PyThreadState*) _PyThreadState_Current.value;
479 return _PyThreadState_UncheckedGet();
484 inline void keep_alive_impl(
handle nurse,
handle patient);
485 inline PyObject *make_new_instance(PyTypeObject *type);
490 : typeinfo(get_type_info(type_info)), cpptype(&type_info) { }
492 type_caster_generic(
const type_info *typeinfo)
493 : typeinfo(typeinfo), cpptype(typeinfo ? typeinfo->cpptype :
nullptr) { }
495 bool load(
handle src,
bool convert) {
496 return load_impl<type_caster_generic>(src, convert);
499 PYBIND11_NOINLINE
static handle cast(
const void *_src, return_value_policy policy,
handle parent,
500 const detail::type_info *tinfo,
501 void *(*copy_constructor)(
const void *),
502 void *(*move_constructor)(
const void *),
503 const void *existing_holder =
nullptr) {
507 void *src =
const_cast<void *
>(_src);
511 auto it_instances = get_internals().registered_instances.equal_range(src);
512 for (
auto it_i = it_instances.first; it_i != it_instances.second; ++it_i) {
513 for (
auto instance_type : detail::all_type_info(Py_TYPE(it_i->second))) {
514 if (instance_type && same_type(*instance_type->cpptype, *tinfo->cpptype))
519 auto inst = reinterpret_steal<object>(make_new_instance(tinfo->type));
520 auto wrapper =
reinterpret_cast<instance *
>(inst.ptr());
521 wrapper->
owned =
false;
525 case return_value_policy::automatic:
526 case return_value_policy::take_ownership:
528 wrapper->owned =
true;
531 case return_value_policy::automatic_reference:
532 case return_value_policy::reference:
534 wrapper->owned =
false;
537 case return_value_policy::copy:
538 if (copy_constructor)
539 valueptr = copy_constructor(src);
542 throw cast_error(
"return_value_policy = copy, but type is "
543 "non-copyable! (compile in debug mode for details)");
545 std::string type_name(tinfo->cpptype->name());
546 detail::clean_type_id(type_name);
547 throw cast_error(
"return_value_policy = copy, but type " +
548 type_name +
" is non-copyable!");
551 wrapper->owned =
true;
554 case return_value_policy::move:
555 if (move_constructor)
556 valueptr = move_constructor(src);
557 else if (copy_constructor)
558 valueptr = copy_constructor(src);
561 throw cast_error(
"return_value_policy = move, but type is neither "
562 "movable nor copyable! "
563 "(compile in debug mode for details)");
565 std::string type_name(tinfo->cpptype->name());
566 detail::clean_type_id(type_name);
567 throw cast_error(
"return_value_policy = move, but type " +
568 type_name +
" is neither movable nor copyable!");
571 wrapper->owned =
true;
574 case return_value_policy::reference_internal:
576 wrapper->owned =
false;
577 keep_alive_impl(inst, parent);
581 throw cast_error(
"unhandled return_value_policy: should not happen!");
584 tinfo->init_instance(wrapper, existing_holder);
586 return inst.release();
591 auto *&vptr = v_h.value_ptr();
593 if (vptr ==
nullptr) {
594 auto *type = v_h.type ? v_h.type : typeinfo;
595 if (type->operator_new) {
596 vptr = type->operator_new(type->type_size);
598 #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
599 if (type->type_align > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
600 vptr = ::operator
new(type->type_size,
601 std::align_val_t(type->type_align));
604 vptr = ::operator
new(type->type_size);
609 bool try_implicit_casts(
handle src,
bool convert) {
610 for (
auto &cast : typeinfo->implicit_casts) {
611 type_caster_generic sub_caster(*cast.first);
612 if (sub_caster.load(src, convert)) {
613 value = cast.second(sub_caster.value);
619 bool try_direct_conversions(
handle src) {
620 for (
auto &converter : *typeinfo->direct_conversions) {
621 if (converter(src.
ptr(), value))
626 void check_holder_compat() {}
628 PYBIND11_NOINLINE
static void *local_load(PyObject *src,
const type_info *ti) {
629 auto caster = type_caster_generic(ti);
630 if (caster.load(src,
false))
638 constexpr
auto *local_key = PYBIND11_MODULE_LOCAL_ID;
640 if (!hasattr(pytype, local_key))
643 type_info *foreign_typeinfo = reinterpret_borrow<capsule>(getattr(pytype, local_key));
645 if (foreign_typeinfo->module_local_load == &local_load
646 || (cpptype && !same_type(*cpptype, *foreign_typeinfo->cpptype)))
649 if (
auto result = foreign_typeinfo->module_local_load(src.
ptr(), foreign_typeinfo)) {
659 template <
typename ThisT>
660 PYBIND11_NOINLINE
bool load_impl(
handle src,
bool convert) {
661 if (!src)
return false;
665 if (!convert)
return false;
670 auto &this_ =
static_cast<ThisT &
>(*this);
671 this_.check_holder_compat();
673 PyTypeObject *srctype = Py_TYPE(src.
ptr());
677 if (srctype == typeinfo->type) {
678 this_.load_value(reinterpret_cast<instance *>(src.
ptr())->get_value_and_holder());
682 else if (PyType_IsSubtype(srctype, typeinfo->type)) {
683 auto &bases = all_type_info(srctype);
684 bool no_cpp_mi = typeinfo->simple_type;
692 if (bases.size() == 1 && (no_cpp_mi || bases.front()->type == typeinfo->type)) {
693 this_.load_value(reinterpret_cast<instance *>(src.
ptr())->get_value_and_holder());
699 else if (bases.size() > 1) {
700 for (
auto base : bases) {
701 if (no_cpp_mi ? PyType_IsSubtype(
base->type, typeinfo->type) :
base->type == typeinfo->type) {
702 this_.load_value(reinterpret_cast<instance *>(src.
ptr())->get_value_and_holder(
base));
711 if (this_.try_implicit_casts(src, convert))
717 for (
auto &converter : typeinfo->implicit_conversions) {
718 auto temp = reinterpret_steal<object>(converter(src.
ptr(), typeinfo->type));
719 if (load_impl<ThisT>(temp,
false)) {
724 if (this_.try_direct_conversions(src))
729 if (typeinfo->module_local) {
730 if (
auto gtype = get_global_type_info(*typeinfo->cpptype)) {
732 return load(src,
false);
744 PYBIND11_NOINLINE
static std::pair<const void *, const type_info *> src_and_type(
745 const void *src,
const std::type_info &cast_type,
const std::type_info *rtti_type =
nullptr) {
746 if (
auto *tpi = get_type_info(cast_type))
747 return {src,
const_cast<const type_info *
>(tpi)};
750 std::string tname = rtti_type ? rtti_type->name() : cast_type.name();
751 detail::clean_type_id(tname);
752 std::string msg =
"Unregistered type : " + tname;
753 PyErr_SetString(PyExc_TypeError, msg.c_str());
754 return {
nullptr,
nullptr};
757 const type_info *typeinfo =
nullptr;
758 const std::type_info *cpptype =
nullptr;
759 void *value =
nullptr;
769 template <
typename T>
771 conditional_t<std::is_pointer<remove_reference_t<T>>::value,
772 typename std::add_pointer<intrinsic_t<T>>
::type,
773 typename std::add_lvalue_reference<intrinsic_t<T>>
::type>;
782 template <
typename T>
783 using movable_cast_op_type =
784 conditional_t<std::is_pointer<typename std::remove_reference<T>::type>::value,
785 typename std::add_pointer<intrinsic_t<T>>
::type,
786 conditional_t<std::is_rvalue_reference<T>::value,
787 typename std::add_rvalue_reference<intrinsic_t<T>>
::type,
788 typename std::add_lvalue_reference<intrinsic_t<T>>
::type>>;
799 std::is_same<typename Container::value_type &, typename Container::reference>,
801 negation<std::is_same<Container, typename Container::value_type>>
808 : all_of<is_copy_constructible<T1>, is_copy_constructible<T2>> {};
811 template <
typename T,
typename SFINAE =
void>
struct is_copy_assignable : std::is_copy_assignable<T> {};
814 std::is_same<typename Container::value_type &, typename Container::reference>
817 : all_of<is_copy_assignable<T1>, is_copy_assignable<T2>> {};
819 PYBIND11_NAMESPACE_END(detail)
842 template <typename itype, typename SFINAE =
void>
845 static const void *
get(
const itype *src,
const std::type_info*&) {
return src; }
847 template <
typename itype>
850 static const void *
get(
const itype *src,
const std::type_info*& type) {
851 type = src ? &
typeid(*src) :
nullptr;
852 return dynamic_cast<const void*
>(src);
855 template <
typename itype,
typename SFINAE =
void>
858 PYBIND11_NAMESPACE_BEGIN(detail)
862 using itype = intrinsic_t<type>;
865 static constexpr
auto name = _<type>();
868 explicit type_caster_base(
const std::type_info &info) : type_caster_generic(info) { }
870 static handle cast(
const itype &src, return_value_policy policy,
handle parent) {
871 if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference)
872 policy = return_value_policy::copy;
873 return cast(&src, policy, parent);
876 static handle cast(itype &&src, return_value_policy,
handle parent) {
877 return cast(&src, return_value_policy::move, parent);
883 static std::pair<const void *, const type_info *> src_and_type(
const itype *src) {
884 auto &cast_type =
typeid(itype);
885 const std::type_info *instance_type =
nullptr;
887 if (instance_type && !same_type(cast_type, *instance_type)) {
896 if (
const auto *tpi = get_type_info(*instance_type))
901 return type_caster_generic::src_and_type(src, cast_type, instance_type);
904 static handle cast(
const itype *src, return_value_policy policy,
handle parent) {
905 auto st = src_and_type(src);
906 return type_caster_generic::cast(
907 st.first, policy, parent, st.second,
908 make_copy_constructor(src), make_move_constructor(src));
911 static handle cast_holder(
const itype *src,
const void *holder) {
912 auto st = src_and_type(src);
913 return type_caster_generic::cast(
914 st.first, return_value_policy::take_ownership, {}, st.second,
915 nullptr,
nullptr, holder);
918 template <
typename T>
using cast_op_type = detail::cast_op_type<T>;
920 operator itype*() {
return (type *) value; }
921 operator itype&() {
if (!value)
throw reference_cast_error();
return *((itype *) value); }
924 using Constructor =
void *(*)(
const void *);
928 template <typename T, typename = enable_if_t<is_copy_constructible<T>::value>>
929 static auto make_copy_constructor(
const T *x) -> decltype(
new T(*x), Constructor{}) {
930 return [](
const void *arg) ->
void * {
931 return new T(*reinterpret_cast<const T *>(arg));
935 template <typename T, typename = enable_if_t<std::is_move_constructible<T>::value>>
936 static auto make_move_constructor(
const T *x) -> decltype(
new T(std::move(*const_cast<T *>(x))), Constructor{}) {
937 return [](
const void *arg) ->
void * {
938 return new T(std::move(*const_cast<T *>(reinterpret_cast<const T *>(arg))));
942 static Constructor make_copy_constructor(...) {
return nullptr; }
943 static Constructor make_move_constructor(...) {
return nullptr; }
955 return std::move(caster).operator
959 template <
typename type>
class type_caster<std::reference_wrapper<type>> {
963 using subcaster_cast_op_type =
typename caster_t::template cast_op_type<type>;
964 static_assert(std::is_same<
typename std::remove_const<type>::type &, subcaster_cast_op_type>::value,
965 "std::reference_wrapper<T> caster requires T to have a caster with an `T &` operator");
967 bool load(
handle src,
bool convert) {
return subcaster.load(src, convert); }
968 static constexpr
auto name = caster_t::name;
969 static handle cast(
const std::reference_wrapper<type> &src, return_value_policy policy,
handle parent) {
971 if (policy == return_value_policy::take_ownership || policy == return_value_policy::automatic)
972 policy = return_value_policy::automatic_reference;
973 return caster_t::cast(&src.get(), policy, parent);
975 template <
typename T>
using cast_op_type = std::reference_wrapper<type>;
976 operator std::reference_wrapper<type>() {
return subcaster.operator subcaster_cast_op_type&(); }
979 #define PYBIND11_TYPE_CASTER(type, py_name) \
983 static constexpr auto name = py_name; \
984 template <typename T_, enable_if_t<std::is_same<type, remove_cv_t<T_>>::value, int> = 0> \
985 static handle cast(T_ *src, return_value_policy policy, handle parent) { \
986 if (!src) return none().release(); \
987 if (policy == return_value_policy::take_ownership) { \
988 auto h = cast(std::move(*src), policy, parent); delete src; return h; \
990 return cast(*src, policy, parent); \
993 operator type*() { return &value; } \
994 operator type&() { return value; } \
995 operator type&&() && { return std::move(value); } \
996 template <typename T_> using cast_op_type = pybind11::detail::movable_cast_op_type<T_>
1000 std::is_same<CharT, char>,
1001 #if defined(PYBIND11_HAS_U8STRING)
1002 std::is_same<CharT, char8_t>,
1004 std::is_same<CharT, char16_t>,
1005 std::is_same<CharT, char32_t>,
1006 std::is_same<CharT, wchar_t>
1010 template <
typename T>
1012 using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>;
1013 using _py_type_1 = conditional_t<std::is_signed<T>::value, _py_type_0,
typename std::make_unsigned<_py_type_0>::type>;
1014 using py_type = conditional_t<std::is_floating_point<T>::value, double, _py_type_1>;
1017 bool load(
handle src,
bool convert) {
1023 if (std::is_floating_point<T>::value) {
1024 if (convert || PyFloat_Check(src.
ptr()))
1025 py_value = (py_type) PyFloat_AsDouble(src.
ptr());
1028 }
else if (PyFloat_Check(src.
ptr())) {
1030 }
else if (std::is_unsigned<py_type>::value) {
1031 py_value = as_unsigned<py_type>(src.
ptr());
1033 py_value =
sizeof(T) <=
sizeof(
long)
1034 ? (py_type) PyLong_AsLong(src.
ptr())
1035 : (py_type) PYBIND11_LONG_AS_LONGLONG(src.
ptr());
1039 bool py_err = py_value == (py_type) -1 && PyErr_Occurred();
1043 if (py_err || (std::is_integral<T>::value &&
sizeof(py_type) !=
sizeof(T) && py_value != (py_type) (T) py_value)) {
1044 bool type_error = py_err && PyErr_ExceptionMatches(
1045 #
if PY_VERSION_HEX < 0x03000000 && !defined(PYPY_VERSION)
1052 if (type_error && convert && PyNumber_Check(src.
ptr())) {
1053 auto tmp = reinterpret_steal<object>(std::is_floating_point<T>::value
1054 ? PyNumber_Float(src.
ptr())
1055 : PyNumber_Long(src.
ptr()));
1057 return load(tmp,
false);
1062 value = (T) py_value;
1066 template<
typename U = T>
1067 static typename std::enable_if<std::is_floating_point<U>::value,
handle>
::type
1068 cast(U src, return_value_policy ,
handle ) {
1069 return PyFloat_FromDouble((
double) src);
1072 template<
typename U = T>
1073 static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value && (
sizeof(U) <=
sizeof(
long)),
handle>::type
1074 cast(U src, return_value_policy ,
handle ) {
1075 return PYBIND11_LONG_FROM_SIGNED((
long) src);
1078 template<
typename U = T>
1079 static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value && (
sizeof(U) <=
sizeof(
unsigned long)),
handle>::type
1080 cast(U src, return_value_policy ,
handle ) {
1081 return PYBIND11_LONG_FROM_UNSIGNED((
unsigned long) src);
1084 template<
typename U = T>
1085 static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value && (
sizeof(U) >
sizeof(
long)),
handle>::type
1086 cast(U src, return_value_policy ,
handle ) {
1087 return PyLong_FromLongLong((
long long) src);
1090 template<
typename U = T>
1091 static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value && (
sizeof(U) >
sizeof(
unsigned long)),
handle>::type
1092 cast(U src, return_value_policy ,
handle ) {
1093 return PyLong_FromUnsignedLongLong((
unsigned long long) src);
1096 PYBIND11_TYPE_CASTER(T, _<std::is_integral<T>::value>(
"int",
"float"));
1101 bool load(
handle src,
bool) {
1102 if (src && src.is_none())
1109 PYBIND11_TYPE_CASTER(T, _(
"None"));
1118 bool load(
handle h,
bool) {
1121 }
else if (h.is_none()) {
1127 if (isinstance<capsule>(h)) {
1128 value = reinterpret_borrow<capsule>(h);
1133 auto &bases = all_type_info((PyTypeObject *)
type::handle_of(h).ptr());
1134 if (bases.size() == 1) {
1143 static handle cast(
const void *ptr, return_value_policy ,
handle ) {
1150 template <
typename T>
using cast_op_type =
void*&;
1151 operator void *&() {
return value; }
1152 static constexpr
auto name = _(
"capsule");
1154 void *value =
nullptr;
1161 bool load(
handle src,
bool convert) {
1162 if (!src)
return false;
1163 else if (src.
ptr() == Py_True) { value =
true;
return true; }
1164 else if (src.
ptr() == Py_False) { value =
false;
return true; }
1165 else if (convert || !strcmp(
"numpy.bool_", Py_TYPE(src.
ptr())->tp_name)) {
1168 Py_ssize_t res = -1;
1169 if (src.is_none()) {
1172 #if defined(PYPY_VERSION)
1174 else if (hasattr(src, PYBIND11_BOOL_ATTR)) {
1175 res = PyObject_IsTrue(src.
ptr());
1180 else if (
auto tp_as_number = src.
ptr()->ob_type->tp_as_number) {
1181 if (PYBIND11_NB_BOOL(tp_as_number)) {
1182 res = (*PYBIND11_NB_BOOL(tp_as_number))(src.
ptr());
1186 if (res == 0 || res == 1) {
1195 static handle cast(
bool src, return_value_policy ,
handle ) {
1198 PYBIND11_TYPE_CASTER(
bool, _(
"bool"));
1203 using CharT =
typename StringType::value_type;
1207 static_assert(!std::is_same<CharT, char>::value ||
sizeof(CharT) == 1,
"Unsupported char size != 1");
1208 #if defined(PYBIND11_HAS_U8STRING)
1209 static_assert(!std::is_same<CharT, char8_t>::value ||
sizeof(CharT) == 1,
"Unsupported char8_t size != 1");
1211 static_assert(!std::is_same<CharT, char16_t>::value ||
sizeof(CharT) == 2,
"Unsupported char16_t size != 2");
1212 static_assert(!std::is_same<CharT, char32_t>::value ||
sizeof(CharT) == 4,
"Unsupported char32_t size != 4");
1214 static_assert(!std::is_same<CharT, wchar_t>::value ||
sizeof(CharT) == 2 ||
sizeof(CharT) == 4,
1215 "Unsupported wchar_t size != 2/4");
1216 static constexpr
size_t UTF_N = 8 *
sizeof(CharT);
1218 bool load(
handle src,
bool) {
1219 #if PY_MAJOR_VERSION < 3
1225 }
else if (!PyUnicode_Check(load_src.
ptr())) {
1226 #if PY_MAJOR_VERSION >= 3
1227 return load_bytes(load_src);
1229 if (std::is_same<CharT, char>::value) {
1230 return load_bytes(load_src);
1234 if (!PYBIND11_BYTES_CHECK(load_src.
ptr()))
1237 temp = reinterpret_steal<object>(PyUnicode_FromObject(load_src.
ptr()));
1238 if (!temp) { PyErr_Clear();
return false; }
1243 object utfNbytes = reinterpret_steal<object>(PyUnicode_AsEncodedString(
1244 load_src.
ptr(), UTF_N == 8 ?
"utf-8" : UTF_N == 16 ?
"utf-16" :
"utf-32",
nullptr));
1245 if (!utfNbytes) { PyErr_Clear();
return false; }
1247 const auto *
buffer =
reinterpret_cast<const CharT *
>(PYBIND11_BYTES_AS_STRING(utfNbytes.
ptr()));
1248 size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.
ptr()) /
sizeof(CharT);
1249 if (UTF_N > 8) {
buffer++; length--; }
1250 value = StringType(
buffer, length);
1259 static handle cast(
const StringType &src, return_value_policy ,
handle ) {
1260 const char *
buffer =
reinterpret_cast<const char *
>(src.data());
1261 auto nbytes = ssize_t(src.size() *
sizeof(CharT));
1262 handle s = decode_utfN(buffer, nbytes);
1267 PYBIND11_TYPE_CASTER(StringType, _(PYBIND11_STRING_NAME));
1270 static handle decode_utfN(
const char *
buffer, ssize_t nbytes) {
1271 #if !defined(PYPY_VERSION)
1273 UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes,
nullptr) :
1274 UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes,
nullptr,
nullptr) :
1275 PyUnicode_DecodeUTF32(buffer, nbytes,
nullptr,
nullptr);
1279 return PyUnicode_Decode(buffer, nbytes, UTF_N == 8 ?
"utf-8" : UTF_N == 16 ?
"utf-16" :
"utf-32",
nullptr);
1286 template <
typename C = CharT>
1287 bool load_bytes(enable_if_t<std::is_same<C, char>::value,
handle> src) {
1288 if (PYBIND11_BYTES_CHECK(src.ptr())) {
1291 const char *
bytes = PYBIND11_BYTES_AS_STRING(src.ptr());
1293 value = StringType(bytes, (
size_t) PYBIND11_BYTES_SIZE(src.ptr()));
1301 template <
typename C = CharT>
1302 bool load_bytes(enable_if_t<!std::is_same<C, char>::value,
handle>) {
return false; }
1305 template <
typename CharT,
class Traits,
class Allocator>
1306 struct type_caster<std::basic_string<CharT, Traits, Allocator>, enable_if_t<is_std_char_type<CharT>::value>>
1307 :
string_caster<std::basic_string<CharT, Traits, Allocator>> {};
1309 #ifdef PYBIND11_HAS_STRING_VIEW
1310 template <
typename CharT,
class Traits>
1311 struct type_caster<std::basic_string_view<CharT, Traits>, enable_if_t<is_std_char_type<CharT>::value>>
1312 :
string_caster<std::basic_string_view<CharT, Traits>, true> {};
1318 using StringType = std::basic_string<CharT>;
1324 bool load(
handle src,
bool convert) {
1325 if (!src)
return false;
1326 if (src.is_none()) {
1328 if (!convert)
return false;
1332 return str_caster.load(src, convert);
1335 static handle cast(
const CharT *src, return_value_policy policy,
handle parent) {
1336 if (src ==
nullptr)
return pybind11::none().
inc_ref();
1337 return StringCaster::cast(StringType(src), policy, parent);
1340 static handle cast(CharT src, return_value_policy policy,
handle parent) {
1341 if (std::is_same<char, CharT>::value) {
1342 handle s = PyUnicode_DecodeLatin1((
const char *) &src, 1,
nullptr);
1346 return StringCaster::cast(StringType(1, src), policy, parent);
1349 operator CharT*() {
return none ?
nullptr :
const_cast<CharT *
>(
static_cast<StringType &
>(str_caster).c_str()); }
1352 throw value_error(
"Cannot convert None to a character");
1354 auto &value =
static_cast<StringType &
>(str_caster);
1355 size_t str_len = value.size();
1357 throw value_error(
"Cannot convert empty string to a character");
1364 if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) {
1365 auto v0 =
static_cast<unsigned char>(value[0]);
1366 size_t char0_bytes = !(v0 & 0x80) ? 1 :
1367 (v0 & 0xE0) == 0xC0 ? 2 :
1368 (v0 & 0xF0) == 0xE0 ? 3 :
1371 if (char0_bytes == str_len) {
1373 if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) {
1374 one_char =
static_cast<CharT
>(((v0 & 3) << 6) + (
static_cast<unsigned char>(value[1]) & 0x3F));
1378 throw value_error(
"Character code point not in range(0x100)");
1385 else if (StringCaster::UTF_N == 16 && str_len == 2) {
1386 one_char =
static_cast<CharT
>(value[0]);
1387 if (one_char >= 0xD800 && one_char < 0xE000)
1388 throw value_error(
"Character code point not in range(0x10000)");
1392 throw value_error(
"Expected a character, but multi-character string found");
1394 one_char = value[0];
1398 static constexpr
auto name = _(PYBIND11_STRING_NAME);
1399 template <
typename _T>
using cast_op_type = pybind11::detail::cast_op_type<_T>;
1403 template <
template<
typename...>
class Tuple,
typename... Ts>
class tuple_caster {
1404 using type = Tuple<Ts...>;
1405 static constexpr
auto size =
sizeof...(Ts);
1406 using indices = make_index_sequence<size>;
1409 bool load(
handle src,
bool convert) {
1410 if (!isinstance<sequence>(src))
1412 const auto seq = reinterpret_borrow<sequence>(src);
1413 if (seq.size() != size)
1415 return load_impl(seq, convert, indices{});
1418 template <
typename T>
1419 static handle cast(T &&src, return_value_policy policy,
handle parent) {
1420 return cast_impl(std::forward<T>(src), policy, parent, indices{});
1424 template <
typename T>
1425 static handle cast(T *src, return_value_policy policy,
handle parent) {
1427 if (policy == return_value_policy::take_ownership) {
1428 auto h = cast(std::move(*src), policy, parent);
delete src;
return h;
1430 return cast(*src, policy, parent);
1436 template <
typename T>
using cast_op_type = type;
1438 operator type() & {
return implicit_cast(indices{}); }
1439 operator type() && {
return std::move(*this).implicit_cast(indices{}); }
1442 template <
size_t... Is>
1443 type implicit_cast(
index_sequence<Is...>) & {
return type(cast_op<Ts>(std::get<Is>(subcasters))...); }
1444 template <
size_t... Is>
1445 type implicit_cast(
index_sequence<Is...>) && {
return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...); }
1449 template <
size_t... Is>
1451 #ifdef __cpp_fold_expressions
1452 if ((... || !std::get<Is>(subcasters).load(seq[Is], convert)))
1455 for (
bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...})
1463 template <
typename T,
size_t... Is>
1465 std::array<object, size> entries{{
1466 reinterpret_steal<object>(
make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...
1468 for (
const auto &entry: entries)
1473 for (
auto & entry: entries)
1474 PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());
1475 return result.release();
1478 Tuple<make_caster<Ts>...> subcasters;
1481 template <
typename T1,
typename T2>
class type_caster<std::pair<T1, T2>>
1489 template <
typename T>
1491 static auto get(
const T &p) -> decltype(p.get()) {
return p.get(); }
1495 template <
typename type,
typename holder_type>
1500 "Holder classes are only supported for custom types");
1503 using base::typeinfo;
1506 bool load(
handle src,
bool convert) {
1507 return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
1510 explicit operator type*() {
return this->value; }
1513 explicit operator type&() {
return *(
static_cast<type *
>(this->value)); }
1514 explicit operator holder_type*() {
return std::addressof(holder); }
1515 explicit operator holder_type&() {
return holder; }
1517 static handle cast(
const holder_type &src, return_value_policy,
handle) {
1523 friend class type_caster_generic;
1524 void check_holder_compat() {
1525 if (typeinfo->default_holder)
1526 throw cast_error(
"Unable to load a custom holder type from a default-holder instance");
1530 if (v_h.holder_constructed()) {
1531 value = v_h.value_ptr();
1532 holder = v_h.template holder<holder_type>();
1535 throw cast_error(
"Unable to cast from non-held to held instance (T& to Holder<T>) "
1537 "(compile in debug mode for type information)");
1539 "of type '" + type_id<holder_type>() +
"''");
1544 template <typename T = holder_type, detail::enable_if_t<!std::is_constructible<T, const T &, type*>::value,
int> = 0>
1545 bool try_implicit_casts(
handle,
bool) {
return false; }
1547 template <typename T = holder_type, detail::enable_if_t<std::is_constructible<T, const T &, type*>::value,
int> = 0>
1548 bool try_implicit_casts(
handle src,
bool convert) {
1549 for (
auto &cast : typeinfo->implicit_casts) {
1551 if (sub_caster.load(src, convert)) {
1552 value = cast.second(sub_caster.value);
1553 holder = holder_type(sub_caster.holder, (type *) value);
1560 static bool try_direct_conversions(
handle) {
return false; }
1567 template <
typename T>
1570 template <
typename type,
typename holder_type>
1573 "Holder classes are only supported for custom types");
1575 static handle cast(holder_type &&src, return_value_policy,
handle) {
1582 template <
typename type,
typename deleter>
1586 template <
typename type,
typename holder_type>
1587 using type_caster_holder = conditional_t<is_copy_constructible<holder_type>::value,
1594 #define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
1595 namespace pybind11 { namespace detail { \
1596 template <typename type> \
1597 struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__> { }; \
1598 template <typename type> \
1599 class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
1600 : public type_caster_holder<type, holder_type> { }; \
1605 std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
1619 template <
typename type>
1621 template <typename T = type, enable_if_t<std::is_same<T, handle>::value,
int> = 0>
1622 bool load(
handle src,
bool ) { value = src;
return static_cast<bool>(value); }
1624 template <typename T = type, enable_if_t<std::is_base_of<object, T>::value,
int> = 0>
1625 bool load(
handle src,
bool ) {
1626 if (!isinstance<type>(src))
1628 value = reinterpret_borrow<type>(src);
1638 template <
typename T>
1651 std::is_void, std::is_pointer, std::is_reference, std::is_const
1653 template <
typename T,
typename SFINAE =
void>
struct move_always : std::false_type {};
1654 template <
typename T>
struct move_always<T, enable_if_t<all_of<
1657 std::is_move_constructible<T>,
1658 std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&>
1659 >::value>> : std::true_type {};
1660 template <
typename T,
typename SFINAE =
void>
struct move_if_unreferenced : std::false_type {};
1661 template <
typename T>
struct move_if_unreferenced<T, enable_if_t<all_of<
1664 std::is_move_constructible<T>,
1665 std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&>
1666 >::value>> : std::true_type {};
1673 template <
typename type>
using cast_is_temporary_value_reference = bool_constant<
1674 (std::is_reference<type>::value || std::is_pointer<type>::value) &&
1676 !std::is_same<intrinsic_t<type>,
void>::value
1682 template <
typename Return,
typename SFINAE =
void>
struct return_value_policy_override {
1683 static return_value_policy policy(return_value_policy p) {
return p; }
1686 template <
typename Return>
struct return_value_policy_override<Return,
1687 detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
1688 static return_value_policy policy(return_value_policy p) {
1689 return !std::is_lvalue_reference<Return>::value &&
1690 !std::is_pointer<Return>::value
1691 ? return_value_policy::move : p;
1697 if (!conv.load(handle,
true)) {
1699 throw cast_error(
"Unable to cast Python instance to C++ type (compile in debug mode for details)");
1701 throw cast_error(
"Unable to cast Python instance of type " +
1708 template <
typename T>
make_caster<T> load_type(
const handle &handle) {
1710 load_type(conv, handle);
1714 PYBIND11_NAMESPACE_END(detail)
1717 template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value,
int> = 0>
1718 T cast(const handle &handle) {
1719 using namespace detail;
1720 static_assert(!cast_is_temporary_value_reference<T>::value,
1721 "Unable to cast type to reference: value is local to type caster");
1722 return cast_op<T>(load_type<T>(handle));
1726 template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value,
int> = 0>
1727 T cast(
const handle &handle) {
return T(reinterpret_borrow<object>(handle)); }
1730 template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value,
int> = 0>
1731 object cast(T &&value, return_value_policy policy = return_value_policy::automatic_reference,
1732 handle parent = handle()) {
1733 using no_ref_T =
typename std::remove_reference<T>::type;
1734 if (policy == return_value_policy::automatic)
1735 policy = std::is_pointer<no_ref_T>::value ? return_value_policy::take_ownership :
1736 std::is_lvalue_reference<T>::value ? return_value_policy::copy : return_value_policy::move;
1737 else if (policy == return_value_policy::automatic_reference)
1738 policy = std::is_pointer<no_ref_T>::value ? return_value_policy::reference :
1739 std::is_lvalue_reference<T>::value ? return_value_policy::copy : return_value_policy::move;
1740 return reinterpret_steal<object>(detail::make_caster<T>::cast(std::forward<T>(value), policy, parent));
1743 template <
typename T> T
handle::cast()
const {
return pybind11::cast<T>(*this); }
1744 template <>
inline void handle::cast()
const {
return; }
1746 template <
typename T>
1747 detail::enable_if_t<!detail::move_never<T>::value, T> move(
object &&obj) {
1748 if (obj.ref_count() > 1)
1750 throw cast_error(
"Unable to cast Python instance to C++ rvalue: instance has multiple references"
1751 " (compile in debug mode for details)");
1753 throw cast_error(
"Unable to move from Python " + (std::string)
str(
type::handle_of(obj)) +
1754 " instance to C++ " + type_id<T>() +
" instance: instance has multiple references");
1758 T ret = std::move(detail::load_type<T>(obj).
operator T&());
1767 template <
typename T> detail::enable_if_t<detail::move_always<T>::value, T> cast(
object &&
object) {
1768 return move<T>(std::move(
object));
1770 template <
typename T> detail::enable_if_t<detail::move_if_unreferenced<T>::value, T> cast(
object &&
object) {
1771 if (
object.ref_count() > 1)
1774 return move<T>(std::move(
object));
1776 template <
typename T> detail::enable_if_t<detail::move_never<T>::value, T> cast(
object &&
object) {
1780 template <
typename T> T object::cast() const & {
return pybind11::cast<T>(*this); }
1781 template <
typename T> T object::cast() && {
return pybind11::cast<T>(std::move(*
this)); }
1782 template <>
inline void object::cast() const & {
return; }
1783 template <>
inline void object::cast() && {
return; }
1785 PYBIND11_NAMESPACE_BEGIN(detail)
1788 template <typename T, enable_if_t<!is_pyobject<T>::value,
int>>
1789 object object_or_cast(T &&o) {
return pybind11::cast(std::forward<T>(o)); }
1791 struct override_unused {};
1792 template <
typename ret_type>
using override_caster_t = conditional_t<
1797 template <
typename T> enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(
object &&o,
make_caster<T> &caster) {
1798 return cast_op<T>(load_type(caster, o));
1800 template <
typename T> enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(
object &&, override_unused &) {
1801 pybind11_fail(
"Internal error: cast_ref fallback invoked"); }
1806 template <
typename T> enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_safe(
object &&o) {
1807 return pybind11::cast<T>(std::move(o)); }
1808 template <
typename T> enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_safe(
object &&) {
1809 pybind11_fail(
"Internal error: cast_safe fallback invoked"); }
1810 template <>
inline void cast_safe<void>(
object &&) {}
1812 PYBIND11_NAMESPACE_END(detail)
1814 template <return_value_policy policy = return_value_policy::automatic_reference>
1817 template <return_value_policy policy = return_value_policy::automatic_reference,
1818 typename... Args>
tuple make_tuple(Args&&... args_) {
1819 constexpr
size_t size =
sizeof...(Args);
1820 std::array<object, size>
args {
1821 { reinterpret_steal<object>(detail::make_caster<Args>::cast(
1822 std::forward<Args>(args_), policy,
nullptr))... }
1824 for (
size_t i = 0; i <
args.size(); i++) {
1827 throw cast_error(
"make_tuple(): unable to convert arguments to Python object (compile in debug mode for details)");
1829 std::array<std::string, size> argtypes { {type_id<Args>()...} };
1830 throw cast_error(
"make_tuple(): unable to convert argument of type '" +
1831 argtypes[i] +
"' to Python object");
1837 for (
auto &arg_value :
args)
1838 PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());
1846 constexpr
explicit arg(
const char *
name =
nullptr) :
name(
name), flag_noconvert(false), flag_none(true) { }
1848 template <
typename T> arg_v operator=(T &&value)
const;
1850 arg &noconvert(
bool flag =
true) { flag_noconvert = flag;
return *
this; }
1852 arg &
none(
bool flag =
true) { flag_none = flag;
return *
this; }
1855 bool flag_noconvert : 1;
1861 struct arg_v : arg {
1863 template <
typename T>
1864 arg_v(arg &&
base, T &&x,
const char *
descr =
nullptr)
1866 value(reinterpret_steal<
object>(
1867 detail::
make_caster<T>::cast(x, return_value_policy::automatic, {})
1870 #if !defined(NDEBUG)
1871 , type(type_id<T>())
1877 template <
typename T>
1878 arg_v(
const char *
name, T &&x,
const char *
descr =
nullptr)
1879 : arg_v(arg(name), std::forward<T>(x),
descr) { }
1882 template <
typename T>
1883 arg_v(
const arg &
base, T &&x,
const char *
descr =
nullptr)
1884 : arg_v(arg(base), std::forward<T>(x),
descr) { }
1887 arg_v &noconvert(
bool flag =
true) { arg::noconvert(flag);
return *
this; }
1890 arg_v &
none(
bool flag =
true) { arg::none(flag);
return *
this; }
1896 #if !defined(NDEBUG)
1912 template <
typename T>
1913 arg_v arg::operator=(T &&value)
const {
return {std::move(*
this), std::forward<T>(value)}; }
1916 template <
typename >
using arg_t = arg_v;
1918 inline namespace literals {
1922 constexpr arg
operator"" _a(
const char *
name,
size_t) {
return arg(name); }
1925 PYBIND11_NAMESPACE_BEGIN(detail)
1931 struct function_call {
1932 function_call(
const function_record &f, handle p);
1935 const function_record &func;
1938 std::vector<handle> args;
1941 std::vector<bool> args_convert;
1945 object args_ref, kwargs_ref;
1956 template <
typename... Args>
1957 class argument_loader {
1958 using indices = make_index_sequence<
sizeof...(Args)>;
1960 template <
typename Arg>
using argument_is_args = std::is_same<intrinsic_t<Arg>, args>;
1961 template <
typename Arg>
using argument_is_kwargs = std::is_same<intrinsic_t<Arg>,
kwargs>;
1963 static constexpr
auto args_pos = constexpr_first<argument_is_args, Args...>() - (
int)
sizeof...(Args),
1964 kwargs_pos = constexpr_first<argument_is_kwargs, Args...>() - (int)
sizeof...(Args);
1966 static constexpr
bool args_kwargs_are_last = kwargs_pos >= - 1 && args_pos >= kwargs_pos - 1;
1968 static_assert(args_kwargs_are_last,
"py::args/py::kwargs are only permitted as the last argument(s) of a function");
1971 static constexpr
bool has_kwargs = kwargs_pos < 0;
1972 static constexpr
bool has_args = args_pos < 0;
1976 bool load_args(function_call &call) {
1977 return load_impl_sequence(call, indices{});
1980 template <
typename Return,
typename Guard,
typename Func>
1981 enable_if_t<!std::is_void<Return>::value, Return> call(Func &&f) && {
1982 return std::move(*this).template call_impl<Return>(std::forward<Func>(f), indices{}, Guard{});
1985 template <
typename Return,
typename Guard,
typename Func>
1986 enable_if_t<std::is_void<Return>::value,
void_type> call(Func &&f) && {
1987 std::move(*this).template call_impl<Return>(std::forward<Func>(f), indices{}, Guard{});
1993 static bool load_impl_sequence(function_call &,
index_sequence<>) {
return true; }
1995 template <
size_t... Is>
1997 #ifdef __cpp_fold_expressions
1998 if ((... || !std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])))
2001 for (
bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...})
2008 template <
typename Return,
typename Func,
size_t... Is,
typename Guard>
2010 return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...);
2013 std::tuple<make_caster<Args>...> argcasters;
2018 template <return_value_policy policy>
2021 template <
typename... Ts>
2023 : m_args(pybind11::make_tuple<policy>(std::forward<Ts>(values)...)) { }
2025 const tuple &args() const & {
return m_args; }
2028 tuple args() && {
return std::move(m_args); }
2031 object call(PyObject *ptr)
const {
2032 PyObject *result = PyObject_CallObject(ptr, m_args.ptr());
2035 return reinterpret_steal<object>(result);
2043 template <return_value_policy policy>
2046 template <
typename... Ts>
2050 auto args_list =
list();
2051 int _[] = { 0, (process(args_list, std::forward<Ts>(values)), 0)... };
2054 m_args = std::move(args_list);
2057 const tuple &args() const & {
return m_args; }
2058 const dict &
kwargs() const & {
return m_kwargs; }
2060 tuple args() && {
return std::move(m_args); }
2061 dict kwargs() && {
return std::move(m_kwargs); }
2064 object call(PyObject *ptr)
const {
2065 PyObject *result = PyObject_Call(ptr, m_args.ptr(), m_kwargs.ptr());
2068 return reinterpret_steal<object>(result);
2072 template <
typename T>
2073 void process(
list &args_list, T &&x) {
2074 auto o = reinterpret_steal<object>(detail::make_caster<T>::cast(std::forward<T>(x), policy, {}));
2077 argument_cast_error();
2079 argument_cast_error(std::to_string(args_list.size()), type_id<T>());
2082 args_list.append(o);
2085 void process(
list &args_list, detail::args_proxy ap) {
2087 args_list.append(a);
2090 void process(
list &, arg_v a) {
2093 nameless_argument_error();
2095 nameless_argument_error(a.type);
2098 if (m_kwargs.contains(a.name)) {
2100 multiple_values_error();
2102 multiple_values_error(a.name);
2107 argument_cast_error();
2109 argument_cast_error(a.name, a.type);
2112 m_kwargs[a.name] = a.value;
2115 void process(
list &, detail::kwargs_proxy kp) {
2118 for (
auto k : reinterpret_borrow<dict>(kp)) {
2119 if (m_kwargs.contains(k.first)) {
2121 multiple_values_error();
2123 multiple_values_error(
str(k.first));
2126 m_kwargs[k.first] = k.second;
2130 [[noreturn]]
static void nameless_argument_error() {
2131 throw type_error(
"Got kwargs without a name; only named arguments "
2132 "may be passed via py::arg() to a python function call. "
2133 "(compile in debug mode for details)");
2135 [[noreturn]]
static void nameless_argument_error(std::string type) {
2136 throw type_error(
"Got kwargs without a name of type '" + type +
"'; only named "
2137 "arguments may be passed via py::arg() to a python function call. ");
2139 [[noreturn]]
static void multiple_values_error() {
2140 throw type_error(
"Got multiple values for keyword argument "
2141 "(compile in debug mode for details)");
2144 [[noreturn]]
static void multiple_values_error(std::string
name) {
2145 throw type_error(
"Got multiple values for keyword argument '" + name +
"'");
2148 [[noreturn]]
static void argument_cast_error() {
2149 throw cast_error(
"Unable to convert call argument to Python object "
2150 "(compile in debug mode for details)");
2153 [[noreturn]]
static void argument_cast_error(std::string
name, std::string type) {
2154 throw cast_error(
"Unable to convert call argument '" + name
2155 +
"' of type '" + type +
"' to Python object");
2164 template <return_value_policy policy,
typename... Args,
2165 typename = enable_if_t<all_of<is_positional<Args>...>::value>>
2171 template <return_value_policy policy,
typename... Args,
2172 typename = enable_if_t<!all_of<is_positional<Args>...>::value>>
2176 constexpr_last<is_positional, Args...>() < constexpr_first<is_keyword_or_ds, Args...>()
2177 && constexpr_last<is_s_unpacking, Args...>() < constexpr_first<is_ds_unpacking, Args...>(),
2178 "Invalid function call: positional args must precede keywords and ** unpacking; "
2179 "* unpacking must precede ** unpacking"
2184 template <
typename Derived>
2185 template <return_value_policy policy,
typename... Args>
2187 return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
2190 template <
typename Derived>
2191 template <return_value_policy policy,
typename... Args>
2193 return operator()<policy>(std::forward<Args>(args)...);
2196 PYBIND11_NAMESPACE_END(detail)
2199 template<typename T>
2200 handle type::handle_of() {
2202 std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value,
2203 "py::type::of<T> only supports the case where T is a registered C++ types."
2206 return detail::get_type_handle(
typeid(T),
true);
2210 #define PYBIND11_MAKE_OPAQUE(...) \
2211 namespace pybind11 { namespace detail { \
2212 template<> class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> { }; \
2217 #define PYBIND11_TYPE(...) __VA_ARGS__
2219 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
Annotation for parent scope.
static constexpr uint8_t status_holder_constructed
Bit values for the non-simple status flags.
Type caster for holder types like std::shared_ptr, etc.
bool isinstance(handle obj)
object operator()(Args &&...args) const
The 'instance' type which needs to be standard layout (need to be able to use 'offsetof') ...
PYBIND11_NOINLINE bool try_load_foreign_module_local(handle src)
void allocate_layout()
Initializes all of the above type/values/holders data (but not the instance values themselves) ...
PyObject * ptr() const
Return the underlying PyObject * pointer.
bool simple_holder_constructed
For simple layout, tracks whether the holder has been constructed.
const handle & inc_ref() const &
bool simple_instance_registered
For simple layout, tracks whether the instance is registered in registered_instances ...
Helper type to replace 'void' in some expressions.
static PYBIND11_NOINLINE void add_patient(handle h)
value_and_holder get_value_and_holder(const type_info *find_type=nullptr, bool throw_if_missing=true)
RAII wrapper that temporarily clears any Python error state.
~loader_life_support()
... and destroyed after it returns
Generic type caster for objects stored on the heap.
void deallocate_layout()
Destroys/deallocates all of the above.
Annotation for function names.
Annotation indicating that a class derives from another given type.
loader_life_support()
A new patient frame is created when a function is entered.
static handle handle_of()
Internal data structure which holds metadata about a bound function (signature, overloads, etc.)
bool owned
If true, the pointer is owned which means we're free to manage it with a holder.