13 #if defined(__INTEL_COMPILER)
15 # pragma warning disable 68 // integer conversion resulted in a change of sign
16 # pragma warning disable 186 // pointless comparison of unsigned integer with zero
17 # pragma warning disable 878 // incompatible exception specifications
18 # pragma warning disable 1334 // the "template" keyword used for syntactic disambiguation may only be used within a template
19 # pragma warning disable 1682 // implicit conversion of a 64-bit integral type to a smaller integral type (potential portability problem)
20 # pragma warning disable 1786 // function "strdup" was declared deprecated
21 # pragma warning disable 1875 // offsetof applied to non-POD (Plain Old Data) types is nonstandard
22 # pragma warning disable 2196 // warning #2196: routine is both "inline" and "noinline"
23 #elif defined(_MSC_VER)
24 # pragma warning(push)
25 # pragma warning(disable: 4100) // warning C4100: Unreferenced formal parameter
26 # pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
27 # pragma warning(disable: 4512) // warning C4512: Assignment operator was implicitly defined as deleted
28 # pragma warning(disable: 4800) // warning C4800: 'int': forcing value to bool 'true' or 'false' (performance warning)
29 # pragma warning(disable: 4996) // warning C4996: The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name
30 # pragma warning(disable: 4702) // warning C4702: unreachable code
31 # pragma warning(disable: 4522) // warning C4522: multiple assignment operators specified
32 # pragma warning(disable: 4505) // warning C4505: 'PySlice_GetIndicesEx': unreferenced local function has been removed (PyPy only)
33 #elif defined(__GNUG__) && !defined(__clang__)
34 # pragma GCC diagnostic push
35 # pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
36 # pragma GCC diagnostic ignored "-Wunused-but-set-variable"
37 # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
38 # pragma GCC diagnostic ignored "-Wstrict-aliasing"
39 # pragma GCC diagnostic ignored "-Wattributes"
41 # pragma GCC diagnostic ignored "-Wnoexcept-type"
55 #if defined(__GNUG__) && !defined(__clang__)
68 template <
typename Return,
typename... Args,
typename... Extra>
70 initialize(f, f, extra...);
74 template <
typename Func,
typename... Extra,
77 initialize(std::forward<Func>(f),
78 (detail::function_signature_t<Func> *)
nullptr, extra...);
82 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
84 initialize([f](Class *c, Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
85 (Return (*) (Class *, Arg...))
nullptr, extra...);
91 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
93 initialize([f](Class *c, Arg...
args) -> Return { return (c->*f)(args...); },
94 (Return (*) (Class *, Arg...))
nullptr, extra...);
98 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
99 cpp_function(Return (Class::*f)(Arg...)
const,
const Extra&... extra) {
100 initialize([f](
const Class *c, Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
101 (Return (*)(
const Class *, Arg ...))
nullptr, extra...);
107 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
108 cpp_function(Return (Class::*f)(Arg...)
const&,
const Extra&... extra) {
109 initialize([f](
const Class *c, Arg...
args) -> Return { return (c->*f)(args...); },
110 (Return (*)(
const Class *, Arg ...))
nullptr, extra...);
114 object name()
const {
return attr(
"__name__"); }
120 void operator()(detail::function_record * rec) { destruct(rec,
false); }
130 template <
typename Func,
typename Return,
typename... Args,
typename... Extra>
131 void initialize(Func &&f, Return (*)(Args...),
const Extra&... extra) {
132 using namespace detail;
137 auto unique_rec = make_function_record();
138 auto rec = unique_rec.get();
141 if (
sizeof(
capture) <=
sizeof(rec->data)) {
145 #if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
146 # pragma GCC diagnostic push
147 # pragma GCC diagnostic ignored "-Wplacement-new"
150 #if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
151 # pragma GCC diagnostic pop
156 rec->data[0] =
new capture { std::forward<Func>(f) };
166 static_assert(expected_num_args<Extra...>(
sizeof...(Args), cast_in::has_args, cast_in::has_kwargs),
167 "The number of argument annotations does not match the number of function arguments");
171 cast_in args_converter;
174 if (!args_converter.load_args(call))
181 auto data = (
sizeof(
capture) <=
sizeof(call.func.data)
182 ? &call.func.data : call.func.data[0]);
193 std::move(args_converter).
template call<Return, Guard>(cap->f),
policy, call.parent);
209 static_assert(has_arg_annotations || !has_kw_only_args,
"py::kw_only requires the use of argument annotations");
210 static_assert(has_arg_annotations || !has_pos_only_args,
"py::pos_only requires the use of argument annotations (for docstrings and aligning the annotations to the argument)");
211 static_assert(!(has_args && has_kw_only_args),
"py::kw_only cannot be combined with a py::args argument");
215 static constexpr
auto signature =
_(
"(") + cast_in::arg_names +
_(
") -> ") + cast_out::name;
220 initialize_generic(
std::move(unique_rec), signature.text, types.data(),
sizeof...(Args));
222 if (cast_in::has_args) rec->has_args =
true;
223 if (cast_in::has_kwargs) rec->has_kwargs =
true;
226 using FunctionType = Return (*)(Args...);
227 constexpr
bool is_function_ptr =
229 sizeof(
capture) ==
sizeof(
void *);
230 if (is_function_ptr) {
231 rec->is_stateless =
true;
232 rec->data[1] =
const_cast<void *
>(
reinterpret_cast<const void *
>(&
typeid(FunctionType)));
241 for (
auto s : strings)
246 strings.push_back(t);
253 std::vector<char *> strings;
258 const std::type_info *
const *types,
size_t args) {
262 auto rec = unique_rec.get();
272 rec->name = guarded_strdup(rec->name ? rec->name :
"");
273 if (rec->doc) rec->doc = guarded_strdup(rec->doc);
274 for (
auto &a: rec->args) {
276 a.name = guarded_strdup(a.name);
278 a.descr = guarded_strdup(a.descr);
280 a.descr = guarded_strdup(
repr(a.value).
cast<std::string>().c_str());
283 rec->is_constructor = !strcmp(rec->name,
"__init__") || !strcmp(rec->name,
"__setstate__");
285 #if !defined(NDEBUG) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING)
286 if (rec->is_constructor && !rec->is_new_style_constructor) {
288 const auto func_name = std::string(rec->name);
291 (
"pybind11-bound class '" + class_name +
"' is using an old-style "
292 "placement-new '" + func_name +
"' which has been deprecated. See "
293 "the upgrade guide in pybind11's docs. This message is only visible "
294 "when compiled in debug mode.").
c_str(), 0
300 std::string signature;
301 size_t type_index = 0, arg_index = 0;
302 for (
auto *pc = text; *pc !=
'\0'; ++pc) {
307 if (*(pc + 1) ==
'*')
311 if (rec->nargs_kw_only > 0 && arg_index + rec->nargs_kw_only ==
args)
313 if (arg_index < rec->
args.
size() && rec->args[arg_index].name) {
314 signature += rec->args[arg_index].name;
315 }
else if (arg_index == 0 && rec->is_method) {
318 signature +=
"arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
321 }
else if (c ==
'}') {
323 if (arg_index < rec->
args.
size() && rec->args[arg_index].descr) {
325 signature += rec->args[arg_index].descr;
329 if (rec->nargs_pos_only > 0 && (arg_index + 1) == rec->nargs_pos_only)
332 }
else if (c ==
'%') {
333 const std::type_info *t = types[type_index++];
335 pybind11_fail(
"Internal error while parsing type signature (1)");
337 handle th((PyObject *) tinfo->type);
339 th.attr(
"__module__").
cast<std::string>() +
"." +
340 th.attr(
"__qualname__").
cast<std::string>();
341 }
else if (rec->is_new_style_constructor && arg_index == 0) {
345 rec->scope.attr(
"__module__").cast<std::string>() +
"." +
346 rec->scope.attr(
"__qualname__").cast<std::string>();
348 std::string tname(t->name());
357 if (arg_index !=
args || types[type_index] !=
nullptr)
358 pybind11_fail(
"Internal error while parsing type signature (2)");
360 #if PY_MAJOR_VERSION < 3
361 if (strcmp(rec->name,
"__next__") == 0) {
362 std::free(rec->name);
363 rec->name = guarded_strdup(
"next");
364 }
else if (strcmp(rec->name,
"__bool__") == 0) {
365 std::free(rec->name);
366 rec->name = guarded_strdup(
"__nonzero__");
369 rec->signature = guarded_strdup(signature.c_str());
370 rec->args.shrink_to_fit();
371 rec->nargs = (std::uint16_t)
args;
376 detail::function_record *chain =
nullptr, *chain_start = rec;
378 if (PyCFunction_Check(rec->sibling.ptr())) {
379 auto rec_capsule = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(rec->sibling.ptr()));
380 chain = (detail::function_record *) rec_capsule;
383 if (!chain->scope.is(rec->scope))
387 else if (!rec->sibling.is_none() && rec->name[0] !=
'_')
388 pybind11_fail(
"Cannot overload existing non-function object \"" + std::string(rec->name) +
389 "\" with a function of the same name");
394 rec->def =
new PyMethodDef();
395 std::memset(rec->def, 0,
sizeof(PyMethodDef));
396 rec->def->ml_name = rec->name;
397 rec->def->ml_meth =
reinterpret_cast<PyCFunction
>(
reinterpret_cast<void (*) (
void)
>(*dispatcher));
398 rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
400 capsule rec_capsule(unique_rec.release(), [](
void *ptr) {
401 destruct((detail::function_record *) ptr);
407 if (
hasattr(rec->scope,
"__module__")) {
408 scope_module = rec->scope.attr(
"__module__");
409 }
else if (
hasattr(rec->scope,
"__name__")) {
410 scope_module = rec->scope.attr(
"__name__");
414 m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.
ptr(), scope_module.
ptr());
416 pybind11_fail(
"cpp_function::cpp_function(): Could not allocate function object");
419 m_ptr = rec->sibling.ptr();
421 if (chain->is_method != rec->is_method)
422 pybind11_fail(
"overloading a method with both static and instance methods is not supported; "
424 "compile in debug mode for more details"
426 "error while attempting to bind " + std::string(rec->is_method ?
"instance" :
"static") +
" method " +
427 std::string(pybind11::str(rec->scope.attr(
"__name__"))) +
"." + std::string(rec->name) + signature
437 auto rec_capsule = reinterpret_borrow<capsule>(((PyCFunctionObject *) m_ptr)->m_self);
438 rec_capsule.set_pointer(unique_rec.release());
445 chain->next = unique_rec.release();
450 std::string signatures;
456 signatures += rec->name;
457 signatures +=
"(*args, **kwargs)\n";
458 signatures +=
"Overloaded function.\n\n";
461 bool first_user_def =
true;
462 for (
auto it = chain_start; it !=
nullptr; it = it->next) {
464 if (index > 0) signatures +=
"\n";
466 signatures += std::to_string(++index) +
". ";
467 signatures += rec->name;
468 signatures += it->signature;
475 if (first_user_def) first_user_def =
false;
476 else signatures +=
"\n";
479 signatures += it->doc;
485 auto *func = (PyCFunctionObject *) m_ptr;
486 std::free(
const_cast<char *
>(func->m_ml->ml_doc));
488 func->m_ml->ml_doc = signatures.empty() ? nullptr : strdup(signatures.c_str());
490 if (rec->is_method) {
493 pybind11_fail(
"cpp_function::cpp_function(): Could not allocate instance method object");
499 static void destruct(detail::function_record *rec,
bool free_strings =
true) {
502 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
503 static bool is_zero = Py_GetVersion()[4] ==
'0';
507 detail::function_record *next = rec->next;
514 std::free((
char *) rec->name);
515 std::free((
char *) rec->doc);
516 std::free((
char *) rec->signature);
517 for (
auto &
arg: rec->args) {
518 std::free(
const_cast<char *
>(
arg.
name));
519 std::free(
const_cast<char *
>(
arg.descr));
522 for (
auto &
arg: rec->args)
525 std::free(
const_cast<char *
>(rec->def->ml_doc));
529 #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9
542 static PyObject *
dispatcher(PyObject *
self, PyObject *args_in, PyObject *kwargs_in) {
543 using namespace detail;
550 const auto n_args_in = (
size_t) PyTuple_GET_SIZE(args_in);
552 handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) :
nullptr,
557 if (!PyObject_TypeCheck(parent.
ptr(), (PyTypeObject *) overloads->
scope.
ptr())) {
558 PyErr_SetString(PyExc_TypeError,
"__init__(self, ...) called with invalid `self` argument");
563 const auto pi =
reinterpret_cast<instance *
>(parent.
ptr());
568 if (self_value_and_holder.instance_registered())
577 std::vector<function_call> second_pass;
580 const bool overloaded = it !=
nullptr && it->next !=
nullptr;
582 for (; it !=
nullptr; it = it->next) {
604 size_t num_args = func.
nargs;
609 if (!func.
has_args && n_args_in > pos_args)
612 if (n_args_in < pos_args && func.
args.size() < pos_args)
617 size_t args_to_copy = (std::min)(pos_args, n_args_in);
618 size_t args_copied = 0;
624 if (self_value_and_holder)
625 self_value_and_holder.type->dealloc(self_value_and_holder);
627 call.
init_self = PyTuple_GET_ITEM(args_in, 0);
628 call.
args.emplace_back(
reinterpret_cast<PyObject *
>(&self_value_and_holder));
634 bool bad_arg =
false;
635 for (; args_copied < args_to_copy; ++args_copied) {
637 if (kwargs_in && arg_rec && arg_rec->
name && PyDict_GetItemString(kwargs_in, arg_rec->
name)) {
642 handle arg(PyTuple_GET_ITEM(args_in, args_copied));
643 if (arg_rec && !arg_rec->
none &&
arg.is_none()) {
654 dict kwargs = reinterpret_borrow<dict>(kwargs_in);
659 const auto &arg_rec = func.
args[args_copied];
663 value = arg_rec.value;
677 if (args_copied < num_args) {
678 bool copied_kwargs =
false;
680 for (; args_copied < num_args; ++args_copied) {
681 const auto &arg_rec = func.
args[args_copied];
684 if (kwargs_in && arg_rec.name)
689 if (!copied_kwargs) {
691 copied_kwargs =
true;
693 PyDict_DelItemString(
kwargs.
ptr(), arg_rec.name);
694 }
else if (arg_rec.value) {
695 value = arg_rec.value;
698 if (!arg_rec.none &&
value.is_none()) {
710 if (args_copied < num_args)
721 if (args_to_copy == 0) {
724 extra_args = reinterpret_borrow<tuple>(args_in);
725 }
else if (args_copied >= n_args_in) {
726 extra_args =
tuple(0);
728 size_t args_size = n_args_in - args_copied;
729 extra_args =
tuple(args_size);
730 for (
size_t i = 0;
i < args_size; ++
i) {
731 extra_args[
i] = PyTuple_GET_ITEM(args_in, args_copied +
i);
734 call.
args.push_back(extra_args);
752 pybind11_fail(
"Internal error: function call dispatcher inserted wrong number of arguments!");
755 std::vector<bool> second_pass_convert;
760 second_pass_convert.resize(func.
nargs,
false);
767 result = func.
impl(call);
768 }
catch (reference_cast_error &) {
779 for (
size_t i = func.
is_method ? 1 : 0;
i < pos_args;
i++) {
780 if (second_pass_convert[
i]) {
793 for (
auto &call : second_pass) {
796 result = call.func.impl(call);
797 }
catch (reference_cast_error &) {
814 }
catch ( abi::__forced_unwind& ) {
829 auto last_exception = std::current_exception();
831 for (
auto& translator : registered_exception_translators) {
833 translator(last_exception);
835 last_exception = std::current_exception();
840 PyErr_SetString(PyExc_SystemError,
"Exception escaped from default exception translator!");
844 auto append_note_if_missing_header_is_suspected = [](std::string &
msg) {
845 if (
msg.find(
"std::") != std::string::npos) {
847 "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n"
848 "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n"
849 "conversions are optional and require extra headers to be included\n"
850 "when compiling your pybind11 module.";
858 std::string
msg = std::string(overloads->
name) +
"(): incompatible " +
859 std::string(overloads->
is_constructor ?
"constructor" :
"function") +
860 " arguments. The following argument types are supported:\n";
864 msg +=
" "+ std::to_string(++ctr) +
". ";
866 bool wrote_sig =
false;
869 std::string sig = it2->signature;
870 size_t start = sig.find(
'(') + 7;
871 if (start < sig.size()) {
873 size_t end = sig.find(
", "), next =
end + 2;
874 size_t ret = sig.rfind(
" -> ");
876 if (
end >= sig.size()) next =
end = sig.find(
')');
877 if (start <
end && next < sig.size()) {
878 msg.append(sig, start,
end - start);
880 msg.append(sig, next, ret - next);
885 if (!wrote_sig)
msg += it2->signature;
889 msg +=
"\nInvoked with: ";
890 auto args_ = reinterpret_borrow<tuple>(args_in);
891 bool some_args =
false;
892 for (
size_t ti = overloads->
is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
893 if (!some_args) some_args =
true;
898 msg +=
"<repr raised Error>";
902 auto kwargs = reinterpret_borrow<dict>(kwargs_in);
904 if (some_args)
msg +=
"; ";
907 for (
auto kwarg :
kwargs) {
910 msg += pybind11::str(
"{}=").format(kwarg.first);
914 msg +=
"<repr raised Error>";
920 append_note_if_missing_header_is_suspected(
msg);
921 PyErr_SetString(PyExc_TypeError,
msg.c_str());
923 }
else if (!result) {
924 std::string
msg =
"Unable to convert function return value to a "
925 "Python type! The signature was\n\t";
926 msg += it->signature;
927 append_note_if_missing_header_is_suspected(
msg);
928 PyErr_SetString(PyExc_TypeError,
msg.c_str());
931 if (overloads->
is_constructor && !self_value_and_holder.holder_constructed()) {
932 auto *pi =
reinterpret_cast<instance *
>(parent.
ptr());
933 self_value_and_holder.type->init_instance(pi,
nullptr);
948 #if PY_MAJOR_VERSION >= 3
960 template <
typename Func,
typename... Extra>
961 module_ &
def(
const char *name_, Func &&f,
const Extra& ... extra) {
981 std::string full_name = std::string(PyModule_GetName(
m_ptr))
982 + std::string(
".") + std::string(
name);
983 auto result = reinterpret_borrow<module_>(PyImport_AddModule(full_name.c_str()));
985 result.attr(
"__doc__") = pybind11::str(
doc);
992 PyObject *obj = PyImport_ImportModule(
name);
995 return reinterpret_steal<module_>(obj);
1000 PyObject *obj = PyImport_ReloadModule(
ptr());
1003 *
this = reinterpret_steal<module_>(obj);
1015 pybind11_fail(
"Error during initialization: multiple incompatible definitions with name \"" +
1016 std::string(
name) +
"\"");
1021 #if PY_MAJOR_VERSION >= 3
1022 using module_def = PyModuleDef;
1034 #if PY_MAJOR_VERSION >= 3
1036 def =
new (
def) PyModuleDef {
1037 PyModuleDef_HEAD_INIT,
1047 auto m = PyModule_Create(
def);
1054 if (PyErr_Occurred())
1056 pybind11_fail(
"Internal error in module_::create_extension_module()");
1060 return reinterpret_borrow<module_>(
m);
1073 PyObject *p = PyEval_GetGlobals();
1074 return reinterpret_borrow<dict>(p ? p :
module_::import(
"__main__").attr(
"__dict__").ptr());
1085 pybind11_fail(
"generic_type: cannot initialize type \"" + std::string(rec.
name) +
1086 "\": an object with that name is already defined");
1090 "\" is already registered!");
1095 auto *tinfo =
new detail::type_info();
1096 tinfo->type = (PyTypeObject *) m_ptr;
1097 tinfo->cpptype = rec.
type;
1101 tinfo->holder_size_in_ptrs = size_in_ptrs(rec.
holder_size);
1104 tinfo->simple_type =
true;
1105 tinfo->simple_ancestors =
true;
1110 auto tindex = std::type_index(*rec.
type);
1119 mark_parents_nonsimple(tinfo->type);
1120 tinfo->simple_ancestors =
false;
1124 tinfo->simple_ancestors = parent_tinfo->simple_ancestors;
1136 auto t = reinterpret_borrow<tuple>(
value->tp_bases);
1140 tinfo2->simple_type =
false;
1141 mark_parents_nonsimple((PyTypeObject *) h.ptr());
1147 void *get_buffer_data) {
1148 auto *
type = (PyHeapTypeObject*) m_ptr;
1151 if (!
type->ht_type.tp_as_buffer)
1153 "To be able to register buffer protocol support for the type '" +
1155 "' the associated class<>(..) invocation must "
1156 "include the pybind11::buffer_protocol() annotation!");
1158 tinfo->get_buffer = get_buffer;
1159 tinfo->get_buffer_data = get_buffer_data;
1165 detail::function_record *rec_func) {
1166 const auto is_static = rec_func && !(rec_func->is_method && rec_func->scope);
1167 const auto has_doc = rec_func && rec_func->doc && pybind11::options::show_user_defined_docstrings();
1169 : &PyProperty_Type));
1173 pybind11::str(has_doc ? rec_func->doc :
""));
1178 template <typename T, typename = void_t<decltype(static_cast<void *(*)(size_t)>(T::operator
new))>>
1185 : std::true_type { };
1188 : std::true_type { };
1197 #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1198 if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
1199 #ifdef __cpp_sized_deallocation
1200 ::operator
delete(p, s, std::align_val_t(a));
1202 ::operator
delete(p, std::align_val_t(a));
1207 #ifdef __cpp_sized_deallocation
1208 ::operator
delete(p, s);
1210 ::operator
delete(p);
1215 cls.attr(cf.
name()) = cf;
1216 if (strcmp(name_,
"__eq__") == 0 && !cls.attr(
"__dict__").contains(
"__hash__")) {
1217 cls.attr(
"__hash__") =
none();
1225 template <
typename ,
typename F>
1226 auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) {
return std::forward<F>(f); }
1228 template <
typename Derived,
typename Return,
typename Class,
typename... Args>
1231 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1235 template <
typename Derived,
typename Return,
typename Class,
typename... Args>
1236 auto method_adaptor(Return (Class::*pmf)(Args...)
const) -> Return (Derived::*)(Args...)
const {
1238 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1242 template <
typename type_,
typename...
options>
1244 template <
typename T>
using is_holder = detail::is_holder_type<type_, T>;
1245 template <
typename T>
using is_subtype = detail::is_strict_base_of<type_, T>;
1246 template <
typename T>
using is_base = detail::is_strict_base_of<T, type_>;
1248 template <
typename T>
struct is_valid_class_option :
1258 "Unknown/invalid class_ template parameters provided");
1261 "Cannot use an alias class with a non-polymorphic type");
1265 template <
typename... Extra>
1267 using namespace detail;
1274 none_of<std::is_same<multiple_inheritance, Extra>...>::
value),
1275 "Error: multiple inheritance bases must be specified via class_ template options");
1288 set_operator_new<type>(&record);
1300 instances[std::type_index(
typeid(
type_alias))] = instances[std::type_index(
typeid(
type))];
1306 rec.add_base(
typeid(
Base), [](
void *src) ->
void * {
1307 return static_cast<Base *
>(
reinterpret_cast<type *
>(src));
1314 template <
typename Func,
typename... Extra>
1315 class_ &
def(
const char *name_, Func&& f,
const Extra&... extra) {
1322 template <
typename Func,
typename... Extra>
class_ &
1325 "def_static(...) called with a non-static member function pointer");
1333 class_ &
def(
const detail::op_<id, ot, L, R> &op,
const Extra&... extra) {
1334 op.execute(*
this, extra...);
1340 op.execute_cast(*
this, extra...);
1344 template <
typename... Args,
typename... Extra>
1345 class_ &
def(
const detail::initimpl::constructor<Args...> &
init,
const Extra&... extra) {
1346 init.execute(*
this, extra...);
1350 template <
typename... Args,
typename... Extra>
1351 class_ &
def(
const detail::initimpl::alias_constructor<Args...> &
init,
const Extra&... extra) {
1352 init.execute(*
this, extra...);
1356 template <
typename... Args,
typename... Extra>
1362 template <
typename... Args,
typename... Extra>
1363 class_ &
def(detail::initimpl::pickle_factory<Args...> &&pf,
const Extra &...extra) {
1368 template <
typename Func>
1370 struct capture { Func func; };
1371 auto *ptr =
new capture { std::forward<Func>(func) };
1372 install_buffer_funcs([](PyObject *obj,
void *ptr) ->
buffer_info* {
1373 detail::make_caster<type> caster;
1374 if (!caster.load(obj,
false))
1385 template <
typename Return,
typename Class,
typename... Args>
1390 template <
typename Return,
typename Class,
typename... Args>
1392 return def_buffer([func] (
const type &obj) {
return (obj.*func)(); });
1395 template <
typename C,
typename D,
typename... Extra>
1404 template <
typename C,
typename D,
typename... Extra>
1412 template <
typename D,
typename... Extra>
1420 template <
typename D,
typename... Extra>
1428 template <
typename Getter,
typename... Extra>
1435 template <
typename... Extra>
1441 template <
typename Getter,
typename... Extra>
1447 template <
typename... Extra>
1453 template <
typename Getter,
typename Setter,
typename... Extra>
1457 template <
typename Getter,
typename... Extra>
1464 template <
typename... Extra>
1470 template <
typename Getter,
typename... Extra>
1476 template <
typename... Extra>
1479 "Argument annotations are not allowed for properties");
1480 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
1481 auto *rec_active = rec_fget;
1483 char *doc_prev = rec_fget->doc;
1485 if (rec_fget->doc && rec_fget->doc != doc_prev) {
1487 rec_fget->doc = strdup(rec_fget->doc);
1491 char *doc_prev = rec_fset->doc;
1493 if (rec_fset->doc && rec_fset->doc != doc_prev) {
1495 rec_fset->doc = strdup(rec_fset->doc);
1497 if (! rec_active) rec_active = rec_fset;
1499 def_property_static_impl(
name, fget, fset, rec_active);
1505 template <
typename T>
1506 static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
1507 const holder_type * ,
const std::enable_shared_from_this<T> * ) {
1509 auto sh = std::dynamic_pointer_cast<typename holder_type::element_type>(
1510 detail::try_get_shared_from_this(v_h.value_ptr<
type>()));
1513 v_h.set_holder_constructed();
1516 if (!v_h.holder_constructed() && inst->owned) {
1518 v_h.set_holder_constructed();
1522 static void init_holder_from_existing(
const detail::value_and_holder &v_h,
1527 static void init_holder_from_existing(
const detail::value_and_holder &v_h,
1528 const holder_type *holder_ptr, std::false_type ) {
1533 static void init_holder(detail::instance *inst, detail::value_and_holder &v_h,
1536 init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
1537 v_h.set_holder_constructed();
1540 v_h.set_holder_constructed();
1548 static void init_instance(detail::instance *inst,
const void *holder_ptr) {
1550 if (!v_h.instance_registered()) {
1552 v_h.set_instance_registered();
1554 init_holder(inst, v_h, (
const holder_type *) holder_ptr, v_h.value_ptr<
type>());
1558 static void dealloc(detail::value_and_holder &v_h) {
1566 if (v_h.holder_constructed()) {
1568 v_h.set_holder_constructed(
false);
1572 v_h.type->type_size,
1573 v_h.type->type_align
1576 v_h.value_ptr() =
nullptr;
1579 static detail::function_record *get_function_record(
handle h) {
1581 return h ? (detail::function_record *) reinterpret_borrow<capsule>(PyCFunction_GET_SELF(h.
ptr()))
1587 template <
typename... Args> detail::initimpl::constructor<Args...>
init() {
return {}; }
1590 template <
typename... Args> detail::initimpl::alias_constructor<Args...>
init_alias() {
return {}; }
1593 template <
typename Func,
typename Ret = detail::initimpl::factory<Func>>
1594 Ret
init(Func &&f) {
return {std::forward<Func>(f)}; }
1598 template <
typename CFunc,
typename AFunc,
typename Ret = detail::initimpl::factory<CFunc, AFunc>>
1600 return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
1605 template <
typename GetState,
typename SetState>
1606 detail::initimpl::pickle_factory<GetState, SetState>
pickle(GetState &&g, SetState &&s) {
1607 return {std::forward<GetState>(g), std::forward<SetState>(s)};
1613 dict entries =
arg.get_type().attr(
"__entries");
1614 for (
auto kv : entries) {
1616 return pybind11::str(kv.first);
1625 m_base.attr(
"__entries") =
dict();
1626 auto property =
handle((PyObject *) &PyProperty_Type);
1632 object type_name =
type.attr(
"__name__");
1642 return pybind11::str(
"{}.{}").format(type_name,
enum_name(
arg));
1648 std::string docstring;
1649 dict entries =
arg.attr(
"__entries");
1650 if (((PyTypeObject *)
arg.ptr())->tp_doc)
1651 docstring += std::string(((PyTypeObject *)
arg.ptr())->tp_doc) +
"\n\n";
1652 docstring +=
"Members:";
1653 for (
auto kv : entries) {
1654 auto key = std::string(pybind11::str(kv.first));
1655 auto comment = kv.second[
int_(1)];
1656 docstring +=
"\n\n " + key;
1657 if (!comment.is_none())
1658 docstring +=
" : " + (std::string) pybind11::str(comment);
1664 m_base.attr(
"__members__") = static_property(
cpp_function(
1666 dict entries =
arg.attr(
"__entries"),
m;
1667 for (
auto kv : entries)
1668 m[kv.first] = kv.second[
int_(0)];
1673 #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \
1674 m_base.attr(op) = cpp_function( \
1675 [](object a, object b) { \
1676 if (!type::handle_of(a).is(type::handle_of(b))) \
1680 name(op), is_method(m_base), arg("other"))
1682 #define PYBIND11_ENUM_OP_CONV(op, expr) \
1683 m_base.attr(op) = cpp_function( \
1684 [](object a_, object b_) { \
1685 int_ a(a_), b(b_); \
1688 name(op), is_method(m_base), arg("other"))
1690 #define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \
1691 m_base.attr(op) = cpp_function( \
1692 [](object a_, object b) { \
1696 name(op), is_method(m_base), arg("other"))
1698 if (is_convertible) {
1702 if (is_arithmetic) {
1720 if (is_arithmetic) {
1721 #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!");
1726 #undef PYBIND11_THROW
1730 #undef PYBIND11_ENUM_OP_CONV_LHS
1731 #undef PYBIND11_ENUM_OP_CONV
1732 #undef PYBIND11_ENUM_OP_STRICT
1742 dict entries = m_base.attr(
"__entries");
1745 std::string type_name = (std::string)
str(m_base.attr(
"__name__"));
1746 throw value_error(type_name +
": element \"" + std::string(name_) +
"\" already exists!");
1754 dict entries = m_base.attr(
"__entries");
1755 for (
auto kv : entries)
1756 m_parent.attr(kv.first) = kv.second[
int_(0)];
1771 using Base::def_property_readonly;
1772 using Base::def_property_readonly_static;
1773 using Scalar =
typename std::underlying_type<Type>::type;
1775 template <
typename... Extra>
1778 constexpr
bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>
::value;
1780 m_base.init(is_arithmetic, is_convertible);
1785 #if PY_MAJOR_VERSION < 3
1788 #if PY_MAJOR_VERSION > 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 8)
1793 [](detail::value_and_holder &v_h,
Scalar arg) {
1794 detail::initimpl::setstate<Base>(v_h,
static_cast<Type
>(
arg),
1795 Py_TYPE(v_h.inst) != v_h.type->type); },
1796 detail::is_new_style_constructor(),
1797 pybind11::name(
"__setstate__"),
is_method(*
this),
arg(
"state"));
1813 detail::enum_base m_base;
1820 if (!nurse || !patient)
1823 if (patient.is_none() || nurse.is_none())
1827 if (!tinfo.empty()) {
1839 weakref wr(nurse, disable_lifesupport);
1842 (void) wr.release();
1847 auto get_arg = [&](
size_t n) {
1852 else if (n <= call.
args.size())
1853 return call.
args[n - 1];
1862 #ifdef __cpp_lib_unordered_map_try_emplace
1865 .emplace(
type, std::vector<detail::type_info *>());
1879 template <
typename Iterator,
typename Sentinel,
bool KeyIterator, return_value_policy Policy>
1892 #ifndef DOXYGEN_SHOULD_SKIP_THIS // Issue in breathe 4.26.1
1893 typename ValueType = decltype(*std::declval<Iterator>()),
1897 using state = detail::iterator_state<Iterator, Sentinel, false, Policy>;
1902 .
def(
"__next__", [](
state &s) -> ValueType {
1903 if (!s.first_or_done)
1906 s.first_or_done =
false;
1907 if (s.it == s.end) {
1908 s.first_or_done = true;
1909 throw stop_iteration();
1912 }, std::forward<Extra>(extra)..., Policy);
1923 #ifndef DOXYGEN_SHOULD_SKIP_THIS // Issue in breathe 4.26.1
1924 typename KeyType = decltype((*std::declval<Iterator>()).
first),
1928 using state = detail::iterator_state<Iterator, Sentinel, true, Policy>;
1933 .
def(
"__next__", [](
state &s) -> KeyType {
1934 if (!s.first_or_done)
1937 s.first_or_done =
false;
1938 if (s.it == s.end) {
1939 s.first_or_done = true;
1940 throw stop_iteration();
1942 return (*s.it).first;
1943 }, std::forward<Extra>(extra)..., Policy);
1966 set_flag(
bool &flag_) : flag(flag_) { flag_ =
true; }
1967 ~set_flag() { flag =
false; }
1969 auto implicit_caster = [](PyObject *obj, PyTypeObject *
type) -> PyObject * {
1970 static bool currently_used =
false;
1973 set_flag flag_helper(currently_used);
1974 if (!detail::make_caster<InputType>().load(obj,
false))
1978 PyObject *result = PyObject_Call((PyObject *)
type,
args.
ptr(),
nullptr);
1979 if (result ==
nullptr)
1985 tinfo->implicit_conversions.push_back(implicit_caster);
1987 pybind11_fail(
"implicitly_convertible: Unable to find type " + type_id<OutputType>());
1990 template <
typename ExceptionTranslator>
1993 std::forward<ExceptionTranslator>(translator));
2003 template <
typename type>
2008 std::string full_name =
scope.attr(
"__name__").cast<std::string>() +
2009 std::string(
".") +
name;
2010 m_ptr = PyErr_NewException(
const_cast<char *
>(full_name.c_str()),
base.ptr(), NULL);
2012 pybind11_fail(
"Error during initialization: multiple incompatible "
2013 "definitions with name \"" + std::string(
name) +
"\"");
2019 PyErr_SetString(m_ptr, message);
2027 template <
typename CppException>
2037 template <
typename CppException>
2041 auto &ex = detail::get_exception_object<CppException>();
2047 std::rethrow_exception(p);
2048 }
catch (
const CppException &e) {
2049 detail::get_exception_object<CppException>()(e.what());
2062 auto line = sep.attr(
"join")(strings);
2079 auto write =
file.attr(
"write");
2084 file.attr(
"flush")();
2090 auto c = detail::collect_arguments<policy>(std::forward<Args>(
args)...);
2094 #if defined(WITH_THREAD) && !defined(PYPY_VERSION)
2130 tstate = PyGILState_GetThisThreadState();
2134 tstate = PyThreadState_New(
internals.istate);
2135 #if !defined(NDEBUG)
2137 pybind11_fail(
"scoped_acquire: could not create thread state!");
2139 tstate->gilstate_counter = 0;
2146 PyEval_AcquireThread(tstate);
2153 ++tstate->gilstate_counter;
2157 --tstate->gilstate_counter;
2158 #if !defined(NDEBUG)
2160 pybind11_fail(
"scoped_acquire::dec_ref(): thread state must be current!");
2161 if (tstate->gilstate_counter < 0)
2162 pybind11_fail(
"scoped_acquire::dec_ref(): reference count underflow!");
2164 if (tstate->gilstate_counter == 0) {
2165 #if !defined(NDEBUG)
2167 pybind11_fail(
"scoped_acquire::dec_ref(): internal error!");
2169 PyThreadState_Clear(tstate);
2171 PyThreadState_DeleteCurrent();
2189 PyEval_SaveThread();
2192 PyThreadState *tstate =
nullptr;
2193 bool release =
true;
2204 tstate = PyEval_SaveThread();
2225 PyEval_RestoreThread(tstate);
2232 PyThreadState *tstate;
2236 #elif defined(PYPY_VERSION)
2238 PyGILState_STATE
state;
2246 PyThreadState *
state;
2265 m_type.release().dec_ref();
2266 m_value.release().dec_ref();
2267 m_trace.release().dec_ref();
2282 if (cache.find(key) != cache.end())
2285 function override =
getattr(
self,
name,
function());
2286 if (
override.is_cpp_function()) {
2293 #if !defined(PYPY_VERSION)
2294 PyFrameObject *frame = PyThreadState_Get()->frame;
2295 if (frame && (std::string)
str(frame->f_code->co_name) ==
name &&
2296 frame->f_code->co_argcount > 0) {
2297 PyFrame_FastToLocals(frame);
2298 PyObject *self_caller = PyDict_GetItem(
2299 frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
2300 if (self_caller ==
self.ptr())
2307 dict d; d[
"self"] =
self; d[
"name"] = pybind11::str(
name);
2308 PyObject *result = PyRun_String(
2310 "frame = inspect.currentframe()\n"
2311 "if frame is not None:\n"
2312 " frame = frame.f_back\n"
2313 " if frame is not None and str(frame.f_code.co_name) == name and "
2314 "frame.f_code.co_argcount > 0:\n"
2315 " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
2316 " if self_caller == self:\n"
2318 Py_file_input, d.
ptr(), d.
ptr());
2319 if (result ==
nullptr)
2321 if (d[
"self"].is_none())
2343 #define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...) \
2345 pybind11::gil_scoped_acquire gil; \
2346 pybind11::function override = pybind11::get_override(static_cast<const cname *>(this), name); \
2348 auto o = override(__VA_ARGS__); \
2349 if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
2350 static pybind11::detail::override_caster_t<ret_type> caster; \
2351 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
2353 else return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
2374 #define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...) \
2376 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2377 return cname::fn(__VA_ARGS__); \
2384 #define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \
2386 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \
2387 pybind11::pybind11_fail("Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\""); \
2414 #define PYBIND11_OVERRIDE(ret_type, cname, fn, ...) \
2415 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2421 #define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \
2422 PYBIND11_OVERRIDE_PURE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__)
2437 #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) \
2438 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__)
2439 #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
2440 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__)
2441 #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
2442 PYBIND11_OVERRIDE_PURE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__);
2443 #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
2444 PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__)
2445 #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
2446 PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__);
2450 #if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
2451 # pragma warning(pop)
2452 #elif defined(__GNUG__) && !defined(__clang__)
2453 # pragma GCC diagnostic pop