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 #elif defined(__GNUG__) && !defined(__clang__) 33 # pragma GCC diagnostic push 34 # pragma GCC diagnostic ignored "-Wunused-but-set-parameter" 35 # pragma GCC diagnostic ignored "-Wunused-but-set-variable" 36 # pragma GCC diagnostic ignored "-Wmissing-field-initializers" 37 # pragma GCC diagnostic ignored "-Wstrict-aliasing" 38 # pragma GCC diagnostic ignored "-Wattributes" 40 # pragma GCC diagnostic ignored "-Wnoexcept-type" 49 #if defined(__GNUG__) && !defined(__clang__) 62 template <
typename Return,
typename... Args,
typename... Extra>
68 template <
typename Func,
typename... Extra,
72 (detail::function_signature_t<Func> *)
nullptr, extra...);
76 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
78 initialize([f](Class *
c, Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
79 (Return (*) (Class *, Arg...))
nullptr, extra...);
85 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
87 initialize([f](Class *
c, Arg...
args) -> Return { return (c->*f)(args...); },
88 (Return (*) (Class *, Arg...))
nullptr, extra...);
92 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
93 cpp_function(Return (Class::*f)(Arg...)
const,
const Extra&... extra) {
94 initialize([f](
const Class *
c, Arg...
args) -> Return { return (c->*f)(std::forward<Arg>(args)...); },
95 (Return (*)(
const Class *, Arg ...))
nullptr, extra...);
101 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
102 cpp_function(Return (Class::*f)(Arg...)
const&,
const Extra&... extra) {
103 initialize([f](
const Class *
c, Arg...
args) -> Return { return (c->*f)(args...); },
104 (Return (*)(
const Class *, Arg ...))
nullptr, extra...);
108 object name()
const {
return attr(
"__name__"); }
113 return new detail::function_record();
117 template <
typename Func,
typename Return,
typename... Args,
typename... Extra>
118 void initialize(Func &&f, Return (*)(Args...),
const Extra&... extra) {
123 auto rec = make_function_record();
126 if (
sizeof(
capture) <=
sizeof(rec->data)) {
130 #if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6 131 # pragma GCC diagnostic push 132 # pragma GCC diagnostic ignored "-Wplacement-new" 135 #if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6 136 # pragma GCC diagnostic pop 141 rec->data[0] =
new capture { std::forward<Func>(
f) };
151 static_assert(expected_num_args<Extra...>(
sizeof...(Args), cast_in::has_args, cast_in::has_kwargs),
152 "The number of argument annotations does not match the number of function arguments");
156 cast_in args_converter;
159 if (!args_converter.load_args(call))
166 auto data = (
sizeof(
capture) <=
sizeof(call.func.data)
167 ? &call.func.data : call.func.data[0]);
178 std::move(args_converter).
template call<Return, Guard>(cap->f), policy, call.parent);
190 constexpr
bool has_kw_only_args = any_of<std::is_same<kw_only, Extra>...>
::value,
191 has_pos_only_args = any_of<std::is_same<pos_only, Extra>...>
::value,
192 has_args = any_of<std::is_same<args, Args>...>
::value,
193 has_arg_annotations = any_of<is_keyword<Extra>...>
::value;
194 static_assert(has_arg_annotations || !has_kw_only_args,
"py::kw_only requires the use of argument annotations");
195 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)");
196 static_assert(!(has_args && has_kw_only_args),
"py::kw_only cannot be combined with a py::args argument");
200 static constexpr
auto signature =
_(
"(") + cast_in::arg_names +
_(
") -> ") +
cast_out::name;
204 initialize_generic(rec, signature.text, types.data(),
sizeof...(Args));
206 if (cast_in::has_args) rec->has_args =
true;
207 if (cast_in::has_kwargs) rec->has_kwargs =
true;
210 using FunctionType = Return (*)(Args...);
211 constexpr
bool is_function_ptr =
213 sizeof(
capture) ==
sizeof(
void *);
214 if (is_function_ptr) {
215 rec->is_stateless =
true;
216 rec->data[1] =
const_cast<void *
>(
reinterpret_cast<const void *
>(&
typeid(FunctionType)));
222 const std::type_info *
const *types,
size_t args) {
225 rec->name = strdup(rec->name ? rec->name :
"");
226 if (rec->doc) rec->doc = strdup(rec->doc);
227 for (
auto &
a: rec->args) {
229 a.name = strdup(
a.name);
231 a.descr = strdup(
a.descr);
233 a.descr = strdup(
repr(
a.value).
cast<std::string>().c_str());
236 rec->is_constructor = !strcmp(rec->name,
"__init__") || !strcmp(rec->name,
"__setstate__");
238 #if !defined(NDEBUG) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING) 239 if (rec->is_constructor && !rec->is_new_style_constructor) {
240 const auto class_name = std::string(((PyTypeObject *) rec->scope.ptr())->tp_name);
241 const auto func_name = std::string(rec->name);
244 (
"pybind11-bound class '" + class_name +
"' is using an old-style " 245 "placement-new '" + func_name +
"' which has been deprecated. See " 246 "the upgrade guide in pybind11's docs. This message is only visible " 247 "when compiled in debug mode.").
c_str(), 0
253 std::string signature;
254 size_t type_index = 0, arg_index = 0;
255 for (
auto *
pc = text; *
pc !=
'\0'; ++
pc) {
260 if (*(
pc + 1) ==
'*')
264 if (rec->nargs_kw_only > 0 && arg_index + rec->nargs_kw_only == args)
266 if (arg_index < rec->args.size() && rec->args[arg_index].name) {
267 signature += rec->args[arg_index].name;
268 }
else if (arg_index == 0 && rec->is_method) {
271 signature +=
"arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
274 }
else if (
c ==
'}') {
276 if (arg_index < rec->args.size() && rec->args[arg_index].descr) {
278 signature += rec->args[arg_index].descr;
282 if (rec->nargs_pos_only > 0 && (arg_index + 1) == rec->nargs_pos_only)
285 }
else if (
c ==
'%') {
286 const std::type_info *
t = types[type_index++];
288 pybind11_fail(
"Internal error while parsing type signature (1)");
290 handle th((PyObject *) tinfo->type);
292 th.attr(
"__module__").
cast<std::string>() +
"." +
293 th.attr(
"__qualname__").
cast<std::string>();
294 }
else if (rec->is_new_style_constructor && arg_index == 0) {
298 rec->scope.attr(
"__module__").cast<std::string>() +
"." +
299 rec->scope.attr(
"__qualname__").cast<std::string>();
301 std::string tname(t->name());
310 if (arg_index != args || types[type_index] !=
nullptr)
311 pybind11_fail(
"Internal error while parsing type signature (2)");
313 #if PY_MAJOR_VERSION < 3 314 if (strcmp(rec->name,
"__next__") == 0) {
315 std::free(rec->name);
316 rec->name = strdup(
"next");
317 }
else if (strcmp(rec->name,
"__bool__") == 0) {
318 std::free(rec->name);
319 rec->name = strdup(
"__nonzero__");
322 rec->signature = strdup(signature.c_str());
323 rec->args.shrink_to_fit();
329 detail::function_record *chain =
nullptr, *chain_start = rec;
331 if (PyCFunction_Check(rec->sibling.ptr())) {
332 auto rec_capsule = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(rec->sibling.ptr()));
333 chain = (detail::function_record *) rec_capsule;
336 if (!chain->scope.is(rec->scope))
340 else if (!rec->sibling.is_none() && rec->name[0] !=
'_')
341 pybind11_fail(
"Cannot overload existing non-function object \"" + std::string(rec->name) +
342 "\" with a function of the same name");
347 rec->def =
new PyMethodDef();
348 std::memset(rec->def, 0,
sizeof(PyMethodDef));
349 rec->def->ml_name = rec->name;
350 rec->def->ml_meth =
reinterpret_cast<PyCFunction
>(
reinterpret_cast<void (*) (
void)
>(*dispatcher));
351 rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
354 destruct((detail::function_record *) ptr);
359 if (
hasattr(rec->scope,
"__module__")) {
360 scope_module = rec->scope.attr(
"__module__");
361 }
else if (
hasattr(rec->scope,
"__name__")) {
362 scope_module = rec->scope.attr(
"__name__");
366 m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
368 pybind11_fail(
"cpp_function::cpp_function(): Could not allocate function object");
371 m_ptr = rec->sibling.ptr();
374 if (chain->is_method != rec->is_method)
375 pybind11_fail(
"overloading a method with both static and instance methods is not supported; " 377 "compile in debug mode for more details" 379 "error while attempting to bind " + std::string(rec->is_method ?
"instance" :
"static") +
" method " +
380 std::string(
pybind11::str(rec->scope.attr(
"__name__"))) +
"." + std::string(rec->name) + signature
388 std::string signatures;
394 signatures += rec->name;
395 signatures +=
"(*args, **kwargs)\n";
396 signatures +=
"Overloaded function.\n\n";
399 bool first_user_def =
true;
400 for (
auto it = chain_start; it !=
nullptr; it = it->next) {
402 if (index > 0) signatures +=
"\n";
404 signatures += std::to_string(++index) +
". ";
405 signatures += rec->name;
406 signatures += it->signature;
413 if (first_user_def) first_user_def =
false;
414 else signatures +=
"\n";
417 signatures += it->doc;
423 auto *
func = (PyCFunctionObject *) m_ptr;
424 if (
func->m_ml->ml_doc)
425 std::free(const_cast<char *>(
func->m_ml->ml_doc));
426 func->m_ml->ml_doc = strdup(signatures.c_str());
428 if (rec->is_method) {
431 pybind11_fail(
"cpp_function::cpp_function(): Could not allocate instance method object");
437 static void destruct(detail::function_record *rec) {
439 detail::function_record *next = rec->next;
442 std::free((
char *) rec->name);
443 std::free((
char *) rec->doc);
444 std::free((
char *) rec->signature);
445 for (
auto &
arg: rec->args) {
446 std::free(const_cast<char *>(
arg.
name));
447 std::free(const_cast<char *>(
arg.descr));
451 std::free(const_cast<char *>(rec->def->ml_doc));
460 static PyObject *
dispatcher(PyObject *
self, PyObject *args_in, PyObject *kwargs_in) {
468 const auto n_args_in = (
size_t) PyTuple_GET_SIZE(args_in);
470 handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) :
nullptr,
476 const auto pi =
reinterpret_cast<instance *
>(parent.
ptr());
479 if (!self_value_and_holder.type || !self_value_and_holder.inst) {
480 PyErr_SetString(PyExc_TypeError,
"__init__(self, ...) called with invalid `self` argument");
486 if (self_value_and_holder.instance_registered())
487 return none().release().ptr();
495 std::vector<function_call> second_pass;
498 const bool overloaded = it !=
nullptr && it->next !=
nullptr;
500 for (; it !=
nullptr; it = it->next) {
522 size_t num_args = func.
nargs;
527 if (!func.
has_args && n_args_in > pos_args)
530 if (n_args_in < pos_args && func.
args.size() < pos_args)
535 size_t args_to_copy = (
std::min)(pos_args, n_args_in);
536 size_t args_copied = 0;
542 if (self_value_and_holder)
543 self_value_and_holder.type->dealloc(self_value_and_holder);
545 call.
init_self = PyTuple_GET_ITEM(args_in, 0);
546 call.
args.emplace_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
552 bool bad_arg =
false;
553 for (; args_copied < args_to_copy; ++args_copied) {
555 if (kwargs_in && arg_rec && arg_rec->
name && PyDict_GetItemString(kwargs_in, arg_rec->
name)) {
560 handle arg(PyTuple_GET_ITEM(args_in, args_copied));
561 if (arg_rec && !arg_rec->
none && arg.is_none()) {
565 call.
args.push_back(arg);
572 dict kwargs = reinterpret_borrow<dict>(kwargs_in);
577 const auto &
arg = func.
args[args_copied];
584 call.
args.push_back(value);
595 if (args_copied < num_args) {
596 bool copied_kwargs =
false;
598 for (; args_copied < num_args; ++args_copied) {
599 const auto &
arg = func.
args[args_copied];
603 value = PyDict_GetItemString(kwargs.
ptr(),
arg.
name);
607 if (!copied_kwargs) {
608 kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.
ptr()));
609 copied_kwargs =
true;
612 }
else if (
arg.value) {
617 call.
args.push_back(value);
624 if (args_copied < num_args)
635 if (args_to_copy == 0) {
638 extra_args = reinterpret_borrow<tuple>(args_in);
639 }
else if (args_copied >= n_args_in) {
640 extra_args =
tuple(0);
642 size_t args_size = n_args_in - args_copied;
643 extra_args =
tuple(args_size);
644 for (
size_t i = 0;
i < args_size; ++
i) {
645 extra_args[
i] = PyTuple_GET_ITEM(args_in, args_copied +
i);
648 call.
args.push_back(extra_args);
650 call.
args_ref = std::move(extra_args);
657 call.
args.push_back(kwargs);
666 pybind11_fail(
"Internal error: function call dispatcher inserted wrong number of arguments!");
669 std::vector<bool> second_pass_convert;
674 second_pass_convert.resize(func.
nargs,
false);
682 }
catch (reference_cast_error &) {
693 for (
size_t i = func.
is_method ? 1 : 0;
i < pos_args;
i++) {
694 if (second_pass_convert[
i]) {
698 second_pass.push_back(std::move(call));
707 for (
auto &call : second_pass) {
710 result = call.func.impl(call);
711 }
catch (reference_cast_error &) {
727 #if defined(__GNUG__) && !defined(__clang__) 728 }
catch ( abi::__forced_unwind& ) {
743 auto last_exception = std::current_exception();
745 for (
auto& translator : registered_exception_translators) {
747 translator(last_exception);
749 last_exception = std::current_exception();
754 PyErr_SetString(PyExc_SystemError,
"Exception escaped from default exception translator!");
758 auto append_note_if_missing_header_is_suspected = [](std::string &
msg) {
759 if (
msg.find(
"std::") != std::string::npos) {
761 "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n" 762 "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n" 763 "conversions are optional and require extra headers to be included\n" 764 "when compiling your pybind11 module.";
772 std::string
msg = std::string(overloads->
name) +
"(): incompatible " +
773 std::string(overloads->
is_constructor ?
"constructor" :
"function") +
774 " arguments. The following argument types are supported:\n";
778 msg +=
" "+ std::to_string(++ctr) +
". ";
780 bool wrote_sig =
false;
783 std::string sig = it2->signature;
784 size_t start = sig.find(
'(') + 7;
785 if (start < sig.size()) {
787 size_t end = sig.find(
", "), next = end + 2;
788 size_t ret = sig.rfind(
" -> ");
790 if (end >= sig.size()) next = end = sig.find(
')');
791 if (start < end && next < sig.size()) {
792 msg.append(sig, start, end - start);
794 msg.append(sig, next, ret - next);
799 if (!wrote_sig) msg += it2->signature;
803 msg +=
"\nInvoked with: ";
804 auto args_ = reinterpret_borrow<tuple>(args_in);
805 bool some_args =
false;
806 for (
size_t ti = overloads->
is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
807 if (!some_args) some_args =
true;
812 msg +=
"<repr raised Error>";
816 auto kwargs = reinterpret_borrow<dict>(kwargs_in);
818 if (some_args) msg +=
"; ";
821 for (
auto kwarg :
kwargs) {
822 if (first) first =
false;
828 msg +=
"<repr raised Error>";
834 append_note_if_missing_header_is_suspected(msg);
835 PyErr_SetString(PyExc_TypeError, msg.c_str());
838 std::string
msg =
"Unable to convert function return value to a " 839 "Python type! The signature was\n\t";
840 msg += it->signature;
841 append_note_if_missing_header_is_suspected(msg);
842 PyErr_SetString(PyExc_TypeError, msg.c_str());
845 if (overloads->
is_constructor && !self_value_and_holder.holder_constructed()) {
846 auto *pi =
reinterpret_cast<instance *
>(parent.
ptr());
847 self_value_and_holder.type->init_instance(pi,
nullptr);
862 #if PY_MAJOR_VERSION >= 3 863 auto *def =
new PyModuleDef();
864 std::memset(def, 0,
sizeof(PyModuleDef));
869 m_ptr = PyModule_Create(def);
871 m_ptr = Py_InitModule3(name,
nullptr,
doc);
873 if (m_ptr ==
nullptr)
883 template <
typename Func,
typename... Extra>
884 module_ &
def(
const char *name_, Func &&f,
const Extra& ... extra) {
889 add_object(name_, func,
true );
904 std::string full_name = std::string(PyModule_GetName(m_ptr))
905 + std::string(
".") + std::string(name);
906 auto result = reinterpret_borrow<module_>(PyImport_AddModule(full_name.c_str()));
915 PyObject *obj = PyImport_ImportModule(
name);
918 return reinterpret_steal<module_>(obj);
923 PyObject *obj = PyImport_ReloadModule(
ptr());
926 *
this = reinterpret_steal<module_>(obj);
935 if (!overwrite &&
hasattr(*
this, name))
936 pybind11_fail(
"Error during initialization: multiple incompatible definitions with name \"" +
937 std::string(name) +
"\"");
949 PyObject *
p = PyEval_GetGlobals();
950 return reinterpret_borrow<dict>(p ? p :
module::import(
"__main__").attr(
"__dict__").
ptr());
955 class generic_type : public
object {
956 template <
typename...>
friend class class_;
961 if (rec.scope &&
hasattr(rec.scope, rec.name))
962 pybind11_fail(
"generic_type: cannot initialize type \"" + std::string(rec.name) +
963 "\": an object with that name is already defined");
966 pybind11_fail(
"generic_type: type \"" + std::string(rec.name) +
967 "\" is already registered!");
972 auto *tinfo =
new detail::type_info();
973 tinfo->type = (PyTypeObject *) m_ptr;
974 tinfo->cpptype = rec.type;
975 tinfo->type_size = rec.type_size;
976 tinfo->type_align = rec.type_align;
977 tinfo->operator_new = rec.operator_new;
978 tinfo->holder_size_in_ptrs =
size_in_ptrs(rec.holder_size);
979 tinfo->init_instance = rec.init_instance;
980 tinfo->dealloc = rec.dealloc;
981 tinfo->simple_type =
true;
982 tinfo->simple_ancestors =
true;
983 tinfo->default_holder = rec.default_holder;
984 tinfo->module_local = rec.module_local;
987 auto tindex = std::type_index(*rec.type);
989 if (rec.module_local)
995 if (rec.bases.size() > 1 || rec.multiple_inheritance) {
996 mark_parents_nonsimple(tinfo->type);
997 tinfo->simple_ancestors =
false;
999 else if (rec.bases.size() == 1) {
1000 auto parent_tinfo =
get_type_info((PyTypeObject *) rec.bases[0].ptr());
1001 tinfo->simple_ancestors = parent_tinfo->simple_ancestors;
1004 if (rec.module_local) {
1013 auto t = reinterpret_borrow<tuple>(value->tp_bases);
1017 tinfo2->simple_type =
false;
1018 mark_parents_nonsimple((PyTypeObject *)
h.ptr());
1024 void *get_buffer_data) {
1025 auto *
type = (PyHeapTypeObject*) m_ptr;
1028 if (!
type->ht_type.tp_as_buffer)
1030 "To be able to register buffer protocol support for the type '" +
1031 std::string(tinfo->type->tp_name) +
1032 "' the associated class<>(..) invocation must " 1033 "include the pybind11::buffer_protocol() annotation!");
1035 tinfo->get_buffer = get_buffer;
1036 tinfo->get_buffer_data = get_buffer_data;
1042 detail::function_record *rec_func) {
1043 const auto is_static = rec_func && !(rec_func->is_method && rec_func->scope);
1044 const auto has_doc = rec_func && rec_func->doc && pybind11::options::show_user_defined_docstrings();
1046 : &PyProperty_Type));
1047 attr(name) = property(fget.
ptr() ? fget : none(),
1048 fset.
ptr() ? fset : none(),
1055 template <
typename T,
typename =
void_t<decltype(static_cast<
void *(*)(
size_t)>(T::operator new))>>
1062 : std::true_type { };
1065 : std::true_type { };
1074 #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912) 1075 if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
1076 #ifdef __cpp_sized_deallocation 1077 ::operator
delete(
p,
s, std::align_val_t(a));
1079 ::operator
delete(
p, std::align_val_t(a));
1084 #ifdef __cpp_sized_deallocation 1085 ::operator
delete(
p,
s);
1087 ::operator
delete(
p);
1092 cls.attr(cf.
name()) = cf;
1093 if (strcmp(name_,
"__eq__") == 0 && !cls.attr(
"__dict__").contains(
"__hash__")) {
1094 cls.attr(
"__hash__") = none();
1100 template <
typename ,
typename F>
1105 template <
typename Derived,
typename Return,
typename Class,
typename... Args>
1108 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1112 template <
typename Derived,
typename Return,
typename Class,
typename... Args>
1113 auto method_adaptor(Return (Class::*pmf)(Args...)
const) -> Return (Derived::*)(Args...)
const {
1115 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1119 template <
typename type_,
typename...
options>
1121 template <
typename T>
using is_holder = detail::is_holder_type<type_, T>;
1122 template <
typename T>
using is_subtype = detail::is_strict_base_of<type_, T>;
1123 template <
typename T>
using is_base = detail::is_strict_base_of<T, type_>;
1135 "Unknown/invalid class_ template parameters provided");
1138 "Cannot use an alias class with a non-polymorphic type");
1142 template <typename... Extra>
1151 none_of<std::is_same<multiple_inheritance, Extra>...>::
value),
1152 "Error: multiple inheritance bases must be specified via class_ template options");
1165 set_operator_new<type>(&record);
1177 instances[std::type_index(
typeid(
type_alias))] = instances[std::type_index(
typeid(
type))];
1183 rec.add_base(
typeid(Base), [](
void *src) ->
void * {
1184 return static_cast<Base *
>(
reinterpret_cast<type *
>(src));
1191 template <
typename Func,
typename... Extra>
1192 class_ &
def(
const char *name_, Func&& f,
const Extra&... extra) {
1199 template <
typename Func,
typename... Extra> class_ &
1202 "def_static(...) called with a non-static member function pointer");
1210 class_ &
def(
const detail::op_<id, ot, L, R> &op,
const Extra&... extra) {
1211 op.execute(*
this, extra...);
1216 class_ &
def_cast(
const detail::op_<id, ot, L, R> &op,
const Extra&... extra) {
1217 op.execute_cast(*
this, extra...);
1221 template <
typename... Args,
typename... Extra>
1222 class_ &
def(
const detail::initimpl::constructor<Args...> &
init,
const Extra&... extra) {
1223 init.execute(*
this, extra...);
1227 template <
typename... Args,
typename... Extra>
1228 class_ &
def(
const detail::initimpl::alias_constructor<Args...> &
init,
const Extra&... extra) {
1229 init.execute(*
this, extra...);
1233 template <
typename... Args,
typename... Extra>
1234 class_ &
def(detail::initimpl::factory<Args...> &&
init,
const Extra&... extra) {
1235 std::move(
init).execute(*
this, extra...);
1239 template <
typename... Args,
typename... Extra>
1240 class_ &
def(detail::initimpl::pickle_factory<Args...> &&pf,
const Extra &...extra) {
1241 std::move(pf).execute(*
this, extra...);
1248 install_buffer_funcs([](PyObject *obj,
void *
ptr) ->
buffer_info* {
1249 detail::make_caster<type> caster;
1250 if (!caster.load(obj,
false))
1257 template <
typename Return,
typename Class,
typename... Args>
1259 return def_buffer([func] (
type &obj) {
return (obj.*func)(); });
1262 template <
typename Return,
typename Class,
typename... Args>
1264 return def_buffer([func] (
const type &obj) {
return (obj.*func)(); });
1267 template <
typename C,
typename D,
typename... Extra>
1276 template <
typename C,
typename D,
typename... Extra>
1284 template <
typename D,
typename... Extra>
1292 template <
typename D,
typename... Extra>
1300 template <
typename Getter,
typename... Extra>
1302 return def_property_readonly(name,
cpp_function(method_adaptor<type>(fget)),
1307 template <
typename... Extra>
1309 return def_property(name, fget,
nullptr, extra...);
1313 template <
typename Getter,
typename... Extra>
1319 template <
typename... Extra>
1321 return def_property_static(name, fget,
nullptr, extra...);
1325 template <
typename Getter,
typename Setter,
typename... Extra>
1326 class_ &
def_property(
const char *
name,
const Getter &fget,
const Setter &fset,
const Extra& ...extra) {
1327 return def_property(name, fget,
cpp_function(method_adaptor<type>(fset)), extra...);
1329 template <
typename Getter,
typename... Extra>
1331 return def_property(name,
cpp_function(method_adaptor<type>(fget)), fset,
1336 template <
typename... Extra>
1338 return def_property_static(name, fget, fset,
is_method(*
this), extra...);
1342 template <
typename Getter,
typename... Extra>
1348 template <
typename... Extra>
1351 "Argument annotations are not allowed for properties");
1352 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
1353 auto *rec_active = rec_fget;
1355 char *doc_prev = rec_fget->doc;
1357 if (rec_fget->doc && rec_fget->doc != doc_prev) {
1359 rec_fget->doc = strdup(rec_fget->doc);
1363 char *doc_prev = rec_fset->doc;
1365 if (rec_fset->doc && rec_fset->doc != doc_prev) {
1367 rec_fset->doc = strdup(rec_fset->doc);
1369 if (! rec_active) rec_active = rec_fset;
1371 def_property_static_impl(name, fget, fset, rec_active);
1377 template <
typename T>
1379 const holder_type * ,
const std::enable_shared_from_this<T> * ) {
1381 auto sh = std::dynamic_pointer_cast<
typename holder_type::element_type>(
1382 v_h.value_ptr<
type>()->shared_from_this());
1385 v_h.set_holder_constructed();
1387 }
catch (
const std::bad_weak_ptr &) {}
1389 if (!v_h.holder_constructed() && inst->owned) {
1391 v_h.set_holder_constructed();
1397 new (std::addressof(v_h.holder<
holder_type>()))
holder_type(*reinterpret_cast<const holder_type *>(holder_ptr));
1401 const holder_type *holder_ptr, std::false_type ) {
1402 new (std::addressof(v_h.holder<
holder_type>()))
holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
1409 init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
1410 v_h.set_holder_constructed();
1413 v_h.set_holder_constructed();
1423 if (!v_h.instance_registered()) {
1425 v_h.set_instance_registered();
1427 init_holder(inst, v_h, (
const holder_type *) holder_ptr, v_h.value_ptr<
type>());
1431 static void dealloc(detail::value_and_holder &v_h) {
1439 if (v_h.holder_constructed()) {
1441 v_h.set_holder_constructed(
false);
1445 v_h.type->type_size,
1446 v_h.type->type_align
1449 v_h.value_ptr() =
nullptr;
1454 return h ? (detail::function_record *) reinterpret_borrow<capsule>(PyCFunction_GET_SELF(h.
ptr()))
1460 template <
typename... Args> detail::initimpl::constructor<Args...>
init() {
return {}; }
1463 template <
typename... Args> detail::initimpl::alias_constructor<Args...>
init_alias() {
return {}; }
1466 template <
typename Func,
typename Ret = detail::initimpl::factory<Func>>
1467 Ret
init(Func &&f) {
return {std::forward<Func>(
f)}; }
1471 template <
typename CFunc,
typename AFunc,
typename Ret = detail::initimpl::factory<CFunc, AFunc>>
1473 return {std::forward<CFunc>(
c), std::forward<AFunc>(
a)};
1478 template <
typename GetState,
typename SetState>
1479 detail::initimpl::pickle_factory<GetState, SetState>
pickle(GetState &&
g, SetState &&s) {
1480 return {std::forward<GetState>(
g), std::forward<SetState>(s)};
1488 m_base.attr(
"__entries") =
dict();
1489 auto property =
handle((PyObject *) &PyProperty_Type);
1495 object type_name = type.attr(
"__name__");
1496 dict entries = type.attr(
"__entries");
1497 for (
const auto &kv : entries) {
1498 object other = kv.second[
int_(0)];
1499 if (other.equal(arg))
1509 for (
const auto &kv : entries) {
1518 [](
handle arg) -> std::string {
1519 std::string docstring;
1520 dict entries = arg.attr(
"__entries");
1521 if (((PyTypeObject *) arg.
ptr())->tp_doc)
1522 docstring += std::string(((PyTypeObject *) arg.
ptr())->tp_doc) +
"\n\n";
1523 docstring +=
"Members:";
1524 for (
const auto &kv : entries) {
1526 auto comment = kv.second[
int_(1)];
1527 docstring +=
"\n\n " +
key;
1528 if (!comment.is_none())
1533 ), none(), none(),
"");
1535 m_base.attr(
"__members__") = static_property(
cpp_function(
1537 dict entries = arg.attr(
"__entries"),
m;
1538 for (
const auto &kv : entries)
1539 m[kv.first] = kv.second[
int_(0)];
1541 },
name(
"__members__")), none(), none(),
"" 1544 #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \ 1545 m_base.attr(op) = cpp_function( \ 1546 [](object a, object b) { \ 1547 if (!type::handle_of(a).is(type::handle_of(b))) \ 1551 name(op), is_method(m_base)) 1553 #define PYBIND11_ENUM_OP_CONV(op, expr) \ 1554 m_base.attr(op) = cpp_function( \ 1555 [](object a_, object b_) { \ 1556 int_ a(a_), b(b_); \ 1559 name(op), is_method(m_base)) 1561 #define PYBIND11_ENUM_OP_CONV_LHS(op, expr) \ 1562 m_base.attr(op) = cpp_function( \ 1563 [](object a_, object b) { \ 1567 name(op), is_method(m_base)) 1569 if (is_convertible) {
1573 if (is_arithmetic) {
1585 [](
object arg) {
return ~(
int_(arg)); },
name(
"__invert__"),
is_method(m_base));
1591 if (is_arithmetic) {
1592 #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!"); 1597 #undef PYBIND11_THROW 1601 #undef PYBIND11_ENUM_OP_CONV_LHS 1602 #undef PYBIND11_ENUM_OP_CONV 1603 #undef PYBIND11_ENUM_OP_STRICT 1613 dict entries = m_base.attr(
"__entries");
1616 std::string
type_name = (std::string)
str(m_base.attr(
"__name__"));
1617 throw value_error(type_name +
": element \"" + std::string(name_) +
"\" already exists!");
1620 entries[
name] = std::make_pair(value,
doc);
1621 m_base.attr(name) =
value;
1625 dict entries = m_base.attr(
"__entries");
1626 for (
const auto &kv : entries)
1627 m_parent.attr(kv.first) = kv.second[
int_(0)];
1636 template <typename
Type> class
enum_ : public class_<
Type> {
1642 using Base::def_property_readonly;
1643 using Base::def_property_readonly_static;
1646 template <
typename... Extra>
1648 : class_<Type>(scope, name, extra...), m_base(*
this, scope) {
1649 constexpr
bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>
::value;
1651 m_base.init(is_arithmetic, is_convertible);
1653 def(
init([](
Scalar i) {
return static_cast<Type
>(
i); }));
1654 def(
"__int__", [](Type
value) {
return (
Scalar) value; });
1655 #if PY_MAJOR_VERSION < 3 1656 def(
"__long__", [](Type value) {
return (
Scalar) value; });
1658 #if PY_MAJOR_VERSION > 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 8) 1659 def(
"__index__", [](Type value) {
return (
Scalar) value; });
1663 [](detail::value_and_holder &v_h,
Scalar arg) {
1664 detail::initimpl::setstate<Base>(v_h,
static_cast<Type
>(
arg),
1665 Py_TYPE(v_h.inst) != v_h.type->type); },
1666 detail::is_new_style_constructor(),
1690 if (!nurse || !patient)
1693 if (patient.is_none() || nurse.is_none())
1697 if (!tinfo.empty()) {
1709 weakref wr(nurse, disable_lifesupport);
1712 (void) wr.release();
1717 auto get_arg = [&](
size_t n) {
1722 else if (
n <= call.
args.size())
1723 return call.
args[
n - 1];
1732 #ifdef __cpp_lib_unordered_map_try_emplace 1735 .emplace(type, std::vector<detail::type_info *>());
1749 template <
typename Iterator,
typename Sentinel,
bool KeyIterator, return_value_policy Policy>
1762 typename ValueType = decltype(*
std::declval<Iterator>()),
1765 typedef detail::iterator_state<Iterator, Sentinel, false, Policy> state;
1768 class_<state>(
handle(),
"iterator", pybind11::module_local())
1769 .def(
"__iter__", [](state &s) -> state& {
return s; })
1770 .def(
"__next__", [](state &s) -> ValueType {
1771 if (!s.first_or_done)
1774 s.first_or_done =
false;
1775 if (s.it == s.end) {
1776 s.first_or_done =
true;
1777 throw stop_iteration();
1780 }, std::forward<Extra>(extra)..., Policy);
1791 typename KeyType = decltype((*std::declval<Iterator>()).
first),
1794 using state = detail::iterator_state<Iterator, Sentinel, true, Policy>;
1797 class_<state>(
handle(),
"iterator", pybind11::module_local())
1798 .def(
"__iter__", [](state &s) -> state& {
return s; })
1799 .def(
"__next__", [](state &s) -> KeyType {
1800 if (!s.first_or_done)
1803 s.first_or_done =
false;
1804 if (s.it == s.end) {
1805 s.first_or_done =
true;
1806 throw stop_iteration();
1808 return (*s.it).first;
1809 }, std::forward<Extra>(extra)..., Policy);
1819 return make_iterator<Policy>(std::begin(value),
std::end(value), extra...);
1826 return make_key_iterator<Policy>(std::begin(value),
std::end(value), extra...);
1832 set_flag(
bool &flag) : flag(flag) { flag =
true; }
1833 ~set_flag() { flag =
false; }
1835 auto implicit_caster = [](PyObject *obj, PyTypeObject *
type) -> PyObject * {
1836 static bool currently_used =
false;
1839 set_flag flag_helper(currently_used);
1840 if (!detail::make_caster<InputType>().
load(obj,
false))
1844 PyObject *
result = PyObject_Call((PyObject *)
type, args.
ptr(),
nullptr);
1845 if (result ==
nullptr)
1851 tinfo->implicit_conversions.push_back(implicit_caster);
1853 pybind11_fail(
"implicitly_convertible: Unable to find type " + type_id<OutputType>());
1856 template <
typename ExceptionTranslator>
1859 std::forward<ExceptionTranslator>(translator));
1869 template <
typename type>
1872 exception() =
default;
1874 std::string full_name = scope.attr(
"__name__").
cast<std::string>() +
1875 std::string(
".") +
name;
1876 m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()),
base.ptr(),
NULL);
1878 pybind11_fail(
"Error during initialization: multiple incompatible " 1879 "definitions with name \"" + std::string(name) +
"\"");
1880 scope.attr(name) = *
this;
1885 PyErr_SetString(m_ptr, message);
1893 template <
typename CppException>
1903 template <
typename CppException>
1907 auto &ex = detail::get_exception_object<CppException>();
1913 std::rethrow_exception(p);
1914 }
catch (
const CppException &
e) {
1915 detail::get_exception_object<CppException>()(e.what());
1923 auto strings =
tuple(args.size());
1924 for (
size_t i = 0;
i < args.size(); ++
i) {
1925 strings[
i] =
str(args[
i]);
1927 auto sep = kwargs.contains(
"sep") ? kwargs[
"sep"] :
cast(
" ");
1928 auto line =
sep.attr(
"join")(strings);
1931 if (kwargs.contains(
"file")) {
1932 file = kwargs[
"file"].
cast<
object>();
1945 auto write = file.attr(
"write");
1947 write(kwargs.contains(
"end") ? kwargs[
"end"] :
cast(
"\n"));
1949 if (kwargs.contains(
"flush") && kwargs[
"flush"].cast<
bool>())
1950 file.attr(
"flush")();
1956 auto c = detail::collect_arguments<policy>(std::forward<Args>(
args)...);
1960 #if defined(WITH_THREAD) && !defined(PYPY_VERSION) 1996 tstate = PyGILState_GetThisThreadState();
2000 tstate = PyThreadState_New(
internals.istate);
2001 #if !defined(NDEBUG) 2003 pybind11_fail(
"scoped_acquire: could not create thread state!");
2005 tstate->gilstate_counter = 0;
2013 #if defined(Py_DEBUG) 2014 PyInterpreterState *interp = tstate->interp;
2015 tstate->interp =
nullptr;
2017 PyEval_AcquireThread(tstate);
2018 #if defined(Py_DEBUG) 2019 tstate->interp = interp;
2027 ++tstate->gilstate_counter;
2031 --tstate->gilstate_counter;
2032 #if !defined(NDEBUG) 2034 pybind11_fail(
"scoped_acquire::dec_ref(): thread state must be current!");
2035 if (tstate->gilstate_counter < 0)
2036 pybind11_fail(
"scoped_acquire::dec_ref(): reference count underflow!");
2038 if (tstate->gilstate_counter == 0) {
2039 #if !defined(NDEBUG) 2041 pybind11_fail(
"scoped_acquire::dec_ref(): internal error!");
2043 PyThreadState_Clear(tstate);
2044 PyThreadState_DeleteCurrent();
2053 PyEval_SaveThread();
2056 PyThreadState *tstate =
nullptr;
2067 tstate = PyEval_SaveThread();
2076 PyEval_RestoreThread(tstate);
2083 PyThreadState *tstate;
2086 #elif defined(PYPY_VERSION) 2088 PyGILState_STATE state;
2095 PyThreadState *state;
2109 m_type.release().dec_ref();
2110 m_value.release().dec_ref();
2111 m_trace.release().dec_ref();
2126 if (cache.find(
key) != cache.end())
2129 function override =
getattr(
self, name,
function());
2130 if (
override.is_cpp_function()) {
2137 #if !defined(PYPY_VERSION) 2138 PyFrameObject *frame = PyThreadState_Get()->frame;
2139 if (frame && (std::string)
str(frame->f_code->co_name) == name &&
2140 frame->f_code->co_argcount > 0) {
2141 PyFrame_FastToLocals(frame);
2142 PyObject *self_caller = PyDict_GetItem(
2143 frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
2144 if (self_caller ==
self.
ptr())
2152 PyObject *
result = PyRun_String(
2154 "frame = inspect.currentframe()\n" 2155 "if frame is not None:\n" 2156 " frame = frame.f_back\n" 2157 " if frame is not None and str(frame.f_code.co_name) == name and " 2158 "frame.f_code.co_argcount > 0:\n" 2159 " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n" 2160 " if self_caller == self:\n" 2162 Py_file_input, d.
ptr(), d.
ptr());
2163 if (result ==
nullptr)
2165 if (d[
"self"].is_none())
2187 #define PYBIND11_OVERRIDE_IMPL(ret_type, cname, name, ...) \ 2189 pybind11::gil_scoped_acquire gil; \ 2190 pybind11::function override = pybind11::get_override(static_cast<const cname *>(this), name); \ 2192 auto o = override(__VA_ARGS__); \ 2193 if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \ 2194 static pybind11::detail::override_caster_t<ret_type> caster; \ 2195 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \ 2197 else return pybind11::detail::cast_safe<ret_type>(std::move(o)); \ 2218 #define PYBIND11_OVERRIDE_NAME(ret_type, cname, name, fn, ...) \ 2220 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \ 2221 return cname::fn(__VA_ARGS__); \ 2228 #define PYBIND11_OVERRIDE_PURE_NAME(ret_type, cname, name, fn, ...) \ 2230 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__); \ 2231 pybind11::pybind11_fail("Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\""); \ 2258 #define PYBIND11_OVERRIDE(ret_type, cname, fn, ...) \ 2259 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__) 2265 #define PYBIND11_OVERRIDE_PURE(ret_type, cname, fn, ...) \ 2266 PYBIND11_OVERRIDE_PURE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__) 2281 #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) \ 2282 PYBIND11_OVERRIDE_IMPL(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__) 2283 #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \ 2284 PYBIND11_OVERRIDE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__) 2285 #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \ 2286 PYBIND11_OVERRIDE_PURE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, fn, __VA_ARGS__); 2287 #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \ 2288 PYBIND11_OVERRIDE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__) 2289 #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \ 2290 PYBIND11_OVERRIDE_PURE(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), fn, __VA_ARGS__); 2294 #if defined(_MSC_VER) && !defined(__INTEL_COMPILER) 2295 # pragma warning(pop) 2296 #elif defined(__GNUG__) && !defined(__clang__) 2297 # pragma GCC diagnostic pop class_ & def_buffer(Func &&func)
handle scope
Python handle to the parent scope (a class or a module)
typename std::conditional< B, T, F >::type conditional_t
void call_operator_delete(T *p, size_t, size_t)
Call class-specific delete if it exists or global otherwise. Can also be an overload set...
detail::exactly_one_t< is_holder, std::unique_ptr< type >, options... > holder_type
detail::exactly_one_t< is_subtype, void, options... > type_alias
#define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior)
class_ & def_buffer(Return(Class::*func)(Args...))
class_ & def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
void(* init_instance)(instance *, const void *)
Function pointer to class_<..>::init_instance.
size_t type_align
What is the alignment of the underlying C++ type?
~error_already_set() override
Annotation for parent scope.
#define PYBIND11_INSTANCE_METHOD_GET_FUNCTION
std::uint16_t nargs
Number of arguments (including py::args and/or py::kwargs, if present)
constexpr int last(int, int result)
class_ & def_property_readonly(const char *name, const cpp_function &fget, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
std::forward_list< void(*)(std::exception_ptr)> registered_exception_translators
static void init_holder_from_existing(const detail::value_and_holder &v_h, const holder_type *holder_ptr, std::true_type)
exception< CppException > & get_exception_object()
static handle handle_of()
bool hasattr(handle obj, handle name)
auto method_adaptor(F &&f) -> decltype(std::forward< F >(f))
void initialize(const type_record &rec)
detail::type_info * get_global_type_info(const std::type_index &tp)
module_ def_submodule(const char *name, const char *doc=nullptr)
std::vector< handle > args
Arguments passed to the function:
Q id(Eigen::AngleAxisd(0, Q_z_axis))
class_ & def_property_readonly_static(const char *name, const Getter &fget, const Extra &...extra)
Uses return_value_policy::reference by default.
static void init_holder(detail::instance *inst, detail::value_and_holder &v_h, const holder_type *, const std::enable_shared_from_this< T > *)
Initialize holder object, variant 1: object derives from enable_shared_from_this. ...
int RealScalar int RealScalar int RealScalar * pc
PyObject * ptr() const
Return the underlying PyObject * pointer.
static PyObject * dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in)
Main dispatch logic for calls to functions bound using pybind11.
type_map< type_info * > & registered_local_types_cpp()
Works like internals.registered_types_cpp, but for module-local registered types: ...
cpp_function(Return(Class::*f)(Arg...) const, const Extra &...extra)
Construct a cpp_function from a class method (const, no ref-qualifier)
Annotation for documentation.
#define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN)
cpp_function(Return(Class::*f)(Arg...), const Extra &...extra)
Construct a cpp_function from a class method (non-const, no ref-qualifier)
PYBIND11_NOINLINE internals & get_internals()
Return a reference to the current internals data.
cpp_function(Return(Class::*f)(Arg...) const &, const Extra &...extra)
detail::is_strict_base_of< Type, T > is_subtype
std::pair< decltype(internals::registered_types_py)::iterator, bool > all_type_info_get_cache(PyTypeObject *type)
void *(* operator_new)(size_t)
The global operator new can be overridden with a class-specific variant.
type_map< type_info * > registered_types_cpp
Rot2 R(Rot2::fromAngle(0.1))
bool contains(T &&key) const
class_ & def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra &...extra)
enum_ & value(char const *name, Type value, const char *doc=nullptr)
Add an enumeration entry.
class_ & def(const char *name_, Func &&f, const Extra &...extra)
typename std::underlying_type< Type >::type Scalar
Wrapper for Python extension modules.
detail::type_info * get_local_type_info(const std::type_index &tp)
size_t type_size
How large is the underlying C++ type?
enum_(const handle &scope, const char *name, const Extra &...extra)
#define PYBIND11_TRY_NEXT_OVERLOAD
static constexpr size_t size_in_ptrs(size_t s)
Helper class which loads arguments for C++ functions called from Python.
class_ & def_buffer(Return(Class::*func)(Args...) const)
static void add_base(detail::type_record &)
class_ & def_readwrite(const char *name, D C::*pm, const Extra &...extra)
static void postcall(function_call &call, handle fn_ret)
Binds C++ enumerations and enumeration classes to Python.
typename exactly_one< Predicate, Default, Ts... >::type exactly_one_t
module_ & def(const char *name_, Func &&f, const Extra &...extra)
Internal data associated with a single function call.
#define PYBIND11_NAMESPACE
The 'instance' type which needs to be standard layout (need to be able to use 'offsetof') ...
op_id
Enumeration with all supported operator types.
function get_override(const T *this_ptr, const char *name)
class_ & def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra &...extra)
Uses return_value_policy::reference by default.
PYBIND11_NOINLINE void clean_type_id(std::string &name)
iterator make_iterator(Iterator first, Sentinel last, Extra &&...extra)
Makes a python iterator from a first and past-the-end C++ InputIterator.
enum_base(handle base, handle parent)
void g(const string &key, int i)
constexpr size_t constexpr_sum()
Compile-time integer sum.
cpp_function(Func &&f, const Extra &...extra)
Construct a cpp_function from a lambda function (possibly with internal state)
PYBIND11_NOINLINE void value(char const *name_, object value, const char *doc=nullptr)
const char * c_str(Args &&...args)
class_ & def_property(const char *name, const Getter &fget, const Setter &fset, const Extra &...extra)
Uses return_value_policy::reference_internal by default.
PyExc_RuntimeError[[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
class_ & def_readwrite_static(const char *name, D *pm, const Extra &...extra)
PyObject * make_new_python_type(const type_record &rec)
cout<< "Here is the matrix m:"<< endl<< m<< endl;Matrix< ptrdiff_t, 3, 1 > res
const handle & inc_ref() const &
static void init_holder_from_existing(const detail::value_and_holder &v_h, const holder_type *holder_ptr, std::false_type)
void add_patient(PyObject *nurse, PyObject *patient)
bool has_kwargs
True if the function has a '**kwargs' argument.
PYBIND11_NOINLINE handle get_object_handle(const void *ptr, const detail::type_info *type)
bool convert
True if the argument is allowed to convert when loading.
cpp_function(Return(*f)(Args...), const Extra &...extra)
Construct a cpp_function from a vanilla function pointer.
const char * name
Argument name.
handle scope
Handle to the parent scope.
value_and_holder get_value_and_holder(const type_info *find_type=nullptr, bool throw_if_missing=true)
PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible)
static void add_base(detail::type_record &rec)
constexpr int first(int i)
Implementation details for constexpr functions.
class_ & def_readonly(const char *name, const D C::*pm, const Extra &...extra)
PYBIND11_NOINLINE void add_object(const char *name, handle obj, bool overwrite=false)
void initialize(Func &&f, Return(*)(Args...), const Extra &...extra)
Special internal constructor for functors, lambda functions, etc.
handle(* impl)(function_call &)
Pointer to lambda function which converts arguments and performs the actual call. ...
detail::initimpl::pickle_factory< GetState, SetState > pickle(GetState &&g, SetState &&s)
exception< CppException > & register_exception(handle scope, const char *name, handle base=PyExc_Exception)
std::uint16_t nargs_pos_only
Number of leading arguments (counted in nargs) that are positional-only.
const char * name
Name of the class.
#define PYBIND11_DESCR_CONSTEXPR
#define PYBIND11_INSTANCE_METHOD_CHECK
object name() const
Return the function name.
void def_property_static_impl(const char *name, handle fget, handle fset, detail::function_record *rec_func)
static void init_instance(detail::instance *inst, const void *holder_ptr)
std::vector< bool > args_convert
The convert value the arguments should be loaded with.
const std::vector< detail::type_info * > & all_type_info(PyTypeObject *type)
std::unordered_set< std::pair< const PyObject *, const char * >, override_hash > inactive_override_cache
PYBIND11_NOINLINE void export_values()
type_map< std::vector< bool(*)(PyObject *, void *&)> > direct_conversions
std::uint16_t nargs_kw_only
Number of trailing arguments (counted in nargs) that are keyword-only.
class_ & def(detail::initimpl::factory< Args... > &&init, const Extra &...extra)
static void precall(function_call &call)
EIGEN_DEVICE_FUNC NewType cast(const OldType &x)
#define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun)
static detail::function_record * get_function_record(handle h)
detail::is_holder_type< Type, T > is_holder
Point2(* f)(const Point3 &, OptionalJacobian< 2, 3 >)
bool is_method
True if this is a method.
static return_value_policy policy(return_value_policy p)
bool is_constructor
True if name == 'init'.
class_(handle scope, const char *name, const Extra &...extra)
Array< double, 1, 3 > e(1./3., 0.5, 2.)
#define PYBIND11_DEPRECATED(reason)
typename std::remove_reference< T >::type remove_reference_t
bool module_local
Is the class definition local to the module shared object?
function get_type_override(const void *this_ptr, const type_info *this_type, const char *name)
static bool show_function_signatures()
typename void_t_impl< Ts... >::type void_t
const handle & dec_ref() const &
#define PYBIND11_TLS_DELETE_VALUE(key)
void reload()
Reload the module or throws error_already_set.
void mark_parents_nonsimple(PyTypeObject *value)
Helper function which tags all parents of a type using mult. inheritance.
Helper type to replace 'void' in some expressions.
class_ & def_property_readonly_static(const char *name, const cpp_function &fget, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name)
handle get_function(handle value)
#define PYBIND11_ENUM_OP_CONV(op, expr)
Matrix< Scalar, Dynamic, Dynamic > C
void add_class_method(object &cls, const char *name_, const cpp_function &cf)
void initialize_generic(detail::function_record *rec, const char *text, const std::type_info *const *types, size_t args)
Register a function call with Python (generic non-templated code goes here)
#define PYBIND11_MODULE_LOCAL_ID
bool none
True if None is allowed when loading.
class_ & def_cast(const detail::op_< id, ot, L, R > &op, const Extra &...extra)
static void init(const Args &...args, function_record *r)
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const ArgReturnType arg() const
void register_exception_translator(ExceptionTranslator &&translator)
function_record * next
Pointer to next overload.
void(* dealloc)(detail::value_and_holder &)
Function pointer to class_<..>::dealloc.
enum_ & export_values()
Export enumeration entries into the parent scope.
static void init_holder(detail::instance *inst, detail::value_and_holder &v_h, const holder_type *holder_ptr, const void *)
Initialize holder object, variant 2: try to construct from existing holder object, if possible.
void set_operator_new(type_record *r)
Set the pointer to operator new if it exists. The cast is needed because it can be overloaded...
std::is_base_of< pyobject_tag, remove_reference_t< T >> is_pyobject
size_t holder_size
How large is the type's holder?
typename exactly_one_t< is_call_guard, call_guard<>, Extra... >::type extract_guard_t
Extract the type from the first call_guard in Extras... (or void_type if none found) ...
Special data structure which (temporarily) holds metadata about a bound class.
static module_ import(const char *name)
Import and return a module or throws error_already_set.
PYBIND11_NOINLINE detail::type_info * get_type_info(PyTypeObject *type)
iterator make_key_iterator(Iterator first, Sentinel last, Extra &&...extra)
bool default_holder
Is the default (unique_ptr) holder type used?
object getattr(handle obj, handle name)
#define PYBIND11_TLS_REPLACE_VALUE(key, value)
RAII wrapper that temporarily clears any Python error state.
std::is_same< bools< Ts::value..., true >, bools< true, Ts::value... >> all_of
detail::is_strict_base_of< T, Type > is_base
PYBIND11_NOINLINE detail::function_record * make_function_record()
Space optimization: don't inline this frequently instantiated fragment.
class_ & def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
detail::initimpl::constructor< Args... > init()
Binds an existing constructor taking arguments Args...
PYBIND11_NOINLINE void print(tuple args, dict kwargs)
static void dealloc(detail::value_and_holder &v_h)
Deallocates an instance; via holder, if constructed; otherwise via operator delete.
std::vector< argument_record > args
List of registered keyword arguments.
const std::type_info * type
class_ & def(const detail::initimpl::constructor< Args... > &init, const Extra &...extra)
Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object.
class_ & def_static(const char *name_, Func &&f, const Extra &...extra)
void implicitly_convertible()
char * name
Function name.
bool has_args
True if the function has a '*args' argument.
bool is_operator
True if this is an operator (add), etc.
class_ & def(detail::initimpl::pickle_factory< Args... > &&pf, const Extra &...extra)
static bool show_user_defined_docstrings()
static PYBIND11_NOINLINE void * local_load(PyObject *src, const type_info *ti)
#define PYBIND11_ENUM_OP_CONV_LHS(op, expr)
#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_)
Include Python header, disable linking to pythonX_d.lib on Windows in debug mode. ...
bool is_new_style_constructor
True if this is a new-style __init__ defined in detail/init.h
Annotation for function names.
const char * name
If non-null, this is a named kwargs argument.
Annotation indicating that a class derives from another given type.
Information record describing a Python buffer object.
#define PYBIND11_TLS_GET_VALUE(key)
function get_overload(const T *this_ptr, const char *name)
void load(Archive &ar, Eigen::Matrix< Scalar_, Rows_, Cols_, Ops_, MaxRows_, MaxCols_ > &m, const unsigned int)
handle init_self
If this is a call to an initializer, this argument contains self
static void destruct(detail::function_record *rec)
When a cpp_function is GCed, release any memory allocated by pybind11.
cpp_function(Return(Class::*f)(Arg...)&, const Extra &...extra)
PyThreadState * get_thread_state_unchecked()
std::unordered_map< PyTypeObject *, std::vector< type_info * > > registered_types_py
bool equal(const T &obj1, const T &obj2, double tol)
void register_instance(instance *self, void *valptr, const type_info *tinfo)
class_ & def_property_readonly(const char *name, const Getter &fget, const Extra &...extra)
Uses return_value_policy::reference_internal by default.
void setattr(handle obj, handle name, handle value)
Annotation indicating that a function is an overload associated with a given "sibling".
#define PYBIND11_NOINLINE
detail::initimpl::alias_constructor< Args... > init_alias()
exception(handle scope, const char *name, handle base=PyExc_Exception)
Values initialize(const NonlinearFactorGraph &graph, bool useOdometricPath)
class_ & def(const detail::initimpl::alias_constructor< Args... > &init, const Extra &...extra)
class_ & def(const detail::op_< id, ot, L, R > &op, const Extra &...extra)
Internal data structure which holds metadata about a bound function (signature, overloads, etc.)
return_value_policy
Approach used to cast a previously unknown C++ instance into a Python object.
class_ & def_readonly_static(const char *name, const D *pm, const Extra &...extra)
void operator()(const char *message)
Internal data structure which holds metadata about a keyword argument.
void keep_alive_impl(handle nurse, handle patient)
#define PYBIND11_NAMESPACE_END(name)
#define PYBIND11_OBJECT(Name, Parent, CheckFun)
cpp_function(std::nullptr_t)
negation< all_of< negation< Ts >... >> any_of
#define PYBIND11_NAMESPACE_BEGIN(name)
void install_buffer_funcs(buffer_info *(*get_buffer)(PyObject *, void *), void *get_buffer_data)