cppyabm
1.0.17
An agent-based library to integrate C++ and Python
|
|
Go to the documentation of this file.
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
57 auto ptr = stack.back();
62 if (stack.capacity() > 16 && !stack.empty() && stack.capacity() / stack.size() > 2)
63 stack.shrink_to_fit();
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);
80 PyList_SET_ITEM(list_ptr, 0, h.
inc_ref().
ptr());
82 auto result = PyList_Append(list_ptr, h.
ptr());
96 std::vector<PyTypeObject *> check;
97 for (
handle parent : reinterpret_borrow<tuple>(t->tp_bases))
98 check.push_back((PyTypeObject *) parent.ptr());
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());
156 return ins.first->second;
168 if (bases.size() > 1)
169 pybind11_fail(
"pybind11::detail::get_type_info: type has multiple pybind11-registered bases");
170 return bases.front();
175 auto it = locals.find(tp);
176 if (it != locals.end())
183 auto it = types.find(tp);
184 if (it != types.end())
191 bool throw_if_missing =
false) {
197 if (throw_if_missing) {
198 std::string tname = tp.name();
200 pybind11_fail(
"pybind11::detail::get_type_info: unable to find type info for \"" + tname +
"\"");
212 const detail::type_info *tinfo) {
214 for (
auto it_i = it_instances.first; it_i != it_instances.second; ++it_i) {
216 if (instance_type &&
same_type(*instance_type->cpptype, *tinfo->cpptype))
226 const detail::type_info *
type =
nullptr;
242 return reinterpret_cast<V *&
>(
vh[0]);
247 template <
typename H> H &
holder()
const {
248 return reinterpret_cast<H &
>(
vh[1]);
282 using type_vec = std::vector<detail::type_info *>;
283 const type_vec &tinfo;
291 const type_vec *types =
nullptr;
295 : inst{inst}, types{tinfo},
297 types->empty() ?
nullptr : (*types)[0] ,
308 curr.
vh += 1 + (*types)[curr.
index]->holder_size_in_ptrs;
310 curr.
type = curr.
index < types->size() ? (*types)[curr.
index] :
nullptr;
322 while (it != endit && it->type != find_type) ++it;
326 size_t size() {
return tinfo.size(); }
341 if (!find_type || Py_TYPE(
this) == find_type->
type)
344 detail::values_and_holders vhs(
this);
345 auto it = vhs.find(find_type);
349 if (!throw_if_missing)
353 pybind11_fail(
"pybind11::detail::instance::get_value_and_holder: "
354 "type is not a pybind11 base of the given instance "
355 "(compile in debug mode for type details)");
357 pybind11_fail(
"pybind11::detail::instance::get_value_and_holder: `" +
366 const size_t n_types = tinfo.size();
369 pybind11_fail(
"instance allocation failed: new instance has no pybind11-registered base types");
386 for (
auto t : tinfo) {
388 space += t->holder_size_in_ptrs;
390 size_t flags_at =
space;
391 space += size_in_ptrs(n_types);
398 #if PY_VERSION_HEX >= 0x03050000
424 if (!PyErr_Occurred()) {
425 PyErr_SetString(PyExc_RuntimeError,
"Unknown internal error occurred");
426 return "Unknown internal error occurred";
431 std::string errorString;
433 errorString +=
handle(
scope.type).attr(
"__name__").
cast<std::string>();
441 #if PY_MAJOR_VERSION >= 3
442 if (
scope.trace !=
nullptr)
446 #if !defined(PYPY_VERSION)
448 auto *trace = (PyTracebackObject *)
scope.trace;
451 while (trace->tb_next)
452 trace = trace->tb_next;
454 PyFrameObject *frame = trace->tb_frame;
455 errorString +=
"\n\nAt:\n";
457 int lineno = PyFrame_GetLineNumber(frame);
459 " " +
handle(frame->f_code->co_filename).
cast<std::string>() +
460 "(" + std::to_string(lineno) +
"): " +
461 handle(frame->f_code->co_name).
cast<std::string>() +
"\n";
462 frame = frame->f_back;
472 auto range = instances.equal_range(ptr);
473 for (
auto it = range.first; it != range.second; ++it) {
476 return handle((PyObject *) it->second);
483 #if defined(PYPY_VERSION)
484 return PyThreadState_GET();
485 #elif PY_VERSION_HEX < 0x03000000
486 return _PyThreadState_Current;
487 #elif PY_VERSION_HEX < 0x03050000
488 return (PyThreadState*) _Py_atomic_load_relaxed(&_PyThreadState_Current);
489 #elif PY_VERSION_HEX < 0x03050200
490 return (PyThreadState*) _PyThreadState_Current.value;
492 return _PyThreadState_UncheckedGet();
509 return load_impl<type_caster_generic>(src, convert);
513 const detail::type_info *tinfo,
514 void *(*copy_constructor)(
const void *),
515 void *(*move_constructor)(
const void *),
516 const void *existing_holder =
nullptr) {
520 void *src =
const_cast<void *
>(_src);
525 return registered_inst;
528 auto wrapper =
reinterpret_cast<instance *
>(inst.ptr());
529 wrapper->
owned =
false;
533 case return_value_policy::automatic:
534 case return_value_policy::take_ownership:
536 wrapper->owned =
true;
539 case return_value_policy::automatic_reference:
542 wrapper->owned =
false;
545 case return_value_policy::copy:
546 if (copy_constructor)
547 valueptr = copy_constructor(src);
550 throw cast_error(
"return_value_policy = copy, but type is "
551 "non-copyable! (compile in debug mode for details)");
553 std::string type_name(tinfo->cpptype->name());
555 throw cast_error(
"return_value_policy = copy, but type " +
556 type_name +
" is non-copyable!");
559 wrapper->owned =
true;
563 if (move_constructor)
564 valueptr = move_constructor(src);
565 else if (copy_constructor)
566 valueptr = copy_constructor(src);
569 throw cast_error(
"return_value_policy = move, but type is neither "
570 "movable nor copyable! "
571 "(compile in debug mode for details)");
573 std::string type_name(tinfo->cpptype->name());
575 throw cast_error(
"return_value_policy = move, but type " +
576 type_name +
" is neither movable nor copyable!");
579 wrapper->owned =
true;
584 wrapper->owned =
false;
589 throw cast_error(
"unhandled return_value_policy: should not happen!");
592 tinfo->init_instance(wrapper, existing_holder);
594 return inst.release();
599 auto *&vptr = v_h.value_ptr();
601 if (vptr ==
nullptr) {
603 if (
type->operator_new) {
604 vptr =
type->operator_new(
type->type_size);
606 #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
607 if (
type->type_align > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
608 vptr = ::operator
new(
type->type_size,
609 std::align_val_t(
type->type_align));
612 vptr = ::operator
new(
type->type_size);
620 if (sub_caster.
load(src, convert)) {
638 if (caster.load(src,
false))
648 if (!
hasattr(pytype, local_key))
651 type_info *foreign_typeinfo = reinterpret_borrow<capsule>(
getattr(pytype, local_key));
667 template <
typename ThisT>
669 if (!src)
return false;
673 if (!convert)
return false;
678 auto &this_ =
static_cast<ThisT &
>(*this);
679 this_.check_holder_compat();
681 PyTypeObject *srctype = Py_TYPE(src.
ptr());
700 if (bases.size() == 1 && (no_cpp_mi || bases.front()->type ==
typeinfo->
type)) {
707 else if (bases.size() > 1) {
708 for (
auto base : bases) {
719 if (this_.try_implicit_casts(src, convert))
726 auto temp = reinterpret_steal<object>(converter(src.
ptr(),
typeinfo->
type));
727 if (load_impl<ThisT>(temp,
false)) {
732 if (this_.try_direct_conversions(src))
740 return load(src,
false);
753 const void *src,
const std::type_info &cast_type,
const std::type_info *rtti_type =
nullptr) {
755 return {src,
const_cast<const type_info *
>(tpi)};
758 std::string tname = rtti_type ? rtti_type->name() : cast_type.name();
760 std::string
msg =
"Unregistered type : " + tname;
761 PyErr_SetString(PyExc_TypeError,
msg.c_str());
762 return {
nullptr,
nullptr};
777 template <
typename T>
780 typename std::add_pointer<intrinsic_t<T>>
::type,
781 typename std::add_lvalue_reference<intrinsic_t<T>>
::type>;
790 template <
typename T>
793 typename std::add_pointer<intrinsic_t<T>>
::type,
795 typename std::add_rvalue_reference<intrinsic_t<T>>
::type,
796 typename std::add_lvalue_reference<intrinsic_t<T>>
::type>>;
807 std::is_same<typename Container::value_type &, typename Container::reference>,
809 negation<std::is_same<Container, typename Container::value_type>>
816 :
all_of<is_copy_constructible<T1>, is_copy_constructible<T2>> {};
819 template <
typename T,
typename SFINAE =
void>
struct is_copy_assignable : std::is_copy_assignable<T> {};
822 std::is_same<typename Container::value_type &, typename Container::reference>
825 :
all_of<is_copy_assignable<T1>, is_copy_assignable<T2>> {};
850 template <
typename itype,
typename SFINAE =
void>
853 static const void *
get(
const itype *src,
const std::type_info*&) {
return src; }
855 template <
typename itype>
858 static const void *
get(
const itype *src,
const std::type_info*&
type) {
859 type = src ? &
typeid(*src) :
nullptr;
860 return dynamic_cast<const void*
>(src);
863 template <
typename itype,
typename SFINAE =
void>
873 static constexpr
auto name = _<type>();
879 if (
policy == return_value_policy::automatic ||
policy == return_value_policy::automatic_reference)
880 policy = return_value_policy::copy;
891 static std::pair<const void *, const type_info *>
src_and_type(
const itype *src) {
892 auto &cast_type =
typeid(itype);
893 const std::type_info *instance_type =
nullptr;
895 if (instance_type && !
same_type(cast_type, *instance_type)) {
913 auto st = src_and_type(src);
915 st.first,
policy, parent, st.second,
916 make_copy_constructor(src), make_move_constructor(src));
920 auto st = src_and_type(src);
922 st.first, return_value_policy::take_ownership, {}, st.second,
923 nullptr,
nullptr, holder);
929 operator itype&() {
if (!
value)
throw reference_cast_error();
return *((itype *)
value); }
938 return [](
const void *
arg) ->
void * {
939 return new T(*
reinterpret_cast<const T *
>(
arg));
945 return [](
const void *
arg) ->
void * {
946 return new T(
std::move(*
const_cast<T *
>(
reinterpret_cast<const T *
>(
arg))));
967 template <
typename type>
class type_caster<std::reference_wrapper<type>> {
972 using subcaster_cast_op_type =
975 static_assert(std::is_same<
typename std::remove_const<type>::type &, subcaster_cast_op_type>::
value ||
977 "std::reference_wrapper<T> caster requires T to have a caster with an "
978 "`operator T &()` or `operator const T &()`");
981 static constexpr
auto name = caster_t::name;
984 if (
policy == return_value_policy::take_ownership ||
policy == return_value_policy::automatic)
985 policy = return_value_policy::automatic_reference;
988 template <
typename T>
using cast_op_type = std::reference_wrapper<type>;
989 operator std::reference_wrapper<type>() {
return cast_op<type &>(subcaster); }
992 #define PYBIND11_TYPE_CASTER(type, py_name) \
996 static constexpr auto name = py_name; \
997 template <typename T_, enable_if_t<std::is_same<type, remove_cv_t<T_>>::value, int> = 0> \
998 static handle cast(T_ *src, return_value_policy policy, handle parent) { \
999 if (!src) return none().release(); \
1000 if (policy == return_value_policy::take_ownership) { \
1001 auto h = cast(std::move(*src), policy, parent); delete src; return h; \
1003 return cast(*src, policy, parent); \
1006 operator type*() { return &value; } \
1007 operator type&() { return value; } \
1008 operator type&&() && { return std::move(value); } \
1009 template <typename T_> using cast_op_type = pybind11::detail::movable_cast_op_type<T_>
1013 std::is_same<CharT, char>,
1014 #if defined(PYBIND11_HAS_U8STRING)
1015 std::is_same<CharT, char8_t>,
1017 std::is_same<CharT, char16_t>,
1018 std::is_same<CharT, char32_t>,
1019 std::is_same<CharT, wchar_t>
1023 template <
typename T>
1036 #if !defined(PYPY_VERSION)
1037 auto index_check = [](PyObject *o) {
return PyIndex_Check(o); };
1041 auto index_check = [](PyObject *o) {
return hasattr(o,
"__index__"); };
1045 if (convert || PyFloat_Check(src.
ptr()))
1046 py_value = (
py_type) PyFloat_AsDouble(src.
ptr());
1049 }
else if (PyFloat_Check(src.
ptr())) {
1054 handle src_or_index = src;
1055 #if PY_VERSION_HEX < 0x03080000
1058 index = reinterpret_steal<object>(PyNumber_Index(src.
ptr()));
1065 src_or_index = index;
1070 py_value = as_unsigned<py_type>(src_or_index.
ptr());
1072 py_value =
sizeof(T) <=
sizeof(
long)
1073 ? (
py_type) PyLong_AsLong(src_or_index.
ptr())
1079 bool py_err = py_value == (
py_type) -1 && PyErr_Occurred();
1085 if (py_err && convert && PyNumber_Check(src.
ptr())) {
1087 ? PyNumber_Float(src.
ptr())
1088 : PyNumber_Long(src.
ptr()));
1090 return load(tmp,
false);
1095 value = (T) py_value;
1099 template<
typename U = T>
1102 return PyFloat_FromDouble((
double) src);
1105 template<
typename U = T>
1111 template<
typename U = T>
1117 template<
typename U = T>
1120 return PyLong_FromLongLong((
long long) src);
1123 template<
typename U = T>
1126 return PyLong_FromUnsignedLongLong((
unsigned long long) src);
1135 if (src && src.is_none())
1154 }
else if (h.is_none()) {
1160 if (isinstance<capsule>(h)) {
1161 value = reinterpret_borrow<capsule>(h);
1167 if (bases.size() == 1) {
1185 static constexpr
auto name =
_(
"capsule");
1187 void *
value =
nullptr;
1195 if (!src)
return false;
1196 else if (src.
ptr() == Py_True) {
value =
true;
return true; }
1197 else if (src.
ptr() == Py_False) {
value =
false;
return true; }
1198 else if (convert || !strcmp(
"numpy.bool_", Py_TYPE(src.
ptr())->tp_name)) {
1201 Py_ssize_t res = -1;
1202 if (src.is_none()) {
1205 #if defined(PYPY_VERSION)
1208 res = PyObject_IsTrue(src.
ptr());
1213 else if (
auto tp_as_number = src.
ptr()->ob_type->tp_as_number) {
1219 if (res == 0 || res == 1) {
1236 using CharT =
typename StringType::value_type;
1241 #if defined(PYBIND11_HAS_U8STRING)
1248 "Unsupported wchar_t size != 2/4");
1252 #if PY_MAJOR_VERSION < 3
1258 }
else if (!PyUnicode_Check(load_src.
ptr())) {
1259 #if PY_MAJOR_VERSION >= 3
1260 return load_bytes(load_src);
1263 return load_bytes(load_src);
1270 temp = reinterpret_steal<object>(PyUnicode_FromObject(load_src.
ptr()));
1271 if (!temp) { PyErr_Clear();
return false; }
1276 auto utfNbytes = reinterpret_steal<object>(PyUnicode_AsEncodedString(
1277 load_src.
ptr(),
UTF_N == 8 ?
"utf-8" :
UTF_N == 16 ?
"utf-16" :
"utf-32",
nullptr));
1278 if (!utfNbytes) { PyErr_Clear();
return false; }
1293 const char *
buffer =
reinterpret_cast<const char *
>(src.data());
1304 #if !defined(PYPY_VERSION)
1306 UTF_N == 8 ? PyUnicode_DecodeUTF8(
buffer, nbytes,
nullptr) :
1307 UTF_N == 16 ? PyUnicode_DecodeUTF16(
buffer, nbytes, nullptr, nullptr) :
1308 PyUnicode_DecodeUTF32(
buffer, nbytes, nullptr, nullptr);
1312 return PyUnicode_Decode(
buffer, nbytes,
UTF_N == 8 ?
"utf-8" :
UTF_N == 16 ?
"utf-16" :
"utf-32",
nullptr);
1319 template <
typename C = CharT>
1334 template <
typename C = CharT>
1338 template <
typename CharT,
class Traits,
class Allocator>
1340 :
string_caster<std::basic_string<CharT, Traits, Allocator>> {};
1342 #ifdef PYBIND11_HAS_STRING_VIEW
1343 template <
typename CharT,
class Traits>
1345 :
string_caster<std::basic_string_view<CharT, Traits>, true> {};
1358 if (!src)
return false;
1359 if (src.is_none()) {
1361 if (!convert)
return false;
1365 return str_caster.
load(src, convert);
1369 if (src ==
nullptr)
return pybind11::none().
inc_ref();
1375 handle s = PyUnicode_DecodeLatin1((
const char *) &src, 1,
nullptr);
1382 operator CharT*() {
return none ? nullptr :
const_cast<CharT *
>(
static_cast<StringType &
>(str_caster).
c_str()); }
1385 throw value_error(
"Cannot convert None to a character");
1388 size_t str_len =
value.size();
1390 throw value_error(
"Cannot convert empty string to a character");
1397 if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) {
1398 auto v0 =
static_cast<unsigned char>(
value[0]);
1399 size_t char0_bytes = !(v0 & 0x80) ? 1 :
1400 (v0 & 0xE0) == 0xC0 ? 2 :
1401 (v0 & 0xF0) == 0xE0 ? 3 :
1404 if (char0_bytes == str_len) {
1406 if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) {
1407 one_char =
static_cast<CharT
>(((v0 & 3) << 6) + (
static_cast<unsigned char>(
value[1]) & 0x3F));
1411 throw value_error(
"Character code point not in range(0x100)");
1418 else if (StringCaster::UTF_N == 16 && str_len == 2) {
1419 one_char =
static_cast<CharT
>(
value[0]);
1420 if (one_char >= 0xD800 && one_char < 0xE000)
1421 throw value_error(
"Character code point not in range(0x10000)");
1425 throw value_error(
"Expected a character, but multi-character string found");
1427 one_char =
value[0];
1432 template <
typename _T>
using cast_op_type = pybind11::detail::cast_op_type<_T>;
1436 template <
template<
typename...>
class Tuple,
typename... Ts>
class tuple_caster {
1437 using type = Tuple<Ts...>;
1438 static constexpr
auto size =
sizeof...(Ts);
1443 if (!isinstance<sequence>(src))
1445 const auto seq = reinterpret_borrow<sequence>(src);
1446 if (seq.size() != size)
1448 return load_impl(seq, convert, indices{});
1451 template <
typename T>
1457 template <
typename T>
1460 if (
policy == return_value_policy::take_ownership) {
1475 template <
size_t... Is>
1477 template <
size_t... Is>
1482 template <
size_t... Is>
1484 #ifdef __cpp_fold_expressions
1488 for (
bool r : {std::get<Is>(
subcasters).load(seq[Is], convert)...})
1496 template <
typename T,
size_t... Is>
1498 std::array<object, size> entries{{
1501 for (
const auto &entry: entries)
1506 for (
auto & entry: entries)
1507 PyTuple_SET_ITEM(result.
ptr(), counter++, entry.release().ptr());
1514 template <
typename T1,
typename T2>
class type_caster<std::pair<T1, T2>>
1522 template <
typename T>
1524 static auto get(
const T &p) -> decltype(p.get()) {
return p.get(); }
1532 template <
typename type,
typename holder_type,
typename SFINAE =
void>
1537 "Holder classes are only supported for custom types");
1544 return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
1551 explicit operator holder_type*() {
return std::addressof(
holder); }
1552 explicit operator holder_type&() {
return holder; }
1563 throw cast_error(
"Unable to load a custom holder type from a default-holder instance");
1567 if (v_h.holder_constructed()) {
1568 value = v_h.value_ptr();
1569 holder = v_h.template holder<holder_type>();
1572 throw cast_error(
"Unable to cast from non-held to held instance (T& to Holder<T>) "
1574 "(compile in debug mode for type information)");
1576 "of type '" + type_id<holder_type>() +
"''");
1588 if (sub_caster.
load(src, convert)) {
1604 template <
typename T>
1610 template <
typename type,
typename holder_type,
typename SFINAE =
void>
1613 "Holder classes are only supported for custom types");
1622 template <
typename type,
typename deleter>
1626 template <
typename type,
typename holder_type>
1634 #define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
1635 namespace pybind11 { namespace detail { \
1636 template <typename type> \
1637 struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__> { }; \
1638 template <typename type> \
1639 class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
1640 : public type_caster_holder<type, holder_type> { }; \
1645 std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
1659 template <
typename type>
1666 #if PY_MAJOR_VERSION < 3 && !defined(PYBIND11_STR_LEGACY_PERMISSIVE)
1671 PyObject *str_from_bytes = PyUnicode_FromEncodedObject(src.
ptr(),
"utf-8",
nullptr);
1673 value = reinterpret_steal<type>(str_from_bytes);
1677 if (!isinstance<type>(src))
1679 value = reinterpret_borrow<type>(src);
1689 template <
typename T>
1702 std::is_void, std::is_pointer, std::is_reference, std::is_const
1704 template <
typename T,
typename SFINAE =
void>
struct move_always : std::false_type {};
1708 std::is_move_constructible<T>,
1709 std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&>
1710 >
::value>> : std::true_type {};
1715 std::is_move_constructible<T>,
1716 std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&>
1717 >
::value>> : std::true_type {};
1738 detail::
enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
1750 throw cast_error(
"Unable to cast Python instance to C++ type (compile in debug mode for details)");
1752 throw cast_error(
"Unable to cast Python instance of type " +
1770 using namespace detail;
1772 "Unable to cast type to reference: value is local to type caster");
1773 return cast_op<T>(load_type<T>(
handle));
1784 using no_ref_T =
typename std::remove_reference<T>::type;
1785 if (
policy == return_value_policy::automatic)
1788 else if (
policy == return_value_policy::automatic_reference)
1794 template <
typename T> T
handle::cast()
const {
return pybind11::cast<T>(*
this); }
1797 template <
typename T>
1799 if (obj.ref_count() > 1)
1801 throw cast_error(
"Unable to cast Python instance to C++ rvalue: instance has multiple references"
1802 " (compile in debug mode for details)");
1804 throw cast_error(
"Unable to move from Python " + (std::string)
str(
type::handle_of(obj)) +
1805 " instance to C++ " + type_id<T>() +
" instance: instance has multiple references");
1809 T ret =
std::move(detail::load_type<T>(obj).
operator T&());
1822 if (
object.ref_count() > 1)
1823 return cast<T>(
object);
1828 return cast<T>(
object);
1831 template <
typename T> T
object::cast() const & {
return pybind11::cast<T>(*
this); }
1849 return cast_op<T>(
load_type(caster, o));
1852 pybind11_fail(
"Internal error: cast_ref fallback invoked"); }
1858 return pybind11::cast<T>(
std::move(o)); }
1860 pybind11_fail(
"Internal error: cast_safe fallback invoked"); }
1865 template <return_value_policy policy = return_value_policy::automatic_reference>
1870 constexpr
size_t size =
sizeof...(Args);
1871 std::array<object, size>
args {
1873 std::forward<Args>(args_),
policy,
nullptr))... }
1878 throw cast_error(
"make_tuple(): unable to convert arguments to Python object (compile in debug mode for details)");
1880 std::array<std::string, size> argtypes { {type_id<Args>()...} };
1881 throw cast_error(
"make_tuple(): unable to convert argument of type '" +
1882 argtypes[
i] +
"' to Python object");
1888 for (
auto &arg_value :
args)
1889 PyTuple_SET_ITEM(result.
ptr(), counter++, arg_value.release().ptr());
1914 template <
typename T>
1917 value(reinterpret_steal<object>(
1921 #if !defined(NDEBUG)
1922 ,
type(type_id<T>())
1928 if (PyErr_Occurred()) {
1935 template <
typename T>
1940 template <
typename T>
1954 #if !defined(NDEBUG)
1970 template <
typename T>
2014 template <
typename... Args>
2018 template <
typename Arg>
using argument_is_args = std::is_same<intrinsic_t<Arg>,
args>;
2019 template <
typename Arg>
using argument_is_kwargs = std::is_same<intrinsic_t<Arg>,
kwargs>;
2021 static constexpr
auto args_pos =
constexpr_first<argument_is_args, Args...>() - (
int)
sizeof...(Args),
2022 kwargs_pos = constexpr_first<argument_is_kwargs, Args...>() - (int)
sizeof...(Args);
2024 static constexpr
bool args_kwargs_are_last = kwargs_pos >= - 1 && args_pos >= kwargs_pos - 1;
2026 static_assert(args_kwargs_are_last,
"py::args/py::kwargs are only permitted as the last argument(s) of a function");
2035 return load_impl_sequence(
call, indices{});
2038 template <
typename Return,
typename Guard,
typename Func>
2040 return std::move(*this).template call_impl<Return>(std::forward<Func>(f), indices{}, Guard{});
2043 template <
typename Return,
typename Guard,
typename Func>
2045 std::move(*this).template call_impl<Return>(std::forward<Func>(f), indices{}, Guard{});
2053 template <
size_t... Is>
2055 #ifdef __cpp_fold_expressions
2056 if ((... || !std::get<Is>(argcasters).load(
call.args[Is],
call.args_convert[Is])))
2059 for (
bool r : {std::get<Is>(argcasters).load(
call.args[Is],
call.args_convert[Is])...})
2066 template <
typename Return,
typename Func,
size_t... Is,
typename Guard>
2068 return std::forward<Func>(f)(cast_op<Args>(
std::move(std::get<Is>(argcasters)))...);
2071 std::tuple<make_caster<Args>...> argcasters;
2076 template <return_value_policy policy>
2079 template <
typename... Ts>
2090 PyObject *result = PyObject_CallObject(ptr, m_args.
ptr());
2093 return reinterpret_steal<object>(result);
2101 template <return_value_policy policy>
2104 template <
typename... Ts>
2108 auto args_list =
list();
2109 int _[] = { 0, (process(args_list, std::forward<Ts>(values)), 0)... };
2123 PyObject *result = PyObject_Call(ptr, m_args.
ptr(), m_kwargs.
ptr());
2126 return reinterpret_steal<object>(result);
2130 template <
typename T>
2131 void process(
list &args_list, T &&
x) {
2135 argument_cast_error();
2137 argument_cast_error(std::to_string(args_list.
size()), type_id<T>());
2143 void process(
list &args_list, detail::args_proxy ap) {
2151 nameless_argument_error();
2153 nameless_argument_error(a.
type);
2158 multiple_values_error();
2160 multiple_values_error(a.
name);
2165 argument_cast_error();
2167 argument_cast_error(a.
name, a.
type);
2173 void process(
list &, detail::kwargs_proxy kp) {
2176 for (
auto k : reinterpret_borrow<dict>(kp)) {
2179 multiple_values_error();
2181 multiple_values_error(
str(k.first));
2184 m_kwargs[k.first] = k.second;
2188 [[noreturn]]
static void nameless_argument_error() {
2189 throw type_error(
"Got kwargs without a name; only named arguments "
2190 "may be passed via py::arg() to a python function call. "
2191 "(compile in debug mode for details)");
2193 [[noreturn]]
static void nameless_argument_error(std::string
type) {
2194 throw type_error(
"Got kwargs without a name of type '" +
type +
"'; only named "
2195 "arguments may be passed via py::arg() to a python function call. ");
2197 [[noreturn]]
static void multiple_values_error() {
2198 throw type_error(
"Got multiple values for keyword argument "
2199 "(compile in debug mode for details)");
2202 [[noreturn]]
static void multiple_values_error(std::string
name) {
2203 throw type_error(
"Got multiple values for keyword argument '" +
name +
"'");
2206 [[noreturn]]
static void argument_cast_error() {
2207 throw cast_error(
"Unable to convert call argument to Python object "
2208 "(compile in debug mode for details)");
2211 [[noreturn]]
static void argument_cast_error(std::string
name, std::string
type) {
2212 throw cast_error(
"Unable to convert call argument '" +
name
2213 +
"' of type '" +
type +
"' to Python object");
2225 template <
typename... Args>
2244 constexpr_last<is_positional, Args...>() < constexpr_first<is_keyword_or_ds, Args...>()
2245 && constexpr_last<is_s_unpacking, Args...>() < constexpr_first<is_ds_unpacking, Args...>(),
2246 "Invalid function call: positional args must precede keywords and ** unpacking; "
2247 "* unpacking must precede ** unpacking"
2252 template <
typename Derived>
2255 return detail::collect_arguments<policy>(std::forward<Args>(
args)...).call(derived().ptr());
2258 template <
typename Derived>
2261 return operator()<
policy>(std::forward<Args>(
args)...);
2267 template<
typename T>
2270 std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::
value,
2271 "py::type::of<T> only supports the case where T is a registered C++ types."
2278 #define PYBIND11_MAKE_OPAQUE(...) \
2279 namespace pybind11 { namespace detail { \
2280 template<> class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> { }; \
2285 #define PYBIND11_TYPE(...) __VA_ARGS__
static auto make_copy_constructor(const T *x) -> decltype(new T(*x), Constructor
static handle cast(T *src, return_value_policy policy, handle parent)
typename std::enable_if< B, T >::type enable_if_t
from cpp_future import (convenient aliases from C++14/17)
type_caster< T, SFINAE > & load_type(type_caster< T, SFINAE > &conv, const handle &handle)
RAII wrapper that temporarily clears any Python error state.
bool try_direct_conversions(handle src)
#define PYBIND11_MODULE_LOCAL_ID
static const void * get(const itype *src, const std::type_info *&)
#define PYBIND11_BYTES_SIZE
Annotation for function names.
Internal data structure which holds metadata about a bound function (signature, overloads,...
conditional_t< std::is_signed< T >::value, _py_type_0, typename std::make_unsigned< _py_type_0 >::type > _py_type_1
static handle cast(itype &&src, return_value_policy, handle parent)
T cast(const handle &handle)
#define PYBIND11_NAMESPACE_BEGIN(name)
static constexpr size_t UTF_N
void *(* module_local_load)(PyObject *, const type_info *)
value_and_holder(size_t index)
Annotation indicating that a class derives from another given type.
void *(*)(const void *) Constructor
static handle cast(const void *ptr, return_value_policy, handle)
#define PYBIND11_NAMESPACE_END(name)
void ignore_unused(const int *)
Ignore that a variable is unused in compiler warnings.
PyThreadState * get_thread_state_unchecked()
bool load_args(function_call &call)
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(bool src, return_value_policy, handle)
Annotation for parent scope.
#define PYBIND11_NAMESPACE
static handle cast(const CharT *src, return_value_policy policy, handle parent)
nonsimple_values_and_holders nonsimple
bool load(handle src, bool)
loader_life_support()
A new patient frame is created when a function is entered.
type_map< type_info * > registered_types_cpp
std::vector< PyObject * > loader_patient_stack
value_and_holder get_value_and_holder(const type_info *find_type=nullptr, bool throw_if_missing=true)
void cast_safe< void >(object &&)
static handle cast(const holder_type &src, return_value_policy, handle)
static constexpr uint8_t status_instance_registered
PYBIND11_NOINLINE void clean_type_id(std::string &name)
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)
#define PYBIND11_BYTES_AS_STRING
conditional_t< std::is_floating_point< T >::value, double, _py_type_1 > py_type
#define PYBIND11_BYTES_CHECK
enable_if_t<!std::is_void< Return >::value, Return > call(Func &&f) &&
const handle & inc_ref() const &
const function_record & func
The function data:
#define PYBIND11_NOINLINE
std::integral_constant< bool, B > bool_constant
Backports of std::bool_constant and std::negation to accommodate older compilers.
bool hasattr(handle obj, handle name)
PYBIND11_NOINLINE type_caster_generic(const std::type_info &type_info)
std::unordered_multimap< const void *, instance * > registered_instances
std::vector< PyObject *(*)(PyObject *, PyTypeObject *)> implicit_conversions
static handle cast(holder_type &&src, return_value_policy, handle)
#define PYBIND11_LONG_FROM_SIGNED(o)
std::is_same< bools< Ts::value..., true >, bools< true, Ts::value... > > all_of
void keep_alive_impl(handle nurse, handle patient)
constexpr descr< N - 1 > _(char const(&text)[N])
object getattr(handle obj, handle name)
conditional_t< sizeof(T)<=sizeof(long), long, long long > _py_type_0
object operator()(Args &&...args) const
static constexpr auto arg_names
static Constructor make_move_constructor(...)
enable_if_t< cast_is_temporary_value_reference< T >::value, T > cast_ref(object &&o, make_caster< T > &caster)
function_call(const function_record &f, handle p)
detail::cast_op_type< T > cast_op_type
static Constructor make_copy_constructor(...)
void ** values_and_holders
PYBIND11_NOINLINE internals & get_internals()
Return a reference to the current internals data.
simple_collector< policy > collect_arguments(Args &&...args)
Collect only positional arguments for a Python function call.
void * simple_value_holder[1+instance_simple_holder_in_ptrs()]
static std::pair< const void *, const type_info * > src_and_type(const itype *src)
#define PYBIND11_LONG_FROM_UNSIGNED(o)
static auto make_move_constructor(const T *x) -> decltype(new T(std::move(*const_cast< T * >(x))), Constructor
arg_v operator=(T &&value) const
Assign a value to this argument.
bool try_implicit_casts(handle src, bool convert)
bool operator!=(const iterator &other) const
const std::type_info * cpptype
static handle cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence< Is... >)
std::reference_wrapper< type > cast_op_type
static handle cast(const StringType &src, return_value_policy, handle)
enable_if_t< std::is_void< Return >::value, void_type > call(Func &&f) &&
typename std::conditional< B, T, F >::type conditional_t
static bool try_direct_conversions(handle)
type implicit_cast(index_sequence< Is... >) &&
handle parent
The parent, if any.
void allocate_layout()
Initializes all of the above type/values/holders data (but not the instance values themselves)
PYBIND11_NOINLINE handle find_registered_python_instance(void *src, const detail::type_info *tinfo)
PYBIND11_NOINLINE std::string error_string()
bool load(handle src, bool convert)
The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
Internal data associated with a single function call.
void load_value(value_and_holder &&v_h)
bool load(handle src, bool convert)
simple_collector(Ts &&...values)
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)
iterator find(const type_info *find_type)
std::string type
The C++ type name of the default value (only available when compiled in debug mode)
static constexpr bool value
static handle cast(const itype &src, return_value_policy policy, handle parent)
void set_instance_registered(bool v=true)
void set_holder_constructed(bool v=true)
bool same_type(const std::type_info &lhs, const std::type_info &rhs)
void check_holder_compat()
type_map< type_info * > & registered_local_types_cpp()
Works like internals.registered_types_cpp, but for module-local registered types:
object call(PyObject *ptr) const
Call a Python function and pass the collected arguments.
const char * name
If non-null, this is a named kwargs argument.
const tuple & args() const &
PYBIND11_TYPE_CASTER(type, handle_type_name< type >::name)
arg_v(const char *name, T &&x, const char *descr=nullptr)
Direct construction with name, default, and description.
std::string get_fully_qualified_tp_name(PyTypeObject *type)
bool isinstance(handle obj)
bool load(handle src, bool convert)
type_caster_base(const std::type_info &info)
object value
The default value.
static handle handle_of()
handle init_self
If this is a call to an initializer, this argument contains self
PyObject * make_new_instance(PyTypeObject *type)
std::basic_string< CharT > StringType
static return_value_policy policy(return_value_policy p)
PYBIND11_NOINLINE handle get_object_handle(const void *ptr, const detail::type_info *type)
static return_value_policy policy(return_value_policy p)
value_and_holder & operator*()
static handle cast(T, return_value_policy, handle)
bool flag_noconvert
If set, do not allow conversion (requires a supporting type caster!)
value_and_holder(instance *i, const detail::type_info *type, size_t vpos, size_t index)
PYBIND11_NOINLINE bool load_impl(handle src, bool convert)
PYBIND11_NOINLINE handle get_type_handle(const std::type_info &tp, bool throw_if_missing)
bool simple_instance_registered
For simple layout, tracks whether the instance is registered in registered_instances
bool load(handle src, bool convert)
void deallocate_layout()
Destroys/deallocates all of the above.
#define PYBIND11_NB_BOOL(ptr)
PYBIND11_TYPE_CASTER(T, _< std::is_integral< T >::value >("int", "float"))
typename intrinsic_type< T >::type intrinsic_t
Tuple< make_caster< Ts >... > subcasters
bool load(handle src, bool)
bool flag_none
If set (the default), allow None to be passed to this argument.
unpacking_collector(Ts &&...values)
const dict & kwargs() const &
constexpr int constexpr_first()
PYBIND11_TYPE_CASTER(StringType, _(PYBIND11_STRING_NAME))
static std::enable_if< std::is_floating_point< U >::value, handle >::type cast(U src, return_value_policy, handle)
bool owned
If true, the pointer is owned which means we're free to manage it with a holder.
constexpr descr< 0 > concat()
static constexpr uint8_t status_holder_constructed
Bit values for the non-simple status flags.
bool load(handle h, bool)
bool load(handle src, bool convert)
static handle cast(const itype &src, return_value_policy policy, handle parent)
std::vector< bool(*)(PyObject *, void *&)> * direct_conversions
arg_v & noconvert(bool flag=true)
Same as arg::noconvert(), but returns *this as arg_v&, not arg&.
constexpr descr< N+2, Ts... > type_descr(const descr< N, Ts... > &descr)
enable_if_t<!cast_is_temporary_value_reference< T >::value, T > cast_safe(object &&o)
conditional_t< cast_is_temporary_value_reference< ret_type >::value, make_caster< ret_type >, override_unused > override_caster_t
PyExc_RuntimeError PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
#define PYBIND11_LONG_AS_LONGLONG(o)
bool load_value(value_and_holder &&v_h)
#define PYBIND11_BOOL_ATTR
static handle cast(const std::reference_wrapper< type > &src, return_value_policy policy, handle parent)
std::vector< std::pair< const std::type_info *, void *(*)(void *)> > implicit_casts
arg & none(bool flag=true)
Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args)
Helper class which collects positional, keyword, * and ** arguments for a Python function call.
const char * descr
The (optional) description of the default value.
detail::enable_if_t<!detail::move_never< T >::value, T > move(object &&obj)
constexpr size_t instance_simple_holder_in_ptrs()
void append(T &&val) const
bool contains(T &&key) const
static PYBIND11_NOINLINE void * local_load(PyObject *src, const type_info *ti)
PyObject * ptr() const
Return the underlying PyObject * pointer.
~loader_life_support()
... and destroyed after it returns
static PYBIND11_NOINLINE std::pair< const void *, const type_info * > src_and_type(const void *src, const std::type_info &cast_type, const std::type_info *rtti_type=nullptr)
value_and_holder()=default
bool simple_holder_constructed
For simple layout, tracks whether the holder has been constructed.
void check_holder_compat()
static constexpr bool load_impl(const sequence &, bool, index_sequence<>)
conditional_t< is_copy_constructible< holder_type >::value, copyable_holder_caster< type, holder_type >, move_only_holder_caster< type, holder_type > > type_caster_holder
typename make_index_sequence_impl< N >::type make_index_sequence
Helper class which loads arguments for C++ functions called from Python.
bool try_implicit_casts(handle, bool)
bool instance_registered() const
Helper type to replace 'void' in some expressions.
PYBIND11_NOINLINE void all_type_info_populate(PyTypeObject *t, std::vector< type_info * > &bases)
bool holder_constructed() const
object call(PyObject *ptr) const
Call a Python function and pass the collected arguments.
return_value_policy
Approach used to cast a previously unknown C++ instance into a Python object.
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)
const char * c_str(Args &&...args)
static auto get(const T &p) -> decltype(p.get())
std::is_base_of< pyobject_tag, remove_reference_t< T > > is_pyobject
bool load_impl(const sequence &seq, bool convert, index_sequence< Is... >)
PYBIND11_NOINLINE bool try_load_foreign_module_local(handle src)
make_caster< T >::template cast_op_type< T > cast_op(make_caster< T > &caster)
#define PYBIND11_BYTES_NAME
std::unordered_map< PyTypeObject *, std::vector< type_info * > > registered_types_py
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)
const std::type_info * cpptype
const type_info * typeinfo
bool load(handle src, bool convert)
std::vector< handle > args
Arguments passed to the function:
static handle cast(const itype *src, return_value_policy policy, handle parent)
object object_or_cast(T &&o)
static handle cast_holder(const itype *src, const void *holder)
static handle cast(const handle &src, return_value_policy, handle)
pybind11::detail::cast_op_type< _T > cast_op_type
std::pair< decltype(internals::registered_types_py)::iterator, bool > all_type_info_get_cache(PyTypeObject *type)
static PYBIND11_NOINLINE handle cast(const void *_src, return_value_policy policy, handle parent, const detail::type_info *tinfo, void *(*copy_constructor)(const void *), void *(*move_constructor)(const void *), const void *existing_holder=nullptr)
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 constexpr bool has_args
PYBIND11_TYPE_CASTER(T, _("None"))
values_and_holders(instance *inst)
#define PYBIND11_LONG_CHECK(o)
arg & noconvert(bool flag=true)
Indicate that the type should not be converted in the type caster.
const std::vector< detail::type_info * > & all_type_info(PyTypeObject *type)
bool try_implicit_casts(handle src, bool convert)
const tuple & args() const &
static handle cast(CharT src, return_value_policy policy, handle parent)
type implicit_cast(index_sequence< Is... >) &
PYBIND11_NOINLINE bool isinstance_generic(handle obj, const std::type_info &tp)
value_and_holder * operator->()
static constexpr bool has_kwargs
bool operator==(const iterator &other) const
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)
detail::type_info * get_global_type_info(const std::type_index &tp)
PYBIND11_TYPE_CASTER(bool, _("bool"))
const detail::type_info * type
arg_v(const arg &base, T &&x, const char *descr=nullptr)
Called internally when invoking py::arg("a") = value
static PYBIND11_NOINLINE void add_patient(handle h)
std::vector< bool > args_convert
The convert value the arguments should be loaded with.
typename StringType::value_type CharT
#define PYBIND11_STRING_NAME
constexpr bool args_are_all_positional()
static const void * get(const itype *src, const std::type_info *&type)
static handle cast(T &&src, return_value_policy policy, handle parent)
arg_v & none(bool flag=true)
Same as arg::nonone(), but returns *this as arg_v&, not arg&.
PYBIND11_NOINLINE detail::type_info * get_type_info(PyTypeObject *type)
bool load(handle src, bool)
detail::type_info * get_local_type_info(const std::type_index &tp)
Generic type caster for objects stored on the heap.
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
type_caster_generic(const type_info *typeinfo)