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> 38 class loader_life_support {
44 get_internals().loader_patient_stack.push_back(
nullptr);
49 auto &stack = get_internals().loader_patient_stack;
51 pybind11_fail(
"loader_life_support: internal error");
53 auto ptr = stack.back();
58 if (stack.capacity() > 16 && stack.size() != 0 && stack.capacity() / stack.size() > 2)
59 stack.shrink_to_fit();
65 auto &stack = get_internals().loader_patient_stack;
67 throw cast_error(
"When called outside a bound function, py::cast() cannot " 68 "do Python -> C++ conversions which require the creation " 69 "of temporary values");
71 auto &list_ptr = stack.back();
72 if (list_ptr ==
nullptr) {
73 list_ptr = PyList_New(1);
75 pybind11_fail(
"loader_life_support: error allocating list");
76 PyList_SET_ITEM(list_ptr, 0, h.
inc_ref().
ptr());
78 auto result = PyList_Append(list_ptr, h.
ptr());
80 pybind11_fail(
"loader_life_support: error adding patient");
92 std::vector<PyTypeObject *> check;
93 for (
handle parent : reinterpret_borrow<tuple>(t->tp_bases))
94 check.push_back((PyTypeObject *) parent.ptr());
96 auto const &
type_dict = get_internals().registered_types_py;
97 for (
size_t i = 0;
i < check.size();
i++) {
100 if (!PyType_Check((PyObject *)
type))
continue;
109 for (
auto *
tinfo : it->second) {
114 for (
auto *known : bases) {
115 if (known ==
tinfo) { found =
true;
break; }
117 if (!found) bases.push_back(
tinfo);
120 else if (type->tp_bases) {
123 if (
i + 1 == check.size()) {
130 for (
handle parent : reinterpret_borrow<tuple>(type->tp_bases))
131 check.push_back((PyTypeObject *) parent.ptr());
150 all_type_info_populate(type, ins.first->second);
152 return ins.first->second;
162 if (bases.size() == 0)
164 if (bases.size() > 1)
165 pybind11_fail(
"pybind11::detail::get_type_info: type has multiple pybind11-registered bases");
166 return bases.front();
171 auto it = locals.find(tp);
172 if (it != locals.end())
178 auto &types = get_internals().registered_types_cpp;
179 auto it = types.find(tp);
180 if (it != types.end())
187 bool throw_if_missing =
false) {
193 if (throw_if_missing) {
194 std::string tname = tp.name();
195 detail::clean_type_id(tname);
196 pybind11_fail(
"pybind11::detail::get_type_info: unable to find type info for \"" + tname +
"\"");
203 return handle(type_info ? ((PyObject *) type_info->
type) :
nullptr);
214 inst{i}, index{index}, type{type},
225 return reinterpret_cast<V *&
>(vh[0]);
228 explicit operator bool()
const {
return value_ptr(); }
230 template <
typename H> H &
holder()
const {
231 return reinterpret_cast<H &
>(vh[1]);
244 inst->
nonsimple.
status[index] &= (uint8_t) ~instance::status_holder_constructed;
249 : inst->
nonsimple.
status[index] & instance::status_instance_registered;
257 inst->
nonsimple.
status[index] &= (uint8_t) ~instance::status_instance_registered;
278 : inst{inst}, types{tinfo},
280 types->empty() ? nullptr : (*types)[0] ,
291 curr.
vh += 1 + (*types)[curr.
index]->holder_size_in_ptrs;
293 curr.
type = curr.
index < types->size() ? (*types)[curr.
index] :
nullptr;
304 auto it = begin(), endit =
end();
305 while (it != endit && it->type != find_type) ++it;
309 size_t size() {
return tinfo.size(); }
324 if (!find_type || Py_TYPE(
this) == find_type->
type)
328 auto it = vhs.
find(find_type);
332 if (!throw_if_missing)
336 pybind11_fail(
"pybind11::detail::instance::get_value_and_holder: " 337 "type is not a pybind11 base of the given instance " 338 "(compile in debug mode for type details)");
340 pybind11_fail(
"pybind11::detail::instance::get_value_and_holder: `" +
341 std::string(find_type->
type->tp_name) +
"' is not a pybind11 base of the given `" +
342 std::string(Py_TYPE(
this)->tp_name) +
"' instance");
349 const size_t n_types =
tinfo.size();
352 pybind11_fail(
"instance allocation failed: new instance has no pybind11-registered base types");
359 simple_value_holder[0] =
nullptr;
360 simple_holder_constructed =
false;
361 simple_instance_registered =
false;
369 for (
auto t :
tinfo) {
371 space += t->holder_size_in_ptrs;
373 size_t flags_at = space;
381 #if PY_VERSION_HEX >= 0x03050000 382 nonsimple.values_and_holders = (
void **) PyMem_Calloc(space,
sizeof(
void *));
383 if (!nonsimple.values_and_holders)
throw std::bad_alloc();
385 nonsimple.values_and_holders = (
void **) PyMem_New(
void *, space);
386 if (!nonsimple.values_and_holders)
throw std::bad_alloc();
387 std::memset(nonsimple.values_and_holders, 0, space *
sizeof(
void *));
389 nonsimple.status =
reinterpret_cast<uint8_t *
>(&nonsimple.values_and_holders[flags_at]);
396 PyMem_Free(nonsimple.values_and_holders);
400 handle type = detail::get_type_handle(tp,
false);
407 if (!PyErr_Occurred()) {
408 PyErr_SetString(PyExc_RuntimeError,
"Unknown internal error occurred");
409 return "Unknown internal error occurred";
414 std::string errorString;
416 errorString +=
handle(scope.
type).attr(
"__name__").cast<std::string>();
420 errorString += (std::string)
str(scope.
value);
422 PyErr_NormalizeException(&scope.
type, &scope.
value, &scope.
trace);
424 #if PY_MAJOR_VERSION >= 3 425 if (scope.
trace !=
nullptr)
426 PyException_SetTraceback(scope.
value, scope.
trace);
429 #if !defined(PYPY_VERSION) 431 PyTracebackObject *trace = (PyTracebackObject *) scope.
trace;
434 while (trace->tb_next)
435 trace = trace->tb_next;
437 PyFrameObject *frame = trace->tb_frame;
438 errorString +=
"\n\nAt:\n";
440 int lineno = PyFrame_GetLineNumber(frame);
442 " " +
handle(frame->f_code->co_filename).cast<std::string>() +
444 handle(frame->f_code->co_name).cast<std::string>() +
"\n";
445 frame = frame->f_back;
454 auto &instances = get_internals().registered_instances;
455 auto range = instances.equal_range(ptr);
459 return handle((PyObject *) it->second);
466 #if defined(PYPY_VERSION) 467 return PyThreadState_GET();
468 #elif PY_VERSION_HEX < 0x03000000 469 return _PyThreadState_Current;
470 #elif PY_VERSION_HEX < 0x03050000 471 return (PyThreadState*) _Py_atomic_load_relaxed(&_PyThreadState_Current);
472 #elif PY_VERSION_HEX < 0x03050200 473 return (PyThreadState*) _PyThreadState_Current.value;
475 return _PyThreadState_UncheckedGet();
486 : typeinfo(get_type_info(type_info)), cpptype(&type_info) { }
489 : typeinfo(typeinfo), cpptype(typeinfo ? typeinfo->cpptype : nullptr) { }
492 return load_impl<type_caster_generic>(src, convert);
497 void *(*copy_constructor)(
const void *),
498 void *(*move_constructor)(
const void *),
499 const void *existing_holder =
nullptr) {
503 void *src =
const_cast<void *
>(_src);
507 auto it_instances = get_internals().registered_instances.equal_range(src);
508 for (
auto it_i = it_instances.first; it_i != it_instances.second; ++it_i) {
511 return handle((PyObject *) it_i->second).inc_ref();
516 auto wrapper =
reinterpret_cast<instance *
>(inst.ptr());
517 wrapper->
owned =
false;
521 case return_value_policy::automatic:
522 case return_value_policy::take_ownership:
524 wrapper->owned =
true;
527 case return_value_policy::automatic_reference:
528 case return_value_policy::reference:
530 wrapper->owned =
false;
533 case return_value_policy::copy:
534 if (copy_constructor)
535 valueptr = copy_constructor(src);
537 throw cast_error(
"return_value_policy = copy, but the " 538 "object is non-copyable!");
539 wrapper->owned =
true;
543 if (move_constructor)
544 valueptr = move_constructor(src);
545 else if (copy_constructor)
546 valueptr = copy_constructor(src);
548 throw cast_error(
"return_value_policy = move, but the " 549 "object is neither movable nor copyable!");
550 wrapper->owned =
true;
553 case return_value_policy::reference_internal:
555 wrapper->owned =
false;
560 throw cast_error(
"unhandled return_value_policy: should not happen!");
565 return inst.release();
570 auto *&vptr = v_h.value_ptr();
572 if (vptr ==
nullptr) {
573 auto *type = v_h.type ? v_h.type : typeinfo;
574 if (type->operator_new) {
575 vptr = type->operator_new(type->type_size);
577 #if defined(PYBIND11_CPP17) 578 if (type->type_align > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
579 vptr = ::operator
new(type->type_size,
580 (std::align_val_t) type->type_align);
583 vptr = ::operator
new(type->type_size);
588 bool try_implicit_casts(
handle src,
bool convert) {
589 for (
auto &
cast : typeinfo->implicit_casts) {
591 if (sub_caster.
load(src, convert)) {
598 bool try_direct_conversions(
handle src) {
599 for (
auto &converter : *typeinfo->direct_conversions) {
605 void check_holder_compat() {}
609 if (caster.load(src,
false))
619 if (!
hasattr(pytype, local_key))
622 type_info *foreign_typeinfo = reinterpret_borrow<capsule>(
getattr(pytype, local_key));
638 template <
typename ThisT>
640 if (!src)
return false;
641 if (!typeinfo)
return try_load_foreign_module_local(src);
644 if (!convert)
return false;
649 auto &this_ =
static_cast<ThisT &
>(*this);
650 this_.check_holder_compat();
652 PyTypeObject *srctype = Py_TYPE(src.
ptr());
656 if (srctype == typeinfo->type) {
657 this_.load_value(reinterpret_cast<instance *>(src.
ptr())->get_value_and_holder());
661 else if (PyType_IsSubtype(srctype, typeinfo->type)) {
663 bool no_cpp_mi = typeinfo->simple_type;
671 if (bases.size() == 1 && (no_cpp_mi || bases.front()->type == typeinfo->type)) {
672 this_.load_value(reinterpret_cast<instance *>(src.
ptr())->get_value_and_holder());
678 else if (bases.size() > 1) {
679 for (
auto base : bases) {
680 if (no_cpp_mi ? PyType_IsSubtype(
base->type, typeinfo->type) :
base->type == typeinfo->type) {
681 this_.load_value(reinterpret_cast<instance *>(src.
ptr())->get_value_and_holder(
base));
690 if (this_.try_implicit_casts(src, convert))
696 for (
auto &converter : typeinfo->implicit_conversions) {
697 auto temp = reinterpret_steal<object>(converter(src.
ptr(), typeinfo->type));
698 if (load_impl<ThisT>(temp,
false)) {
703 if (this_.try_direct_conversions(src))
708 if (typeinfo->module_local) {
711 return load(src,
false);
716 return try_load_foreign_module_local(src);
724 const void *src,
const std::type_info &cast_type,
const std::type_info *rtti_type =
nullptr) {
725 if (
auto *tpi = get_type_info(cast_type))
726 return {src,
const_cast<const type_info *
>(tpi)};
729 std::string tname = rtti_type ? rtti_type->name() : cast_type.name();
730 detail::clean_type_id(tname);
731 std::string
msg =
"Unregistered type : " + tname;
732 PyErr_SetString(PyExc_TypeError, msg.c_str());
733 return {
nullptr,
nullptr};
736 const type_info *typeinfo =
nullptr;
737 const std::type_info *cpptype =
nullptr;
748 template <
typename T>
751 typename std::add_pointer<intrinsic_t<T>>
::type,
752 typename std::add_lvalue_reference<intrinsic_t<T>>::type>;
761 template <
typename T>
764 typename std::add_pointer<intrinsic_t<T>>
::type,
766 typename std::add_rvalue_reference<intrinsic_t<T>>
::type,
767 typename std::add_lvalue_reference<intrinsic_t<T>>::type>>;
778 std::is_same<typename Container::value_type &, typename Container::reference>
781 #if !defined(PYBIND11_CPP17) 785 :
all_of<is_copy_constructible<T1>, is_copy_constructible<T2>> {};
807 template <
typename itype,
typename SFINAE =
void>
810 static const void *
get(
const itype *src,
const std::type_info*&) {
return src; }
812 template <
typename itype>
815 static const void *
get(
const itype *src,
const std::type_info*&
type) {
816 type = src ? &
typeid(*src) :
nullptr;
817 return dynamic_cast<const void*
>(src);
823 template <
typename type>
class type_caster_base :
public type_caster_generic {
828 static constexpr
auto name = _<type>();
834 if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference)
835 policy = return_value_policy::copy;
836 return cast(&src, policy, parent);
847 auto &cast_type =
typeid(
itype);
848 const std::type_info *instance_type =
nullptr;
850 if (instance_type && !
same_type(cast_type, *instance_type)) {
859 if (
const auto *tpi = get_type_info(*instance_type))
864 return type_caster_generic::src_and_type(src, cast_type, instance_type);
868 auto st = src_and_type(src);
870 st.first, policy, parent, st.second,
871 make_copy_constructor(src), make_move_constructor(src));
875 auto st = src_and_type(src);
877 st.first, return_value_policy::take_ownership, {}, st.second,
878 nullptr,
nullptr, holder);
893 return [](
const void *
arg) ->
void * {
894 return new T(*reinterpret_cast<const T *>(
arg));
900 return [](
const void *
arg) ->
void * {
901 return new T(
std::move(*const_cast<T *>(reinterpret_cast<const T *>(
arg))));
922 template <
typename type>
class type_caster<std::reference_wrapper<type>> {
928 "std::reference_wrapper<T> caster requires T to have a caster with an `T &` operator");
931 static constexpr
auto name = caster_t::name;
934 if (policy == return_value_policy::take_ownership || policy == return_value_policy::automatic)
935 policy = return_value_policy::automatic_reference;
938 template <
typename T>
using cast_op_type = std::reference_wrapper<type>;
942 #define PYBIND11_TYPE_CASTER(type, py_name) \ 946 static constexpr auto name = py_name; \ 947 template <typename T_, enable_if_t<std::is_same<type, remove_cv_t<T_>>::value, int> = 0> \ 948 static handle cast(T_ *src, return_value_policy policy, handle parent) { \ 949 if (!src) return none().release(); \ 950 if (policy == return_value_policy::take_ownership) { \ 951 auto h = cast(std::move(*src), policy, parent); delete src; return h; \ 953 return cast(*src, policy, parent); \ 956 operator type*() { return &value; } \ 957 operator type&() { return value; } \ 958 operator type&&() && { return std::move(value); } \ 959 template <typename T_> using cast_op_type = pybind11::detail::movable_cast_op_type<T_> 963 std::is_same<CharT, char>,
964 std::is_same<CharT, char16_t>,
965 std::is_same<CharT, char32_t>,
966 std::is_same<CharT, wchar_t>
969 template <
typename T>
983 if (convert || PyFloat_Check(src.
ptr()))
984 py_value = (
py_type) PyFloat_AsDouble(src.
ptr());
987 }
else if (PyFloat_Check(src.
ptr())) {
990 py_value = as_unsigned<py_type>(src.
ptr());
992 py_value =
sizeof(T) <=
sizeof(
long)
997 bool py_err = py_value == (
py_type) -1 && PyErr_Occurred();
1001 (py_value < (
py_type) (std::numeric_limits<T>::min)() ||
1002 py_value > (
py_type) (std::numeric_limits<T>::max)()))) {
1003 bool type_error = py_err && PyErr_ExceptionMatches(
1004 #
if PY_VERSION_HEX < 0x03000000 && !defined(PYPY_VERSION)
1011 if (type_error && convert && PyNumber_Check(src.
ptr())) {
1013 ? PyNumber_Float(src.
ptr())
1014 : PyNumber_Long(src.
ptr()));
1016 return load(tmp,
false);
1021 value = (T) py_value;
1025 template<
typename U = T>
1028 return PyFloat_FromDouble((
double) src);
1031 template<
typename U = T>
1037 template<
typename U = T>
1043 template<
typename U = T>
1046 return PyLong_FromLongLong((
long long) src);
1049 template<
typename U = T>
1052 return PyLong_FromUnsignedLongLong((
unsigned long long) src);
1086 if (isinstance<capsule>(h)) {
1087 value = reinterpret_borrow<capsule>(h);
1093 if (bases.size() == 1) {
1111 static constexpr
auto name =
_(
"capsule");
1121 if (!src)
return false;
1122 else if (src.
ptr() == Py_True) {
value =
true;
return true; }
1123 else if (src.
ptr() == Py_False) {
value =
false;
return true; }
1124 else if (convert || !strcmp(
"numpy.bool_", Py_TYPE(src.
ptr())->tp_name)) {
1127 Py_ssize_t res = -1;
1131 #if defined(PYPY_VERSION) 1134 res = PyObject_IsTrue(src.
ptr());
1139 else if (
auto tp_as_number = src.
ptr()->ob_type->tp_as_number) {
1145 if (res == 0 || res == 1) {
1153 return handle(src ? Py_True : Py_False).inc_ref();
1160 using CharT =
typename StringType::value_type;
1169 "Unsupported wchar_t size != 2/4");
1170 static constexpr
size_t UTF_N = 8 *
sizeof(
CharT);
1173 #if PY_MAJOR_VERSION < 3 1179 }
else if (!PyUnicode_Check(load_src.
ptr())) {
1180 #if PY_MAJOR_VERSION >= 3 1181 return load_bytes(load_src);
1183 if (
sizeof(
CharT) == 1) {
1184 return load_bytes(load_src);
1191 temp = reinterpret_steal<object>(PyUnicode_FromObject(load_src.
ptr()));
1192 if (!temp) { PyErr_Clear();
return false; }
1197 object utfNbytes = reinterpret_steal<object>(PyUnicode_AsEncodedString(
1198 load_src.
ptr(), UTF_N == 8 ?
"utf-8" : UTF_N == 16 ?
"utf-16" :
"utf-32",
nullptr));
1199 if (!utfNbytes) { PyErr_Clear();
return false; }
1203 if (UTF_N > 8) { buffer++; length--; }
1204 value = StringType(buffer, length);
1214 const char *
buffer =
reinterpret_cast<const char *
>(src.data());
1216 handle s = decode_utfN(buffer, nbytes);
1225 #if !defined(PYPY_VERSION) 1227 UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes,
nullptr) :
1228 UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes,
nullptr,
nullptr) :
1229 PyUnicode_DecodeUTF32(buffer, nbytes,
nullptr,
nullptr);
1235 return PyUnicode_Decode(buffer, nbytes, UTF_N == 8 ?
"utf-8" : UTF_N == 16 ?
"utf-16" :
"utf-32",
nullptr);
1242 template <
typename C = CharT>
1257 template <
typename C = CharT>
1261 template <
typename CharT,
class Traits,
class Allocator>
1263 :
string_caster<std::basic_string<CharT, Traits, Allocator>> {};
1265 #ifdef PYBIND11_HAS_STRING_VIEW 1266 template <
typename CharT,
class Traits>
1268 :
string_caster<std::basic_string_view<CharT, Traits>, true> {};
1281 if (!src)
return false;
1284 if (!convert)
return false;
1288 return str_caster.
load(src, convert);
1298 handle s = PyUnicode_DecodeLatin1((
const char *) &src, 1,
nullptr);
1305 operator CharT*() {
return none ? nullptr :
const_cast<CharT *
>(
static_cast<StringType &
>(str_caster).
c_str()); }
1308 throw value_error(
"Cannot convert None to a character");
1311 size_t str_len =
value.size();
1313 throw value_error(
"Cannot convert empty string to a character");
1320 if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) {
1321 unsigned char v0 =
static_cast<unsigned char>(
value[0]);
1322 size_t char0_bytes = !(v0 & 0x80) ? 1 :
1323 (v0 & 0xE0) == 0xC0 ? 2 :
1324 (v0 & 0xF0) == 0xE0 ? 3 :
1327 if (char0_bytes == str_len) {
1329 if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) {
1330 one_char =
static_cast<CharT
>(((v0 & 3) << 6) + (
static_cast<unsigned char>(
value[1]) & 0x3F));
1334 throw value_error(
"Character code point not in range(0x100)");
1341 else if (StringCaster::UTF_N == 16 && str_len == 2) {
1342 one_char =
static_cast<CharT
>(
value[0]);
1343 if (one_char >= 0xD800 && one_char < 0xE000)
1344 throw value_error(
"Character code point not in range(0x10000)");
1348 throw value_error(
"Expected a character, but multi-character string found");
1350 one_char =
value[0];
1359 template <
template<
typename...>
class Tuple,
typename... Ts>
class tuple_caster {
1360 using type = Tuple<Ts...>;
1361 static constexpr
auto size =
sizeof...(Ts);
1366 if (!isinstance<sequence>(src))
1368 const auto seq = reinterpret_borrow<sequence>(src);
1369 if (seq.size() !=
size)
1371 return load_impl(seq, convert,
indices{});
1374 template <
typename T>
1376 return cast_impl(std::forward<T>(src), policy, parent,
indices{});
1387 template <
size_t... Is>
1389 template <
size_t... Is>
1394 template <
size_t... Is>
1396 for (
bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...})
1403 template <
typename T,
size_t... Is>
1405 std::array<object, size> entries{{
1406 reinterpret_steal<object>(
make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...
1408 for (
const auto &entry: entries)
1413 for (
auto & entry: entries)
1414 PyTuple_SET_ITEM(result.
ptr(), counter++, entry.release().ptr());
1421 template <
typename T1,
typename T2>
class type_caster<std::pair<T1, T2>>
1429 template <
typename T>
1431 static auto get(
const T &p) -> decltype(p.get()) {
return p.
get(); }
1435 template <
typename type,
typename holder_type>
1440 "Holder classes are only supported for custom types");
1443 using base::typeinfo;
1447 return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
1450 explicit operator type*() {
return this->
value; }
1451 explicit operator type&() {
return *(this->
value); }
1452 explicit operator holder_type*() {
return std::addressof(holder); }
1456 #if defined(__ICC) || defined(__INTEL_COMPILER) 1457 operator holder_type&() {
return holder; }
1459 explicit operator holder_type&() {
return holder; }
1470 if (typeinfo->default_holder)
1471 throw cast_error(
"Unable to load a custom holder type from a default-holder instance");
1475 if (v_h.holder_constructed()) {
1476 value = v_h.value_ptr();
1477 holder = v_h.template holder<holder_type>();
1480 throw cast_error(
"Unable to cast from non-held to held instance (T& to Holder<T>) " 1482 "(compile in debug mode for type information)");
1484 "of type '" + type_id<holder_type>() +
"''");
1494 for (
auto &
cast : typeinfo->implicit_casts) {
1496 if (sub_caster.
load(src, convert)) {
1498 holder = holder_type(sub_caster.
holder, (type *)
value);
1512 template <
typename T>
1515 template <
typename type,
typename holder_type>
1518 "Holder classes are only supported for custom types");
1527 template <
typename type,
typename deleter>
1531 template <
typename type,
typename holder_type>
1539 #define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \ 1540 namespace pybind11 { namespace detail { \ 1541 template <typename type> \ 1542 struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__> { }; \ 1543 template <typename type> \ 1544 class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \ 1545 : public type_caster_holder<type, holder_type> { }; \ 1550 std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
1560 template <
typename type>
1567 if (!isinstance<type>(src))
1569 value = reinterpret_borrow<type>(src);
1579 template <
typename T>
1592 std::is_void, std::is_pointer, std::is_reference, std::is_const
1594 template <
typename T,
typename SFINAE =
void>
struct move_always : std::false_type {};
1598 std::is_move_constructible<T>,
1599 std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&>
1600 >::value>> : std::true_type {};
1605 std::is_move_constructible<T>,
1606 std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&>
1607 >::value>> : std::true_type {};
1628 detail::
enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
1638 if (!conv.
load(handle,
true)) {
1640 throw cast_error(
"Unable to cast Python instance to C++ type (compile in debug mode for details)");
1642 throw cast_error(
"Unable to cast Python instance of type " +
1643 (std::string)
str(handle.
get_type()) +
" to C++ type '" + type_id<T>() +
"'");
1660 using namespace detail;
1662 "Unable to cast type to reference: value is local to type caster");
1663 return cast_op<T>(load_type<T>(
handle));
1668 T
cast(
const handle &
handle) {
return T(reinterpret_borrow<object>(handle)); }
1673 handle parent =
handle()) {
1674 if (policy == return_value_policy::automatic)
1676 else if (policy == return_value_policy::automatic_reference)
1681 template <
typename T> T
handle::cast()
const {
return pybind11::cast<T>(*this); }
1684 template <
typename T>
1686 if (obj.ref_count() > 1)
1688 throw cast_error(
"Unable to cast Python instance to C++ rvalue: instance has multiple references" 1689 " (compile in debug mode for details)");
1691 throw cast_error(
"Unable to move from Python " + (std::string)
str(obj.get_type()) +
1692 " instance to C++ " + type_id<T>() +
" instance: instance has multiple references");
1696 T
ret =
std::move(detail::load_type<T>(obj).
operator T&());
1709 if (
object.ref_count() > 1)
1718 template <
typename T> T
object::cast() const & {
return pybind11::cast<T>(*this); }
1736 return cast_op<T>(
load_type(caster, o));
1739 pybind11_fail(
"Internal error: cast_ref fallback invoked"); }
1745 return pybind11::cast<T>(
std::move(o)); }
1747 pybind11_fail(
"Internal error: cast_safe fallback invoked"); }
1752 template <return_value_policy policy = return_value_policy::automatic_reference>
1757 constexpr
size_t size =
sizeof...(Args);
1758 std::array<object, size>
args {
1760 std::forward<Args>(args_), policy,
nullptr))... }
1762 for (
size_t i = 0;
i <
args.size();
i++) {
1765 throw cast_error(
"make_tuple(): unable to convert arguments to Python object (compile in debug mode for details)");
1767 std::array<std::string, size> argtypes { {type_id<Args>()...} };
1768 throw cast_error(
"make_tuple(): unable to convert argument of type '" +
1769 argtypes[i] +
"' to Python object");
1775 for (
auto &arg_value :
args)
1776 PyTuple_SET_ITEM(result.
ptr(), counter++, arg_value.release().ptr());
1784 constexpr
explicit arg(
const char *name =
nullptr) : name(name), flag_noconvert(false), flag_none(true) { }
1786 template <
typename T>
arg_v operator=(T &&value)
const;
1790 arg &
none(
bool flag =
true) { flag_none = flag;
return *
this; }
1801 template <
typename T>
1808 #if !defined(NDEBUG) 1809 ,
type(type_id<T>())
1815 template <
typename T>
1816 arg_v(
const char *name, T &&
x,
const char *descr =
nullptr)
1817 :
arg_v(
arg(name), std::forward<T>(
x), descr) { }
1820 template <
typename T>
1822 :
arg_v(
arg(base), std::forward<T>(
x), descr) { }
1828 arg_v &
none(
bool flag =
true) { arg::none(flag);
return *
this; }
1834 #if !defined(NDEBUG) 1840 template <
typename T>
1846 inline namespace literals {
1850 constexpr
arg operator"" _a(
const char *name,
size_t) {
return arg(name); }
1856 struct function_record;
1884 template <
typename... Args>
1892 kwargs_pos = constexpr_first<argument_is_kwargs, Args...>() - (int)
sizeof...(Args);
1894 static constexpr
bool args_kwargs_are_last = kwargs_pos >= - 1 && args_pos >= kwargs_pos - 1;
1896 static_assert(args_kwargs_are_last,
"py::args/py::kwargs are only permitted as the last argument(s) of a function");
1899 static constexpr
bool has_kwargs = kwargs_pos < 0;
1900 static constexpr
bool has_args = args_pos < 0;
1905 return load_impl_sequence(call,
indices{});
1908 template <
typename Return,
typename Guard,
typename Func>
1910 return std::move(*this).template call_impl<Return>(std::forward<Func>(f),
indices{}, Guard{});
1913 template <
typename Return,
typename Guard,
typename Func>
1915 std::move(*this).template call_impl<Return>(std::forward<Func>(f),
indices{}, Guard{});
1923 template <
size_t... Is>
1925 for (
bool r : {std::get<Is>(argcasters).load(call.
args[Is], call.
args_convert[Is])...})
1931 template <
typename Return,
typename Func,
size_t... Is,
typename Guard>
1933 return std::forward<Func>(f)(cast_op<Args>(
std::move(std::get<Is>(argcasters)))...);
1941 template <return_value_policy policy>
1944 template <
typename... Ts>
1955 PyObject *result = PyObject_CallObject(ptr, m_args.ptr());
1958 return reinterpret_steal<object>(result);
1966 template <return_value_policy policy>
1969 template <
typename... Ts>
1973 auto args_list =
list();
1974 int _[] = { 0, (process(args_list, std::forward<Ts>(values)), 0)... };
1988 PyObject *result = PyObject_Call(ptr, m_args.ptr(), m_kwargs.ptr());
1991 return reinterpret_steal<object>(result);
1995 template <
typename T>
2000 argument_cast_error();
2002 argument_cast_error(
std::to_string(args_list.size()), type_id<T>());
2005 args_list.append(o);
2009 for (
const auto &a : ap)
2010 args_list.append(a);
2016 nameless_argument_error();
2018 nameless_argument_error(a.
type);
2021 if (m_kwargs.contains(a.
name)) {
2023 multiple_values_error();
2025 multiple_values_error(a.
name);
2030 argument_cast_error();
2032 argument_cast_error(a.
name, a.
type);
2041 for (
const auto &k : reinterpret_borrow<dict>(kp)) {
2042 if (m_kwargs.contains(k.first)) {
2044 multiple_values_error();
2046 multiple_values_error(
str(k.first));
2049 m_kwargs[k.first] = k.second;
2054 throw type_error(
"Got kwargs without a name; only named arguments " 2055 "may be passed via py::arg() to a python function call. " 2056 "(compile in debug mode for details)");
2059 throw type_error(
"Got kwargs without a name of type '" + type +
"'; only named " 2060 "arguments may be passed via py::arg() to a python function call. ");
2063 throw type_error(
"Got multiple values for keyword argument " 2064 "(compile in debug mode for details)");
2068 throw type_error(
"Got multiple values for keyword argument '" + name +
"'");
2072 throw cast_error(
"Unable to convert call argument to Python object " 2073 "(compile in debug mode for details)");
2077 throw cast_error(
"Unable to convert call argument '" + name
2078 +
"' of type '" + type +
"' to Python object");
2099 constexpr_last<is_positional, Args...>() < constexpr_first<is_keyword_or_ds, Args...>()
2100 && constexpr_last<is_s_unpacking, Args...>() < constexpr_first<is_ds_unpacking, Args...>(),
2101 "Invalid function call: positional args must precede keywords and ** unpacking; " 2102 "* unpacking must precede ** unpacking" 2107 template <
typename Derived>
2110 return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
2113 template <
typename Derived>
2116 return operator()<policy>(std::forward<Args>(args)...);
2121 #define PYBIND11_MAKE_OPAQUE(...) \ 2122 namespace pybind11 { namespace detail { \ 2123 template<> class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> { }; \ 2128 #define PYBIND11_TYPE(...) __VA_ARGS__
bool load_bytes(enable_if_t< sizeof(C) !=1, handle >)
nonsimple_values_and_holders nonsimple
static handle cast(const handle &src, return_value_policy, handle)
enable_if_t<!std::is_void< Return >::value, Return > call(Func &&f) &&
type implicit_cast(index_sequence< Is... >) &
type implicit_cast(index_sequence< Is... >) &&
static handle cast(bool src, return_value_policy, handle)
handle get_type() const
Return a handle to the Python type object underlying the instance.
static void argument_cast_error()
std::vector< handle > args
Arguments passed to the function:
T reinterpret_steal(handle h)
#define PYBIND11_NB_BOOL(ptr)
void * simple_value_holder[1+instance_simple_holder_in_ptrs()]
bool load(handle src, bool convert)
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)
#define PYBIND11_NAMESPACE
static return_value_policy policy(return_value_policy p)
value_and_holder * operator->()
bool try_implicit_casts(handle src, bool convert)
static return_value_policy policy(return_value_policy p)
PyObject * ptr() const
Return the underlying PyObject * pointer.
object getattr(handle obj, handle name)
static handle cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence< Is... >)
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)
static auto make_move_constructor(const T *x) -> decltype(new T(std::move(*const_cast< T *>(x))), Constructor
static handle cast(const StringType &src, return_value_policy, handle)
static auto make_copy_constructor(const T *x) -> decltype(new T(*x), Constructor
static void multiple_values_error()
#define PYBIND11_BOOL_ATTR
bool load(handle src, bool)
enable_if_t< std::is_void< Return >::value, void_type > call(Func &&f) &&
bool flag_noconvert
If set, do not allow conversion (requires a supporting type caster!)
Helper class which collects positional, keyword, * and ** arguments for a Python function call...
RAII wrapper that temporarily clears any Python error state.
static void nameless_argument_error()
const char * name
If non-null, this is a named kwargs argument.
bool load_impl(const sequence &seq, bool convert, index_sequence< Is... >)
std::is_base_of< pyobject_tag, remove_reference_t< T > > is_pyobject
bool load(handle src, bool)
std::string error_string()
glibc defines I as a macro which breaks things, e.g., boost template names
negation< all_of< negation< Ts >... > > any_of
detail::type_info * get_local_type_info(const std::type_index &tp)
void add_patient(PyObject *nurse, PyObject *patient)
std::string type
The C++ type name of the default value (only available when compiled in debug mode) ...
detail::enable_if_t< detail::move_never< T >::value, T > cast(object &&object)
static constexpr size_t size_in_ptrs(size_t s)
bool operator!=(const iterator &other)
std::vector< detail::type_info * > type_vec
void set_holder_constructed(bool v=true)
std::is_same< bools< Ts::value..., true >, bools< true, Ts::value... > > all_of
bool load(handle src, bool convert)
bool load(handle src, bool convert)
type_caster_base(const std::type_info &info)
constexpr descr< N+2, Ts... > type_descr(const descr< N, Ts... > &descr)
PyThreadState * get_thread_state_unchecked()
static void nameless_argument_error(std::string type)
bool holder_constructed() const
void check_holder_compat()
make_index_sequence< sizeof...(Args)> indices
object object_or_cast(T &&o)
static constexpr bool load_impl(const sequence &, bool, index_sequence<>)
type_map< type_info * > & registered_local_types_cpp()
Works like internals.registered_types_cpp, but for module-local registered types: ...
return_value_policy handle const detail::type_info void *(*) void *(*) const void const type_info src_and_type)(const void *src, const std::type_info &cast_type, const std::type_info *rtti_type=nullptr)
bool load_bytes(enable_if_t< sizeof(C)==1, handle > src)
arg_v(const char *name, T &&x, const char *descr=nullptr)
Direct construction with name, default, and description.
handle parent
The parent, if any.
Internal data structure which holds metadata about a bound function (signature, overloads, etc.)
detail::type_info * get_global_type_info(const std::type_index &tp)
const std::vector< detail::type_info * > & all_type_info(PyTypeObject *type)
Internal data associated with a single function call.
constexpr descr< N - 1 > _(char const(&text)[N])
iterator(instance *inst, const type_vec *tinfo)
handle init_self
If this is a call to an initializer, this argument contains self
std::is_same< intrinsic_t< Arg >, args > argument_is_args
const tuple & args() const &
void process(list &args_list, detail::args_proxy ap)
#define PYBIND11_NOINLINE
void(* init_instance)(instance *, const void *)
static handle cast_holder(const itype *src, const void *holder)
The 'instance' type which needs to be standard layout (need to be able to use 'offsetof') ...
detail::cast_op_type< T > cast_op_type
Return call_impl(Func &&f, index_sequence< Is... >, Guard &&)
#define PYBIND11_LONG_FROM_SIGNED(o)
PyObject * make_new_instance(PyTypeObject *type)
typename std::enable_if< B, T >::type enable_if_t
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
bool load(handle src, bool convert)
static handle cast(const void *ptr, return_value_policy, handle)
bool same_type(const std::type_info &lhs, const std::type_info &rhs)
object call(PyObject *ptr) const
Call a Python function and pass the collected arguments.
static Constructor make_move_constructor(...)
std::vector< type_info * > & bases
loader_life_support()
A new patient frame is created when a function is entered.
static handle cast(T, return_value_policy, handle)
bool is_none() const
Equivalent to obj is None in Python.
arg_v & none(bool flag=true)
Same as arg::nonone(), but returns *this as arg_v&, not arg&.
bool load(handle h, bool)
size_t function_call handle ret
bool simple_holder_constructed
For simple layout, tracks whether the holder has been constructed.
bool isinstance_generic(handle obj, const std::type_info &tp)
~loader_life_support()
... and destroyed after it returns
static handle decode_utfN(const char *buffer, ssize_t nbytes)
void process(list &, arg_v a)
static bool try_direct_conversions(handle)
bool load(handle src, bool convert)
bool load(handle src, bool convert)
static handle cast(const itype *src, return_value_policy policy, handle parent)
#define NAMESPACE_END(name)
void process(list &args_list, T &&x)
const char * descr
The (optional) description of the default value.
value_and_holder(size_t index)
pybind11::detail::cast_op_type< _T > cast_op_type
return isinstance(obj, type)
const std::type_info * cpptype
const detail::type_info * type
static bool load_impl_sequence(function_call &, index_sequence<>)
make_caster< T > load_type(const handle &handle)
static void multiple_values_error(std::string name)
typename intrinsic_type< T >::type intrinsic_t
return_value_policy
Approach used to cast a previously unknown C++ instance into a Python object.
void *(*)(const void *) Constructor
typename std::basic_string< CharT, Traits, Allocator > ::value_type CharT
object value
The default value.
bool owned
If true, the pointer is owned which means we're free to manage it with a holder.
size_t function_call & call
enable_if_t< cast_is_temporary_value_reference< T >::value, T > cast_safe(object &&)
static handle cast(holder_type &&src, return_value_policy, handle)
typename make_index_sequence_impl< N >::type make_index_sequence
#define PYBIND11_BYTES_NAME
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
static handle cast(itype &&src, return_value_policy, handle parent)
static void argument_cast_error(std::string name, std::string type)
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)
static std::enable_if< std::is_floating_point< U >::value, handle >::type cast(U src, return_value_policy, handle)
tuple make_tuple(Args &&... args_)
value_and_holder & operator*()
void cast_safe< void >(object &&)
arg_v(const arg &base, T &&x, const char *descr=nullptr)
Called internally when invoking py::arg("a") = value
std::tuple< make_caster< Args >... > argcasters
void *(* module_local_load)(PyObject *, const type_info *)
bool load_impl_sequence(function_call &call, index_sequence< Is... >)
Generic type caster for objects stored on the heap.
std::pair< decltype(internals::registered_types_py)::iterator, bool > all_type_info_get_cache(PyTypeObject *type)
#define PYBIND11_MODULE_LOCAL_ID
typename caster_t::template cast_op_type< type > subcaster_cast_op_type
typename std::conditional< B, T, F >::type conditional_t
arg & none(bool flag=true)
Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args) ...
static Constructor make_copy_constructor(...)
const std::type_info & tp
std::reference_wrapper< type > cast_op_type
constexpr int constexpr_first()
const dict & kwargs() const &
#define PYBIND11_BYTES_CHECK
static handle cast(T &&src, return_value_policy policy, handle parent)
simple_collector(Ts &&...values)
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
static handle cast(CharT src, return_value_policy policy, handle parent)
bool operator==(const iterator &other)
const function_record & func
The function data:
value_and_holder(instance *i, const detail::type_info *type, size_t vpos, size_t index)
std::integral_constant< bool, B > bool_constant
Backports of std::bool_constant and std::negation to accommodate older compilers. ...
const tuple & args() const &
Annotation indicating that a class derives from another given type.
const detail::type_info * type
Annotation for function names.
void set_instance_registered(bool v=true)
#define PYBIND11_LONG_FROM_UNSIGNED(o)
arg_v(arg &&base, T &&x, const char *descr=nullptr)
const char * c_str(Args &&...args)
make_index_sequence< size > indices
enable_if_t<!cast_is_temporary_value_reference< T >::value, T > cast_ref(object &&, overload_unused &)
std::vector< bool > args_convert
The convert value the arguments should be loaded with.
detail::enable_if_t<!detail::move_never< T >::value, T > move(object &&obj)
Tuple< make_caster< Ts >... > subcasters
conditional_t< std::is_floating_point< T >::value, double, _py_type_1 > py_type
Helper type to replace 'void' in some expressions.
static handle cast(const holder_type &src, return_value_policy, handle)
unpacking_collector< policy > collect_arguments(Args &&...args)
Collect all arguments, including keywords and unpacking (only instantiated when needed) ...
conditional_t< is_copy_constructible< holder_type >::value, copyable_holder_caster< type, holder_type >, move_only_holder_caster< type, holder_type > > type_caster_holder
std::is_same< intrinsic_t< Arg >, kwargs > argument_is_kwargs
conditional_t< std::is_signed< T >::value, _py_type_0, typename std::make_unsigned< _py_type_0 >::type > _py_type_1
object call(PyObject *ptr) const
Call a Python function and pass the collected arguments.
#define PYBIND11_STRING_NAME
void ignore_unused(const int *)
Ignore that a variable is unused in compiler warnings.
Helper class which loads arguments for C++ functions called from Python.
unpacking_collector(Ts &&...values)
any_of< std::is_same< CharT, char >, std::is_same< CharT, char16_t >, std::is_same< CharT, char32_t >, std::is_same< CharT, wchar_t > > is_std_char_type
constexpr size_t instance_simple_holder_in_ptrs()
arg & noconvert(bool flag=true)
Indicate that the type should not be converted in the type caster.
bool try_implicit_casts(handle, bool)
Type caster for holder types like std::shared_ptr, etc.
type_caster_generic(const type_info *typeinfo)
#define PYBIND11_BYTES_AS_STRING
#define NAMESPACE_BEGIN(name)
Thrown when pybind11::cast or handle::call fail due to a type casting error.
make_caster< T >::template cast_op_type< typename std::add_rvalue_reference< T >::type > cast_op(make_caster< T > &&caster)
T cast(const handle &handle)
static handle cast(const std::reference_wrapper< type > &src, return_value_policy policy, handle parent)
arg_v & noconvert(bool flag=true)
Same as arg::noconvert(), but returns *this as arg_v&, not arg&.
conditional_t< cast_is_temporary_value_reference< ret_type >::value, make_caster< ret_type >, overload_unused > overload_caster_t
bool load(handle src, bool convert)
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)
conditional_t< sizeof(T)<=sizeof(long), long, long long > _py_type_0
#define PYBIND11_BYTES_SIZE
bool simple_instance_registered
For simple layout, tracks whether the instance is registered in registered_instances ...
static std::pair< const void *, const type_info * > src_and_type(const itype *src)
type_caster< intrinsic_t< type > > make_caster
bool load(handle src, bool)
iterator find(const type_info *find_type)
constexpr arg(const char *name=nullptr)
Constructs an argument with the name of the argument; if null or omitted, this is a positional argume...
static handle cast(const CharT *src, return_value_policy policy, handle parent)
static auto get(const T &p) -> decltype(p.get())
static handle cast(const itype &src, return_value_policy policy, handle parent)
bool load_value(value_and_holder &&v_h)
bool load_args(function_call &call)
void process(list &, detail::kwargs_proxy kp)
const std::type_info & tinfo
#define PYBIND11_TYPE_CASTER(type, py_name)
bool flag_none
If set (the default), allow None to be passed to this argument.
typename std::enable_if< B, T >::type enable_if_t
from cpp_future import (convenient aliases from C++14/17)
const handle & inc_ref() const &
auto to_string(T &&value) -> decltype(std::forward< T >(value))
Convert an object to a string (directly forward if this can become a string)
void keep_alive_impl(handle nurse, handle patient)
std::basic_string< CharT > StringType
bool hasattr(handle obj, handle name)
values_and_holders(instance *inst)
constexpr descr< 0 > concat()
bool instance_registered() const
#define PYBIND11_LONG_AS_LONGLONG(o)
void ** values_and_holders