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__) 55 class cpp_function :
public function {
62 template <
typename Return,
typename... Args,
typename... Extra>
64 initialize(f, f, extra...);
68 template <
typename Func,
typename... Extra,
71 initialize(std::forward<Func>(f),
76 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
78 initialize([f](Class *c, Arg...
args) -> Return { return (c->*f)(args...); },
79 (Return (*) (Class *, Arg...))
nullptr, extra...);
83 template <
typename Return,
typename Class,
typename... Arg,
typename... Extra>
84 cpp_function(Return (Class::*f)(Arg...)
const,
const Extra&... extra) {
85 initialize([f](
const Class *c, Arg...
args) -> Return { return (c->*f)(args...); },
86 (Return (*)(
const Class *, Arg ...))
nullptr, extra...);
90 object name()
const {
return attr(
"__name__"); }
99 template <
typename Func,
typename Return,
typename... Args,
typename... Extra>
100 void initialize(Func &&f, Return (*)(Args...),
const Extra&... extra) {
101 using namespace detail;
102 struct capture { remove_reference_t<Func> f; };
105 auto rec = make_function_record();
108 if (
sizeof(
capture) <=
sizeof(rec->data)) {
112 #if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6 113 # pragma GCC diagnostic push 114 # pragma GCC diagnostic ignored "-Wplacement-new" 117 #if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6 118 # pragma GCC diagnostic pop 121 rec->free_data = [](function_record *r) { ((
capture *) &r->data)->~capture(); };
123 rec->data[0] =
new capture { std::forward<Func>(f) };
124 rec->free_data = [](function_record *r) {
delete ((
capture *) r->data[0]); };
128 using cast_in = argument_loader<Args...>;
133 static_assert(expected_num_args<Extra...>(
sizeof...(Args), cast_in::has_args, cast_in::has_kwargs),
134 "The number of argument annotations does not match the number of function arguments");
137 rec->impl = [](function_call &
call) ->
handle {
138 cast_in args_converter;
141 if (!args_converter.load_args(
call))
145 process_attributes<Extra...>::precall(
call);
163 process_attributes<Extra...>::postcall(
call, result);
172 static constexpr
auto signature =
_(
"(") + cast_in::arg_names +
_(
") -> ") + cast_out::name;
176 initialize_generic(rec, signature.text, types.data(),
sizeof...(Args));
178 if (cast_in::has_args) rec->has_args =
true;
179 if (cast_in::has_kwargs) rec->has_kwargs =
true;
182 using FunctionType = Return (*)(Args...);
183 constexpr
bool is_function_ptr =
185 sizeof(
capture) ==
sizeof(
void *);
186 if (is_function_ptr) {
187 rec->is_stateless =
true;
188 rec->data[1] =
const_cast<void *
>(
reinterpret_cast<const void *
>(&
typeid(FunctionType)));
194 const std::type_info *
const *types,
size_t args) {
198 if (rec->
doc) rec->
doc = strdup(rec->
doc);
199 for (
auto &a: rec->
args) {
201 a.name = strdup(a.name);
203 a.descr = strdup(a.descr);
205 a.descr = strdup(a.value.attr(
"__repr__")().cast<std::string>().c_str());
210 #if !defined(NDEBUG) && !defined(PYBIND11_DISABLE_NEW_STYLE_INIT_WARNING) 212 const auto class_name = std::string(((PyTypeObject *) rec->
scope.
ptr())->tp_name);
213 const auto func_name = std::string(rec->
name);
216 (
"pybind11-bound class '" + class_name +
"' is using an old-style " 217 "placement-new '" + func_name +
"' which has been deprecated. See " 218 "the upgrade guide in pybind11's docs. This message is only visible " 219 "when compiled in debug mode.").
c_str(), 0
225 std::string signature;
226 size_t type_index = 0, arg_index = 0;
227 for (
auto *pc = text; *pc !=
'\0'; ++pc) {
232 if (*(pc + 1) ==
'*')
235 if (arg_index < rec->args.size() && rec->
args[arg_index].name) {
236 signature += rec->
args[arg_index].name;
237 }
else if (arg_index == 0 && rec->
is_method) {
243 }
else if (c ==
'}') {
245 if (arg_index < rec->args.size() && rec->
args[arg_index].descr) {
247 signature += rec->
args[arg_index].descr;
250 }
else if (c ==
'%') {
251 const std::type_info *t = types[type_index++];
253 pybind11_fail(
"Internal error while parsing type signature (1)");
254 if (
auto tinfo = detail::get_type_info(*t)) {
257 th.
attr(
"__module__").cast<std::string>() +
"." +
258 th.
attr(
"__qualname__").cast<std::string>();
263 rec->
scope.
attr(
"__module__").cast<std::string>() +
"." +
264 rec->
scope.
attr(
"__qualname__").cast<std::string>();
266 std::string tname(t->name());
267 detail::clean_type_id(tname);
274 if (arg_index != args || types[type_index] !=
nullptr)
275 pybind11_fail(
"Internal error while parsing type signature (2)");
277 #if PY_MAJOR_VERSION < 3 278 if (strcmp(rec->
name,
"__next__") == 0) {
279 std::free(rec->
name);
280 rec->
name = strdup(
"next");
281 }
else if (strcmp(rec->
name,
"__bool__") == 0) {
282 std::free(rec->
name);
283 rec->
name = strdup(
"__nonzero__");
286 rec->
signature = strdup(signature.c_str());
287 rec->
args.shrink_to_fit();
288 rec->
nargs = (std::uint16_t) args;
296 auto rec_capsule = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(rec->
sibling.
ptr()));
300 if (!chain->scope.is(rec->
scope))
305 pybind11_fail(
"Cannot overload existing non-function object \"" + std::string(rec->
name) +
306 "\" with a function of the same name");
311 rec->
def =
new PyMethodDef();
312 std::memset(rec->
def, 0,
sizeof(PyMethodDef));
314 rec->
def->ml_meth =
reinterpret_cast<PyCFunction
>(
reinterpret_cast<void (*) (
void)
>(*dispatcher));
315 rec->
def->ml_flags = METH_VARARGS | METH_KEYWORDS;
317 capsule rec_capsule(rec, [](
void *ptr) {
324 scope_module = rec->
scope.
attr(
"__module__");
326 scope_module = rec->
scope.
attr(
"__name__");
330 m_ptr = PyCFunction_NewEx(rec->
def, rec_capsule.ptr(), scope_module.ptr());
332 pybind11_fail(
"cpp_function::cpp_function(): Could not allocate function object");
339 pybind11_fail(
"overloading a method with both static and instance methods is not supported; " 341 "compile in debug mode for more details" 343 "error while attempting to bind " + std::string(rec->
is_method ?
"instance" :
"static") +
" method " +
352 std::string signatures;
356 if (chain && options::show_function_signatures()) {
358 signatures += rec->
name;
359 signatures +=
"(*args, **kwargs)\n";
360 signatures +=
"Overloaded function.\n\n";
363 bool first_user_def =
true;
364 for (
auto it = chain_start; it !=
nullptr; it = it->next) {
365 if (options::show_function_signatures()) {
366 if (index > 0) signatures +=
"\n";
369 signatures += rec->
name;
370 signatures += it->signature;
373 if (it->doc && strlen(it->doc) > 0 && options::show_user_defined_docstrings()) {
376 if (!options::show_function_signatures()) {
377 if (first_user_def) first_user_def =
false;
378 else signatures +=
"\n";
380 if (options::show_function_signatures()) signatures +=
"\n";
381 signatures += it->doc;
382 if (options::show_function_signatures()) signatures +=
"\n";
387 PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
388 if (func->m_ml->ml_doc)
389 std::free(const_cast<char *>(func->m_ml->ml_doc));
390 func->m_ml->ml_doc = strdup(signatures.c_str());
395 pybind11_fail(
"cpp_function::cpp_function(): Could not allocate instance method object");
406 std::free((
char *) rec->
name);
407 std::free((
char *) rec->
doc);
410 std::free(const_cast<char *>(
arg.
name));
411 std::free(const_cast<char *>(
arg.descr));
415 std::free(const_cast<char *>(rec->
def->ml_doc));
424 static PyObject *
dispatcher(PyObject *
self, PyObject *args_in, PyObject *kwargs_in) {
425 using namespace detail;
428 const function_record *overloads = (function_record *) PyCapsule_GetPointer(
self,
nullptr),
432 const size_t n_args_in = (
size_t) PyTuple_GET_SIZE(args_in);
434 handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) :
nullptr,
437 auto self_value_and_holder = value_and_holder();
438 if (overloads->is_constructor) {
439 const auto tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
440 const auto pi =
reinterpret_cast<instance *
>(parent.
ptr());
441 self_value_and_holder = pi->get_value_and_holder(
tinfo,
false);
443 if (!self_value_and_holder.type || !self_value_and_holder.inst) {
444 PyErr_SetString(PyExc_TypeError,
"__init__(self, ...) called with invalid `self` argument");
450 if (self_value_and_holder.instance_registered())
459 std::vector<function_call> second_pass;
462 const bool overloaded = it !=
nullptr && it->next !=
nullptr;
464 for (; it !=
nullptr; it = it->next) {
485 const function_record &func = *it;
486 size_t pos_args = func.nargs;
487 if (func.has_args) --pos_args;
488 if (func.has_kwargs) --pos_args;
490 if (!func.has_args && n_args_in > pos_args)
493 if (n_args_in < pos_args && func.args.size() < pos_args)
496 function_call
call(func, parent);
498 size_t args_to_copy = (std::min)(pos_args, n_args_in);
499 size_t args_copied = 0;
502 if (func.is_new_style_constructor) {
505 if (self_value_and_holder)
506 self_value_and_holder.type->dealloc(self_value_and_holder);
508 call.init_self = PyTuple_GET_ITEM(args_in, 0);
509 call.args.push_back(reinterpret_cast<PyObject *>(&self_value_and_holder));
510 call.args_convert.push_back(
false);
515 bool bad_arg =
false;
516 for (; args_copied < args_to_copy; ++args_copied) {
517 const argument_record *arg_rec = args_copied < func.args.size() ? &func.args[args_copied] :
nullptr;
518 if (kwargs_in && arg_rec && arg_rec->name && PyDict_GetItemString(kwargs_in, arg_rec->name)) {
523 handle arg(PyTuple_GET_ITEM(args_in, args_copied));
524 if (arg_rec && !arg_rec->none && arg.
is_none()) {
528 call.args.push_back(arg);
529 call.args_convert.push_back(arg_rec ? arg_rec->convert :
true);
535 dict kwargs = reinterpret_borrow<dict>(kwargs_in);
538 if (args_copied < pos_args) {
539 bool copied_kwargs =
false;
541 for (; args_copied < pos_args; ++args_copied) {
542 const auto &
arg = func.args[args_copied];
546 value = PyDict_GetItemString(kwargs.
ptr(),
arg.
name);
550 if (!copied_kwargs) {
551 kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.
ptr()));
552 copied_kwargs =
true;
555 }
else if (
arg.value) {
560 call.args.push_back(value);
561 call.args_convert.push_back(
arg.convert);
567 if (args_copied < pos_args)
572 if (kwargs && kwargs.
size() > 0 && !func.has_kwargs)
578 if (args_to_copy == 0) {
581 extra_args = reinterpret_borrow<tuple>(args_in);
582 }
else if (args_copied >= n_args_in) {
583 extra_args =
tuple(0);
585 size_t args_size = n_args_in - args_copied;
586 extra_args =
tuple(args_size);
587 for (
size_t i = 0;
i < args_size; ++
i) {
588 extra_args[
i] = PyTuple_GET_ITEM(args_in, args_copied +
i);
591 call.args.push_back(extra_args);
592 call.args_convert.push_back(
false);
597 if (func.has_kwargs) {
600 call.args.push_back(kwargs);
601 call.args_convert.push_back(
false);
608 if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs)
609 pybind11_fail(
"Internal error: function call dispatcher inserted wrong number of arguments!");
612 std::vector<bool> second_pass_convert;
617 second_pass_convert.resize(func.nargs,
false);
618 call.args_convert.swap(second_pass_convert);
623 loader_life_support guard{};
624 result = func.impl(call);
636 for (
size_t i = func.is_method ? 1 : 0;
i < pos_args;
i++) {
637 if (second_pass_convert[
i]) {
640 call.args_convert.swap(second_pass_convert);
650 for (
auto &
call : second_pass) {
652 loader_life_support guard{};
670 #if defined(__GNUG__) && !defined(__clang__) 671 }
catch ( abi::__forced_unwind& ) {
686 auto last_exception = std::current_exception();
687 auto ®istered_exception_translators = get_internals().registered_exception_translators;
688 for (
auto& translator : registered_exception_translators) {
690 translator(last_exception);
692 last_exception = std::current_exception();
697 PyErr_SetString(PyExc_SystemError,
"Exception escaped from default exception translator!");
701 auto append_note_if_missing_header_is_suspected = [](std::string &
msg) {
702 if (
msg.find(
"std::") != std::string::npos) {
704 "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n" 705 "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n" 706 "conversions are optional and require extra headers to be included\n" 707 "when compiling your pybind11 module.";
712 if (overloads->is_operator)
713 return handle(Py_NotImplemented).inc_ref().ptr();
715 std::string
msg = std::string(overloads->name) +
"(): incompatible " +
716 std::string(overloads->is_constructor ?
"constructor" :
"function") +
717 " arguments. The following argument types are supported:\n";
720 for (
const function_record *it2 = overloads; it2 !=
nullptr; it2 = it2->next) {
723 bool wrote_sig =
false;
724 if (overloads->is_constructor) {
726 std::string sig = it2->signature;
727 size_t start = sig.find(
'(') + 7;
728 if (start < sig.size()) {
730 size_t end = sig.find(
", "), next = end + 2;
731 size_t ret = sig.rfind(
" -> ");
733 if (end >= sig.size()) next = end = sig.find(
')');
734 if (start < end && next < sig.size()) {
735 msg.append(sig, start, end - start);
737 msg.append(sig, next, ret - next);
742 if (!wrote_sig) msg += it2->signature;
746 msg +=
"\nInvoked with: ";
747 auto args_ = reinterpret_borrow<tuple>(args_in);
748 bool some_args =
false;
749 for (
size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
750 if (!some_args) some_args =
true;
755 auto kwargs = reinterpret_borrow<dict>(kwargs_in);
757 if (some_args) msg +=
"; ";
760 for (
auto kwarg :
kwargs) {
761 if (first) first =
false;
763 msg +=
pybind11::str(
"{}={!r}").format(kwarg.first, kwarg.second);
768 append_note_if_missing_header_is_suspected(msg);
769 PyErr_SetString(PyExc_TypeError, msg.c_str());
771 }
else if (!result) {
772 std::string
msg =
"Unable to convert function return value to a " 773 "Python type! The signature was\n\t";
774 msg += it->signature;
775 append_note_if_missing_header_is_suspected(msg);
776 PyErr_SetString(PyExc_TypeError, msg.c_str());
779 if (overloads->is_constructor && !self_value_and_holder.holder_constructed()) {
780 auto *pi =
reinterpret_cast<instance *
>(parent.
ptr());
781 self_value_and_holder.type->init_instance(pi,
nullptr);
794 explicit module(
const char *
name,
const char *
doc =
nullptr) {
795 if (!options::show_user_defined_docstrings())
doc =
nullptr;
796 #if PY_MAJOR_VERSION >= 3 797 PyModuleDef *def =
new PyModuleDef();
798 std::memset(def, 0,
sizeof(PyModuleDef));
803 m_ptr = PyModule_Create(def);
805 m_ptr = Py_InitModule3(name,
nullptr,
doc);
807 if (m_ptr ==
nullptr)
808 pybind11_fail(
"Internal error in module::module()");
817 template <
typename Func,
typename... Extra>
818 module &def(
const char *name_, Func &&f,
const Extra& ... extra) {
823 add_object(name_, func,
true );
837 module def_submodule(
const char *
name,
const char *
doc =
nullptr) {
838 std::string full_name = std::string(PyModule_GetName(m_ptr))
839 + std::string(
".") + std::string(name);
840 auto result = reinterpret_borrow<module>(PyImport_AddModule(full_name.c_str()));
841 if (
doc && options::show_user_defined_docstrings())
848 static module import(
const char *name) {
849 PyObject *obj = PyImport_ImportModule(name);
852 return reinterpret_steal<module>(obj);
857 PyObject *obj = PyImport_ReloadModule(ptr());
860 *
this = reinterpret_steal<module>(obj);
869 if (!overwrite &&
hasattr(*
this, name))
870 pybind11_fail(
"Error during initialization: multiple incompatible definitions with name \"" +
871 std::string(name) +
"\"");
873 PyModule_AddObject(ptr(), name, obj.
inc_ref().
ptr() );
881 PyObject *p = PyEval_GetGlobals();
882 return reinterpret_borrow<dict>(p ? p : module::import(
"__main__").attr(
"__dict__").ptr());
888 template <
typename...>
friend class class_;
894 pybind11_fail(
"generic_type: cannot initialize type \"" + std::string(rec.
name) +
895 "\": an object with that name is already defined");
898 pybind11_fail(
"generic_type: type \"" + std::string(rec.
name) +
899 "\" is already registered!");
905 tinfo->type = (PyTypeObject *) m_ptr;
913 tinfo->simple_type =
true;
914 tinfo->simple_ancestors =
true;
919 auto tindex = std::type_index(*rec.
type);
928 mark_parents_nonsimple(
tinfo->type);
929 tinfo->simple_ancestors =
false;
931 else if (rec.
bases.size() == 1) {
932 auto parent_tinfo = get_type_info((PyTypeObject *) rec.
bases[0].
ptr());
933 tinfo->simple_ancestors = parent_tinfo->simple_ancestors;
938 tinfo->module_local_load = &type_caster_generic::local_load;
944 void mark_parents_nonsimple(PyTypeObject *
value) {
945 auto t = reinterpret_borrow<tuple>(value->tp_bases);
947 auto tinfo2 = get_type_info((PyTypeObject *) h.ptr());
949 tinfo2->simple_type =
false;
950 mark_parents_nonsimple((PyTypeObject *) h.ptr());
954 void install_buffer_funcs(
956 void *get_buffer_data) {
957 PyHeapTypeObject *
type = (PyHeapTypeObject*) m_ptr;
958 auto tinfo = detail::get_type_info(&type->ht_type);
960 if (!type->ht_type.tp_as_buffer)
962 "To be able to register buffer protocol support for the type '" +
963 std::string(
tinfo->type->tp_name) +
964 "' the associated class<>(..) invocation must " 965 "include the pybind11::buffer_protocol() annotation!");
967 tinfo->get_buffer = get_buffer;
968 tinfo->get_buffer_data = get_buffer_data;
972 void def_property_static_impl(
const char *
name,
975 const auto is_static = rec_func && !(rec_func->
is_method && rec_func->
scope);
977 auto property =
handle((PyObject *) (is_static ? get_internals().static_property_type
978 : &PyProperty_Type));
979 attr(name) = property(fget.
ptr() ? fget :
none(),
987 template <
typename T,
typename =
void_t<decltype(static_cast<
void *(*)(
size_t)>(T::operator new))>>
994 : std::true_type { };
997 : std::true_type { };
1006 #if defined(PYBIND11_CPP17) 1007 if (a > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
1008 ::operator
delete(p, s, std::align_val_t(a));
1010 ::operator
delete(p, s);
1012 ::operator
delete(p);
1018 template <
typename ,
typename F>
1021 auto method_adaptor(F &&f) -> decltype(std::forward<F>(f)) {
return std::forward<F>(f); }
1023 template <
typename Derived,
typename Return,
typename Class,
typename... Args>
1026 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1030 template <
typename Derived,
typename Return,
typename Class,
typename... Args>
1031 auto method_adaptor(Return (Class::*pmf)(Args...)
const) -> Return (Derived::*)(Args...)
const {
1033 "Cannot bind an inaccessible base class method; use a lambda definition instead");
1037 template <
typename type_,
typename...
options>
1053 "Unknown/invalid class_ template parameters provided");
1056 "Cannot use an alias class with a non-polymorphic type");
1060 template <
typename... Extra>
1062 using namespace detail;
1069 none_of<std::is_same<multiple_inheritance, Extra>...>::
value),
1070 "Error: multiple inheritance bases must be specified via class_ template options");
1073 record.scope =
scope;
1075 record.type = &
typeid(
type);
1076 record.type_size =
sizeof(conditional_t<has_alias, type_alias, type>);
1077 record.type_align =
alignof(conditional_t<has_alias, type_alias, type>&);
1079 record.init_instance = init_instance;
1080 record.dealloc = dealloc;
1083 set_operator_new<type>(&record);
1091 generic_type::initialize(record);
1095 instances[std::type_index(
typeid(
type_alias))] = instances[std::type_index(
typeid(
type))];
1101 rec.add_base(
typeid(
Base), [](
void *src) ->
void * {
1102 return static_cast<Base *
>(
reinterpret_cast<type *
>(src));
1109 template <
typename Func,
typename... Extra>
1110 class_ &
def(
const char *name_, Func&& f,
const Extra&... extra) {
1113 attr(cf.name()) = cf;
1117 template <
typename Func,
typename... Extra>
class_ &
1120 "def_static(...) called with a non-static member function pointer");
1139 template <
typename... Args,
typename... Extra>
1141 init.
execute(*
this, extra...);
1145 template <
typename... Args,
typename... Extra>
1147 init.
execute(*
this, extra...);
1151 template <
typename... Args,
typename... Extra>
1157 template <
typename... Args,
typename... Extra>
1164 struct capture { Func func; };
1166 install_buffer_funcs([](PyObject *obj,
void *ptr) ->
buffer_info* {
1168 if (!caster.
load(obj,
false))
1175 template <
typename Return,
typename Class,
typename... Args>
1177 return def_buffer([func] (
type &obj) {
return (obj.*func)(); });
1180 template <
typename Return,
typename Class,
typename... Args>
1182 return def_buffer([func] (
const type &obj) {
return (obj.*func)(); });
1185 template <
typename C,
typename D,
typename... Extra>
1190 def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
1194 template <
typename C,
typename D,
typename... Extra>
1198 def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
1202 template <
typename D,
typename... Extra>
1206 def_property_static(name, fget, fset, return_value_policy::reference, extra...);
1210 template <
typename D,
typename... Extra>
1213 def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
1218 template <
typename Getter,
typename... Extra>
1220 return def_property_readonly(name,
cpp_function(method_adaptor<type>(fget)),
1221 return_value_policy::reference_internal, extra...);
1225 template <
typename... Extra>
1227 return def_property(name, fget,
nullptr, extra...);
1231 template <
typename Getter,
typename... Extra>
1233 return def_property_readonly_static(name,
cpp_function(fget), return_value_policy::reference, extra...);
1237 template <
typename... Extra>
1239 return def_property_static(name, fget,
nullptr, extra...);
1243 template <
typename Getter,
typename Setter,
typename... Extra>
1245 return def_property(name, fget,
cpp_function(method_adaptor<type>(fset)), extra...);
1247 template <
typename Getter,
typename... Extra>
1249 return def_property(name,
cpp_function(method_adaptor<type>(fget)), fset,
1250 return_value_policy::reference_internal, extra...);
1254 template <
typename... Extra>
1256 return def_property_static(name, fget, fset,
is_method(*
this), extra...);
1260 template <
typename Getter,
typename... Extra>
1262 return def_property_static(name,
cpp_function(fget), fset, return_value_policy::reference, extra...);
1266 template <
typename... Extra>
1269 "Argument annotations are not allowed for properties");
1270 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
1271 auto *rec_active = rec_fget;
1273 char *doc_prev = rec_fget->doc;
1275 if (rec_fget->doc && rec_fget->doc != doc_prev) {
1277 rec_fget->doc = strdup(rec_fget->doc);
1281 char *doc_prev = rec_fset->doc;
1283 if (rec_fset->doc && rec_fset->doc != doc_prev) {
1285 rec_fset->doc = strdup(rec_fset->doc);
1287 if (! rec_active) rec_active = rec_fset;
1289 def_property_static_impl(name, fget, fset, rec_active);
1295 template <
typename T>
1297 const holder_type * ,
const std::enable_shared_from_this<T> * ) {
1299 auto sh = std::dynamic_pointer_cast<
typename holder_type::element_type>(
1305 }
catch (
const std::bad_weak_ptr &) {}
1319 const holder_type *holder_ptr, std::false_type ) {
1327 init_holder_from_existing(v_h, holder_ptr, std::is_copy_constructible<holder_type>());
1341 if (!v_h.instance_registered()) {
1343 v_h.set_instance_registered();
1345 init_holder(inst, v_h, (
const holder_type *) holder_ptr, v_h.value_ptr<
type>());
1377 template <
typename Func,
typename Ret = detail::initimpl::factory<Func>>
1378 Ret
init(Func &&f) {
return {std::forward<Func>(f)}; }
1382 template <
typename CFunc,
typename AFunc,
typename Ret = detail::initimpl::factory<CFunc, AFunc>>
1384 return {std::forward<CFunc>(c), std::forward<AFunc>(a)};
1389 template <
typename GetState,
typename SetState>
1391 return {std::forward<GetState>(g), std::forward<SetState>(s)};
1399 m_base.attr(
"__entries") =
dict();
1400 auto property =
handle((PyObject *) &PyProperty_Type);
1401 auto static_property =
handle((PyObject *) get_internals().static_property_type);
1407 dict entries = type.
attr(
"__entries");
1408 for (
const auto &kv : entries) {
1409 object other = kv.second[
int_(0)];
1410 if (other.
equal(arg))
1420 for (
const auto &kv : entries) {
1429 [](
handle arg) -> std::string {
1430 std::string docstring;
1431 dict entries = arg.
attr(
"__entries");
1432 if (((PyTypeObject *) arg.
ptr())->tp_doc)
1433 docstring += std::string(((PyTypeObject *) arg.
ptr())->tp_doc) +
"\n\n";
1434 docstring +=
"Members:";
1435 for (
const auto &kv : entries) {
1437 auto comment = kv.second[
int_(1)];
1438 docstring +=
"\n\n " + key;
1439 if (!comment.is_none())
1446 m_base.attr(
"__members__") = static_property(
cpp_function(
1448 dict entries = arg.
attr(
"__entries"), m;
1449 for (
const auto &kv : entries)
1450 m[kv.first] = kv.second[
int_(0)];
1455 #define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior) \ 1456 m_base.attr(op) = cpp_function( \ 1457 [](object a, object b) { \ 1458 if (!a.get_type().is(b.get_type())) \ 1464 #define PYBIND11_ENUM_OP_CONV(op, expr) \ 1465 m_base.attr(op) = cpp_function( \ 1466 [](object a_, object b_) { \ 1467 int_ a(a_), b(b_); \ 1472 if (is_convertible) {
1476 if (is_arithmetic) {
1492 if (is_arithmetic) {
1493 #define PYBIND11_THROW throw type_error("Expected an enumeration of matching type!"); 1498 #undef PYBIND11_THROW 1502 #undef PYBIND11_ENUM_OP_CONV 1503 #undef PYBIND11_ENUM_OP_STRICT 1508 m_base.
attr(
"__getstate__") = getstate;
1509 m_base.
attr(
"__hash__") = getstate;
1513 dict entries = m_base.
attr(
"__entries");
1516 std::string type_name = (std::string)
str(m_base.attr(
"__name__"));
1517 throw value_error(type_name +
": element \"" + std::string(name_) +
"\" already exists!");
1520 entries[name] = std::make_pair(value,
doc);
1521 m_base.attr(name) =
value;
1525 dict entries = m_base.
attr(
"__entries");
1526 for (
const auto &kv : entries)
1527 m_parent.
attr(kv.first) = kv.second[
int_(0)];
1536 template <
typename Type>
class enum_ :
public class_<Type> {
1542 using Base::def_property_readonly;
1543 using Base::def_property_readonly_static;
1546 template <
typename... Extra>
1548 :
class_<Type>(scope, name, extra...), m_base(*this, scope) {
1551 m_base.init(is_arithmetic, is_convertible);
1553 def(
init([](
Scalar i) {
return static_cast<Type
>(
i); }));
1554 def(
"__int__", [](Type
value) {
return (
Scalar) value; });
1555 #if PY_MAJOR_VERSION < 3 1556 def(
"__long__", [](Type value) {
return (
Scalar) value; });
1559 [](Type &value,
Scalar arg) { value =
static_cast<Type
>(arg); },
1584 if (!nurse || !patient)
1585 pybind11_fail(
"Could not activate keep_alive!");
1587 if (patient.is_none() || nurse.is_none())
1591 if (!
tinfo.empty()) {
1603 weakref wr(nurse, disable_lifesupport);
1606 (void) wr.release();
1611 auto get_arg = [&](
size_t n) {
1616 else if (n <= call.
args.size())
1617 return call.
args[n - 1];
1625 auto res = get_internals().registered_types_py
1626 #ifdef __cpp_lib_unordered_map_try_emplace 1629 .emplace(type, std::vector<detail::type_info *>());
1635 get_internals().registered_types_py.erase(type);
1643 template <
typename Iterator,
typename Sentinel,
bool KeyIterator, return_value_policy Policy>
1656 typename ValueType = decltype(*std::declval<Iterator>()),
1661 if (!detail::get_type_info(
typeid(state),
false)) {
1663 .def(
"__iter__", [](state &s) -> state& {
return s; })
1664 .def(
"__next__", [](state &s) -> ValueType {
1665 if (!s.first_or_done)
1668 s.first_or_done =
false;
1669 if (s.it == s.end) {
1670 s.first_or_done =
true;
1674 }, std::forward<Extra>(extra)..., Policy);
1685 typename KeyType = decltype((*std::declval<Iterator>()).
first),
1690 if (!detail::get_type_info(
typeid(state),
false)) {
1692 .def(
"__iter__", [](state &s) -> state& {
return s; })
1693 .def(
"__next__", [](state &s) -> KeyType {
1694 if (!s.first_or_done)
1697 s.first_or_done =
false;
1698 if (s.it == s.end) {
1699 s.first_or_done =
true;
1702 return (*s.it).first;
1703 }, std::forward<Extra>(extra)..., Policy);
1713 return make_iterator<Policy>(std::begin(value),
std::end(value), extra...);
1720 return make_key_iterator<Policy>(std::begin(value),
std::end(value), extra...);
1726 set_flag(
bool &flag) : flag(flag) { flag =
true; }
1727 ~set_flag() { flag =
false; }
1729 auto implicit_caster = [](PyObject *obj, PyTypeObject *
type) -> PyObject * {
1730 static bool currently_used =
false;
1733 set_flag flag_helper(currently_used);
1738 PyObject *result = PyObject_Call((PyObject *) type, args.
ptr(),
nullptr);
1739 if (result ==
nullptr)
1744 if (
auto tinfo = detail::get_type_info(
typeid(OutputType)))
1745 tinfo->implicit_conversions.push_back(implicit_caster);
1747 pybind11_fail(
"implicitly_convertible: Unable to find type " + type_id<OutputType>());
1750 template <
typename ExceptionTranslator>
1752 detail::get_internals().registered_exception_translators.push_front(
1753 std::forward<ExceptionTranslator>(translator));
1763 template <
typename type>
1768 std::string full_name = scope.
attr(
"__name__").cast<std::string>() +
1769 std::string(
".") + name;
1770 m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()),
base, NULL);
1772 pybind11_fail(
"Error during initialization: multiple incompatible " 1773 "definitions with name \"" + std::string(name) +
"\"");
1774 scope.
attr(name) = *
this;
1779 PyErr_SetString(m_ptr, message);
1787 template <
typename CppException>
1797 template <
typename CppException>
1800 PyObject *
base = PyExc_Exception) {
1801 auto &ex = detail::get_exception_object<CppException>();
1807 std::rethrow_exception(p);
1808 }
catch (
const CppException &e) {
1809 detail::get_exception_object<CppException>()(e.what());
1817 auto strings =
tuple(args.size());
1818 for (
size_t i = 0;
i < args.size(); ++
i) {
1819 strings[
i] =
str(args[
i]);
1821 auto sep = kwargs.contains(
"sep") ? kwargs[
"sep"] :
cast(
" ");
1825 if (kwargs.contains(
"file")) {
1826 file = kwargs[
"file"].
cast<
object>();
1829 file = module::import(
"sys").
attr(
"stdout");
1841 write(kwargs.contains(
"end") ? kwargs[
"end"] :
cast(
"\n"));
1843 if (kwargs.contains(
"flush") && kwargs[
"flush"].cast<
bool>())
1844 file.
attr(
"flush")();
1848 template <
return_value_policy policy = return_value_policy::automatic_reference,
typename... Args>
1850 auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
1854 #if defined(WITH_THREAD) && !defined(PYPY_VERSION) 1881 auto const &internals = detail::get_internals();
1890 tstate = PyGILState_GetThisThreadState();
1894 tstate = PyThreadState_New(internals.istate);
1895 #if !defined(NDEBUG) 1897 pybind11_fail(
"scoped_acquire: could not create thread state!");
1899 tstate->gilstate_counter = 0;
1907 #if defined(Py_DEBUG) 1908 PyInterpreterState *interp = tstate->interp;
1909 tstate->interp =
nullptr;
1911 PyEval_AcquireThread(tstate);
1912 #if defined(Py_DEBUG) 1913 tstate->interp = interp;
1921 ++tstate->gilstate_counter;
1925 --tstate->gilstate_counter;
1926 #if !defined(NDEBUG) 1928 pybind11_fail(
"scoped_acquire::dec_ref(): thread state must be current!");
1929 if (tstate->gilstate_counter < 0)
1930 pybind11_fail(
"scoped_acquire::dec_ref(): reference count underflow!");
1932 if (tstate->gilstate_counter == 0) {
1933 #if !defined(NDEBUG) 1935 pybind11_fail(
"scoped_acquire::dec_ref(): internal error!");
1937 PyThreadState_Clear(tstate);
1938 PyThreadState_DeleteCurrent();
1947 PyEval_SaveThread();
1950 PyThreadState *tstate =
nullptr;
1960 const auto &internals = detail::get_internals();
1961 tstate = PyEval_SaveThread();
1963 auto key = internals.tstate;
1970 PyEval_RestoreThread(tstate);
1972 auto key = detail::get_internals().tstate;
1977 PyThreadState *tstate;
1980 #elif defined(PYPY_VERSION) 1982 PyGILState_STATE state;
1989 PyThreadState *state;
1999 error_already_set::~error_already_set() {
2003 m_type.release().dec_ref();
2004 m_value.release().dec_ref();
2005 m_trace.release().dec_ref();
2010 handle self = detail::get_object_handle(this_ptr, this_type);
2014 auto key = std::make_pair(type.
ptr(), name);
2018 auto &cache = detail::get_internals().inactive_overload_cache;
2019 if (cache.find(key) != cache.end())
2022 function overload =
getattr(
self, name,
function());
2023 if (overload.is_cpp_function()) {
2030 #if !defined(PYPY_VERSION) 2031 PyFrameObject *frame = PyThreadState_Get()->frame;
2032 if (frame && (std::string)
str(frame->f_code->co_name) == name &&
2033 frame->f_code->co_argcount > 0) {
2034 PyFrame_FastToLocals(frame);
2035 PyObject *self_caller = PyDict_GetItem(
2036 frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
2037 if (self_caller ==
self.ptr())
2045 PyObject *result = PyRun_String(
2047 "frame = inspect.currentframe()\n" 2048 "if frame is not None:\n" 2049 " frame = frame.f_back\n" 2050 " if frame is not None and str(frame.f_code.co_name) == name and " 2051 "frame.f_code.co_argcount > 0:\n" 2052 " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n" 2053 " if self_caller == self:\n" 2055 Py_file_input, d.
ptr(), d.
ptr());
2056 if (result ==
nullptr)
2058 if (d[
"self"].is_none())
2075 auto tinfo = detail::get_type_info(
typeid(T));
2079 #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) { \ 2080 pybind11::gil_scoped_acquire gil; \ 2081 pybind11::function overload = pybind11::get_overload(static_cast<const cname *>(this), name); \ 2083 auto o = overload(__VA_ARGS__); \ 2084 if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \ 2085 static pybind11::detail::overload_caster_t<ret_type> caster; \ 2086 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \ 2088 else return pybind11::detail::cast_safe<ret_type>(std::move(o)); \ 2109 #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \ 2110 PYBIND11_OVERLOAD_INT(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__) \ 2111 return cname::fn(__VA_ARGS__) 2117 #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \ 2118 PYBIND11_OVERLOAD_INT(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), name, __VA_ARGS__) \ 2119 pybind11::pybind11_fail("Tried to call pure virtual function \"" PYBIND11_STRINGIFY(cname) "::" name "\""); 2145 #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \ 2146 PYBIND11_OVERLOAD_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__) 2152 #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \ 2153 PYBIND11_OVERLOAD_PURE_NAME(PYBIND11_TYPE(ret_type), PYBIND11_TYPE(cname), #fn, fn, __VA_ARGS__) 2157 #if defined(_MSC_VER) && !defined(__INTEL_COMPILER) 2158 # pragma warning(pop) 2159 #elif defined(__GNUG__) && !defined(__clang__) 2160 # pragma GCC diagnostic pop
class_ & def_readwrite_static(const char *name, D *pm, const Extra &...extra)
class_ & def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra &...extra)
Uses return_value_policy::reference by default.
class_ & def(const detail::initimpl::constructor< Args... > &init, const Extra &... extra)
constexpr int first(int i)
Implementation details for constexpr functions.
#define PYBIND11_ENUM_OP_STRICT(op, expr, strict_behavior)
std::uint16_t nargs
Number of arguments (including py::args and/or py::kwargs, if present)
Implementation for py::pickle(GetState, SetState)
detail::exactly_one_t< is_holder, std::unique_ptr< type >, options... > holder_type
handle get_type() const
Return a handle to the Python type object underlying the instance.
void operator()(const char *message)
std::vector< handle > args
Arguments passed to the function:
PyMethodDef * def
Python method object.
static detail::function_record * get_function_record(handle h)
Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object.
value_and_holder get_value_and_holder(const type_info *find_type=nullptr, bool throw_if_missing=true)
Annotation for parent scope.
constexpr const date::last_spec last
Operator implementation generator.
std::unordered_map< PyTypeObject *, std::vector< type_info * > > registered_types_py
#define PYBIND11_NAMESPACE
constexpr const char * type_name()
This one should not be used, since vector types print the internal type.
PyObject * ptr() const
Return the underlying PyObject * pointer.
object getattr(handle obj, handle name)
static void init_instance(detail::instance *inst, const void *holder_ptr)
return_value_policy policy
Return value policy associated with this function.
bool is_constructor
True if name == 'init'.
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.
handle sibling
Python handle to the sibling function representing an overload chain.
typename exactly_one< Predicate, Default, Ts... >::type exactly_one_t
void call_operator_delete(void *p, size_t s, size_t a)
void register_instance(instance *self, void *valptr, const type_info *tinfo)
RAII wrapper that temporarily clears any Python error state.
void setstate(value_and_holder &v_h, T &&result, bool need_alias)
Set just the C++ state. Same as __init__.
const char * name
If non-null, this is a named kwargs argument.
cpp_function(Return(*f)(Args...), const Extra &... extra)
Construct a cpp_function from a vanilla function pointer.
detail::exactly_one_t< is_subtype, void, options... > type_alias
const char * name
Name of the class.
detail::type_info * get_local_type_info(const std::type_index &tp)
void add_patient(PyObject *nurse, PyObject *patient)
typename void_t_impl< Ts... >::type void_t
class_ & def_buffer(Func &&func)
void(* free_data)(function_record *ptr)
Pointer to custom destructor for 'data' (if needed)
static constexpr size_t size_in_ptrs(size_t s)
static void execute(Class &cl, const Extra &... extra)
enum_base(handle base, handle parent)
void set_holder_constructed(bool v=true)
void(* dealloc)(detail::value_and_holder &)
Function pointer to class_<..>::dealloc.
std::is_same< bools< Ts::value..., true >, bools< true, Ts::value... > > all_of
class_ & def_property_readonly(const char *name, const Getter &fget, const Extra &...extra)
Uses return_value_policy::reference_internal by default.
class_ & def_buffer(Return(Class::*func)(Args...))
PyThreadState * get_thread_state_unchecked()
bool holder_constructed() const
bool equal(object_api const &other) const
Equivalent to obj == other in Python.
bool contains(T &&key) const
#define PYBIND11_INSTANCE_METHOD_GET_FUNCTION
static void init_holder_from_existing(const detail::value_and_holder &v_h, const holder_type *holder_ptr, std::false_type)
enum_ & value(char const *name, Type value, const char *doc=nullptr)
Add an enumeration entry.
type_map< type_info * > & registered_local_types_cpp()
Works like internals.registered_types_cpp, but for module-local registered types: ...
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)
handle parent
The parent, if any.
bool_constant< std::is_base_of< Base, Derived >::value &&!std::is_same< Base, Derived >::value > is_strict_base_of
Internal data structure which holds metadata about a bound function (signature, overloads, etc.)
detail::type_info * get_global_type_info(const std::type_index &tp)
const std::vector< detail::type_info * > & all_type_info(PyTypeObject *type)
Internal data associated with a single function call.
constexpr descr< N - 1 > _(char const(&text)[N])
Ret init(CFunc &&c, AFunc &&a)
test_initializer class_("class_", test_submodule_class_)
arr data(const arr &a, Ix... index)
Binds C++ enumerations and enumeration classes to Python.
exception(handle scope, const char *name, PyObject *base=PyExc_Exception)
handle init_self
If this is a call to an initializer, this argument contains self
static void init_holder_from_existing(const detail::value_and_holder &v_h, const holder_type *holder_ptr, std::true_type)
class_ & def_readonly_static(const char *name, const D *pm, const Extra &...extra)
Information record describing a Python buffer object.
Wrapper for Python extension modules.
const handle & dec_ref() const &
#define PYBIND11_NOINLINE
class_ & def_cast(const detail::op_< id, ot, L, R > &op, const Extra &... extra)
The 'instance' type which needs to be standard layout (need to be able to use 'offsetof') ...
iterator make_iterator(Type &value, Extra &&... extra)
obj_attr_accessor attr(handle key) const
static void destruct(detail::function_record *rec)
When a cpp_function is GCed, release any memory allocated by pybind11.
typename std::underlying_type< Type >::type Scalar
bool is_none() const
Equivalent to obj is None in Python.
size_t function_call handle ret
op_< op_int, op_u, self_t, undefined_t > int_(const self_t &)
detail::is_strict_base_of< Type, T > is_subtype
auto method_adaptor(Return(Class::*pmf)(Args...)) -> Return(Derived::*)(Args...)
detail::initimpl::pickle_factory< GetState, SetState > pickle(GetState &&g, SetState &&s)
handle scope
Python handle to the parent scope (a class or a module)
handle scope
Handle to the parent scope.
iterator make_key_iterator(Type &value, Extra &&... extra)
void(* init_instance)(instance *, const void *)
Function pointer to class_<..>::init_instance.
#define NAMESPACE_END(name)
exception< CppException > & register_exception(handle scope, const char *name, PyObject *base=PyExc_Exception)
#define PYBIND11_DESCR_CONSTEXPR
cpp_function(Return(Class::*f)(Arg...), const Extra &... extra)
Construct a cpp_function from a class method (non-const)
const detail::type_info * type
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) ...
bool module_local
Is the class definition local to the module shared object?
class_ & def_property_readonly_static(const char *name, const cpp_function &fget, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
return_value_policy
Approach used to cast a previously unknown C++ instance into a Python object.
enum_ & export_values()
Export enumeration entries into the parent scope.
#define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun)
void execute_cast(Class &cl, const Extra &... extra) const
static void dealloc(detail::value_and_holder &v_h)
Deallocates an instance; via holder, if constructed; otherwise via operator delete.
Annotation indicating that a function is an overload associated with a given "sibling".
bool multiple_inheritance
Multiple inheritance marker.
bool is_method
True if this is a method.
bool owned
If true, the pointer is owned which means we're free to manage it with a holder.
detail::initimpl::alias_constructor< Args... > init_alias()
class_ & def(const detail::op_< id, ot, L, R > &op, const Extra &... extra)
size_t function_call & call
enum_(const handle &scope, const char *name, const Extra &... extra)
static bool show_user_defined_docstrings()
char * name
Function name.
negation< any_of< Ts... > > none_of
#define PYBIND11_TLS_DELETE_VALUE(key)
#define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN)
void initialize(Func &&f, Return(*)(Args...), const Extra &... extra)
Special internal constructor for functors, lambda functions, etc.
void set_operator_new(...)
constexpr size_t constexpr_sum()
Compile-time integer sum.
const std::type_info * type
bool default_holder
Is the default (unique_ptr) holder type used?
write(kwargs.contains("end") ? kwargs["end"] :cast("\))
class_ & def(detail::initimpl::factory< Args... > &&init, const Extra &... extra)
#define PYBIND11_ENUM_OP_CONV(op, expr)
std::pair< decltype(internals::registered_types_py)::iterator, bool > all_type_info_get_cache(PyTypeObject *type)
class_ & def_static(const char *name_, Func &&f, const Extra &... extra)
#define PYBIND11_MODULE_LOCAL_ID
class_ & def_buffer(Return(Class::*func)(Args...) const)
void *(* operator_new)(size_t)
The global operator new can be overridden with a class-specific variant.
void register_exception_translator(ExceptionTranslator &&translator)
str format(Args &&...args) const
Annotation for documentation.
op_id
Enumeration with all supported operator types.
#define PYBIND11_TRY_NEXT_OVERLOAD
static PyObject * dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in)
Main dispatch logic for calls to functions bound using pybind11.
const function_record & func
The function data:
static void execute(Class &cl, const Extra &... extra)
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. ...
void execute(Class &cl, const Extra &... extra) const
Annotation indicating that a class derives from another given type.
const detail::type_info * type
Annotation for function names.
#define PYBIND11_TLS_REPLACE_VALUE(key, value)
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.
type_map< type_info * > registered_types_cpp
const char * c_str(Args &&...args)
class_ & def_property_readonly_static(const char *name, const Getter &fget, const Extra &...extra)
Uses return_value_policy::reference by default.
void implicitly_convertible()
exception< CppException > & get_exception_object()
detail::enable_if_t<!detail::move_never< T >::value, T > move(object &&obj)
function_record * next
Pointer to next overload.
handle get_function(handle value)
class_ & def(const detail::initimpl::alias_constructor< Args... > &init, const Extra &... extra)
#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_)
Include Python header, disable linking to pythonX_d.lib on Windows in debug mode. ...
detail::is_strict_base_of< T, Type > is_base
class_ & def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra &...extra)
char * signature
Human-readable version of the function signature.
cpp_function(std::nullptr_t)
void * data[3]
Storage for the wrapped function pointer and captured data, if any.
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.
cpp_function(Func &&f, const Extra &... extra)
Construct a cpp_function from a lambda function (possibly with internal state)
PyObject * make_new_python_type(const type_record &rec)
function get_overload(const T *this_ptr, const char *name)
#define NAMESPACE_BEGIN(name)
size_t holder_size
How large is the type's holder?
#define PYBIND11_INSTANCE_METHOD_CHECK
handle(* impl)(function_call &)
Pointer to lambda function which converts arguments and performs the actual call. ...
Thrown when pybind11::cast or handle::call fail due to a type casting error.
Generic support for creating new Python heap types.
#define PYBIND11_TLS_GET_VALUE(key)
T cast(const handle &handle)
bool is_new_style_constructor
True if this is a new-style __init__ defined in detail/init.h
std::vector< argument_record > args
List of registered keyword arguments.
class_ & def_readonly(const char *name, const D C::*pm, const Extra &...extra)
class_ & def_property(const char *name, const Getter &fget, const Setter &fset, const Extra &...extra)
Uses return_value_policy::reference_internal by default.
void print(Args &&...args)
bool load(handle src, bool convert)
bool_constant< std::is_base_of< Base, Derived >::value &&std::is_convertible< Derived *, Base * >::value > is_accessible_base_of
conditional_t< std::is_function< F >::value, F, typename conditional_t< std::is_pointer< F >::value||std::is_member_pointer< F >::value, std::remove_pointer< F >, strip_function_object< F > >::type > function_signature_t
function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name)
size_t type_align
What is the alignment of the underlying C++ type?
Special data structure which (temporarily) holds metadata about a bound class.
list bases
List of base classes of the newly created type.
type_caster< intrinsic_t< type > > make_caster
void setattr(handle obj, handle name, handle value)
bool typename Extra class_ & def(const char *name_, Func &&f, const Extra &... extra)
const std::type_info & tinfo
type_map< std::vector< bool(*)(PyObject *, void *&)> > direct_conversions
class_ & def(detail::initimpl::pickle_factory< Args... > &&pf, const Extra &...extra)
size_t type_size
How large is the underlying C++ type?
#define PYBIND11_OBJECT(Name, Parent, CheckFun)
cpp_function(Return(Class::*f)(Arg...) const, const Extra &... extra)
Construct a cpp_function from a class method (const)
typename std::enable_if< B, T >::type enable_if_t
from cpp_future import (convenient aliases from C++14/17)
const handle & inc_ref() const &
auto to_string(T &&value) -> decltype(std::forward< T >(value))
Convert an object to a string (directly forward if this can become a string)
class_ & def_property_readonly(const char *name, const cpp_function &fget, const Extra &...extra)
Uses cpp_function's return_value_policy by default.
bool hasattr(handle obj, handle name)
object name() const
Return the function name.
Annotation that marks a class as local to the module:
class_ & def_readwrite(const char *name, D C::*pm, const Extra &... extra)
keep_alive_impl(get_arg(Nurse), get_arg(Patient))