You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1741 lines
75 KiB

8 years ago
  1. /*
  2. pybind11/pybind11.h: Main header file of the C++11 python
  3. binding generator library
  4. Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
  5. All rights reserved. Use of this source code is governed by a
  6. BSD-style license that can be found in the LICENSE file.
  7. */
  8. #pragma once
  9. #if defined(_MSC_VER)
  10. # pragma warning(push)
  11. # pragma warning(disable: 4100) // warning C4100: Unreferenced formal parameter
  12. # pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
  13. # pragma warning(disable: 4512) // warning C4512: Assignment operator was implicitly defined as deleted
  14. # pragma warning(disable: 4800) // warning C4800: 'int': forcing value to bool 'true' or 'false' (performance warning)
  15. # pragma warning(disable: 4996) // warning C4996: The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name
  16. # pragma warning(disable: 4702) // warning C4702: unreachable code
  17. # pragma warning(disable: 4522) // warning C4522: multiple assignment operators specified
  18. #elif defined(__INTEL_COMPILER)
  19. # pragma warning(push)
  20. # pragma warning(disable: 186) // pointless comparison of unsigned integer with zero
  21. # pragma warning(disable: 1334) // the "template" keyword used for syntactic disambiguation may only be used within a template
  22. # pragma warning(disable: 2196) // warning #2196: routine is both "inline" and "noinline"
  23. #elif defined(__GNUG__) && !defined(__clang__)
  24. # pragma GCC diagnostic push
  25. # pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
  26. # pragma GCC diagnostic ignored "-Wunused-but-set-variable"
  27. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  28. # pragma GCC diagnostic ignored "-Wstrict-aliasing"
  29. # pragma GCC diagnostic ignored "-Wattributes"
  30. #endif
  31. #include "attr.h"
  32. #include "options.h"
  33. #include "class_support.h"
  34. NAMESPACE_BEGIN(pybind11)
  35. /// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
  36. class cpp_function : public function {
  37. public:
  38. cpp_function() { }
  39. /// Construct a cpp_function from a vanilla function pointer
  40. template <typename Return, typename... Args, typename... Extra>
  41. cpp_function(Return (*f)(Args...), const Extra&... extra) {
  42. initialize(f, f, extra...);
  43. }
  44. /// Construct a cpp_function from a lambda function (possibly with internal state)
  45. template <typename Func, typename... Extra, typename = detail::enable_if_t<
  46. detail::satisfies_none_of<
  47. typename std::remove_reference<Func>::type,
  48. std::is_function, std::is_pointer, std::is_member_pointer
  49. >::value>
  50. >
  51. cpp_function(Func &&f, const Extra&... extra) {
  52. using FuncType = typename detail::remove_class<decltype(&std::remove_reference<Func>::type::operator())>::type;
  53. initialize(std::forward<Func>(f),
  54. (FuncType *) nullptr, extra...);
  55. }
  56. /// Construct a cpp_function from a class method (non-const)
  57. template <typename Return, typename Class, typename... Arg, typename... Extra>
  58. cpp_function(Return (Class::*f)(Arg...), const Extra&... extra) {
  59. initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
  60. (Return (*) (Class *, Arg...)) nullptr, extra...);
  61. }
  62. /// Construct a cpp_function from a class method (const)
  63. template <typename Return, typename Class, typename... Arg, typename... Extra>
  64. cpp_function(Return (Class::*f)(Arg...) const, const Extra&... extra) {
  65. initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
  66. (Return (*)(const Class *, Arg ...)) nullptr, extra...);
  67. }
  68. /// Return the function name
  69. object name() const { return attr("__name__"); }
  70. protected:
  71. /// Space optimization: don't inline this frequently instantiated fragment
  72. PYBIND11_NOINLINE detail::function_record *make_function_record() {
  73. return new detail::function_record();
  74. }
  75. /// Special internal constructor for functors, lambda functions, etc.
  76. template <typename Func, typename Return, typename... Args, typename... Extra>
  77. void initialize(Func &&f, Return (*)(Args...), const Extra&... extra) {
  78. struct capture { typename std::remove_reference<Func>::type f; };
  79. /* Store the function including any extra state it might have (e.g. a lambda capture object) */
  80. auto rec = make_function_record();
  81. /* Store the capture object directly in the function record if there is enough space */
  82. if (sizeof(capture) <= sizeof(rec->data)) {
  83. /* Without these pragmas, GCC warns that there might not be
  84. enough space to use the placement new operator. However, the
  85. 'if' statement above ensures that this is the case. */
  86. #if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
  87. # pragma GCC diagnostic push
  88. # pragma GCC diagnostic ignored "-Wplacement-new"
  89. #endif
  90. new ((capture *) &rec->data) capture { std::forward<Func>(f) };
  91. #if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
  92. # pragma GCC diagnostic pop
  93. #endif
  94. if (!std::is_trivially_destructible<Func>::value)
  95. rec->free_data = [](detail::function_record *r) { ((capture *) &r->data)->~capture(); };
  96. } else {
  97. rec->data[0] = new capture { std::forward<Func>(f) };
  98. rec->free_data = [](detail::function_record *r) { delete ((capture *) r->data[0]); };
  99. }
  100. /* Type casters for the function arguments and return value */
  101. using cast_in = detail::argument_loader<Args...>;
  102. using cast_out = detail::make_caster<
  103. detail::conditional_t<std::is_void<Return>::value, detail::void_type, Return>
  104. >;
  105. static_assert(detail::expected_num_args<Extra...>(sizeof...(Args), cast_in::has_args, cast_in::has_kwargs),
  106. "The number of argument annotations does not match the number of function arguments");
  107. /* Dispatch code which converts function arguments and performs the actual function call */
  108. rec->impl = [](detail::function_call &call) -> handle {
  109. cast_in args_converter;
  110. /* Try to cast the function arguments into the C++ domain */
  111. if (!args_converter.load_args(call))
  112. return PYBIND11_TRY_NEXT_OVERLOAD;
  113. /* Invoke call policy pre-call hook */
  114. detail::process_attributes<Extra...>::precall(call);
  115. /* Get a pointer to the capture object */
  116. auto data = (sizeof(capture) <= sizeof(call.func.data)
  117. ? &call.func.data : call.func.data[0]);
  118. capture *cap = const_cast<capture *>(reinterpret_cast<const capture *>(data));
  119. /* Override policy for rvalues -- usually to enforce rvp::move on an rvalue */
  120. const auto policy = detail::return_value_policy_override<Return>::policy(call.func.policy);
  121. /* Perform the function call */
  122. handle result = cast_out::cast(args_converter.template call<Return>(cap->f),
  123. policy, call.parent);
  124. /* Invoke call policy post-call hook */
  125. detail::process_attributes<Extra...>::postcall(call, result);
  126. return result;
  127. };
  128. /* Process any user-provided function attributes */
  129. detail::process_attributes<Extra...>::init(extra..., rec);
  130. /* Generate a readable signature describing the function's arguments and return value types */
  131. using detail::descr; using detail::_;
  132. PYBIND11_DESCR signature = _("(") + cast_in::arg_names() + _(") -> ") + cast_out::name();
  133. /* Register the function with Python from generic (non-templated) code */
  134. initialize_generic(rec, signature.text(), signature.types(), sizeof...(Args));
  135. if (cast_in::has_args) rec->has_args = true;
  136. if (cast_in::has_kwargs) rec->has_kwargs = true;
  137. /* Stash some additional information used by an important optimization in 'functional.h' */
  138. using FunctionType = Return (*)(Args...);
  139. constexpr bool is_function_ptr =
  140. std::is_convertible<Func, FunctionType>::value &&
  141. sizeof(capture) == sizeof(void *);
  142. if (is_function_ptr) {
  143. rec->is_stateless = true;
  144. rec->data[1] = const_cast<void *>(reinterpret_cast<const void *>(&typeid(FunctionType)));
  145. }
  146. }
  147. /// Register a function call with Python (generic non-templated code goes here)
  148. void initialize_generic(detail::function_record *rec, const char *text,
  149. const std::type_info *const *types, size_t args) {
  150. /* Create copies of all referenced C-style strings */
  151. rec->name = strdup(rec->name ? rec->name : "");
  152. if (rec->doc) rec->doc = strdup(rec->doc);
  153. for (auto &a: rec->args) {
  154. if (a.name)
  155. a.name = strdup(a.name);
  156. if (a.descr)
  157. a.descr = strdup(a.descr);
  158. else if (a.value)
  159. a.descr = strdup(a.value.attr("__repr__")().cast<std::string>().c_str());
  160. }
  161. /* Generate a proper function signature */
  162. std::string signature;
  163. size_t type_depth = 0, char_index = 0, type_index = 0, arg_index = 0;
  164. while (true) {
  165. char c = text[char_index++];
  166. if (c == '\0')
  167. break;
  168. if (c == '{') {
  169. // Write arg name for everything except *args, **kwargs and return type.
  170. if (type_depth == 0 && text[char_index] != '*' && arg_index < args) {
  171. if (!rec->args.empty() && rec->args[arg_index].name) {
  172. signature += rec->args[arg_index].name;
  173. } else if (arg_index == 0 && rec->is_method) {
  174. signature += "self";
  175. } else {
  176. signature += "arg" + std::to_string(arg_index - (rec->is_method ? 1 : 0));
  177. }
  178. signature += ": ";
  179. }
  180. ++type_depth;
  181. } else if (c == '}') {
  182. --type_depth;
  183. if (type_depth == 0) {
  184. if (arg_index < rec->args.size() && rec->args[arg_index].descr) {
  185. signature += "=";
  186. signature += rec->args[arg_index].descr;
  187. }
  188. arg_index++;
  189. }
  190. } else if (c == '%') {
  191. const std::type_info *t = types[type_index++];
  192. if (!t)
  193. pybind11_fail("Internal error while parsing type signature (1)");
  194. if (auto tinfo = detail::get_type_info(*t)) {
  195. #if defined(PYPY_VERSION)
  196. signature += handle((PyObject *) tinfo->type)
  197. .attr("__module__")
  198. .cast<std::string>() + ".";
  199. #endif
  200. signature += tinfo->type->tp_name;
  201. } else {
  202. std::string tname(t->name());
  203. detail::clean_type_id(tname);
  204. signature += tname;
  205. }
  206. } else {
  207. signature += c;
  208. }
  209. }
  210. if (type_depth != 0 || types[type_index] != nullptr)
  211. pybind11_fail("Internal error while parsing type signature (2)");
  212. #if !defined(PYBIND11_CPP14)
  213. delete[] types;
  214. delete[] text;
  215. #endif
  216. #if PY_MAJOR_VERSION < 3
  217. if (strcmp(rec->name, "__next__") == 0) {
  218. std::free(rec->name);
  219. rec->name = strdup("next");
  220. } else if (strcmp(rec->name, "__bool__") == 0) {
  221. std::free(rec->name);
  222. rec->name = strdup("__nonzero__");
  223. }
  224. #endif
  225. rec->signature = strdup(signature.c_str());
  226. rec->args.shrink_to_fit();
  227. rec->is_constructor = !strcmp(rec->name, "__init__") || !strcmp(rec->name, "__setstate__");
  228. rec->nargs = (std::uint16_t) args;
  229. #if PY_MAJOR_VERSION < 3
  230. if (rec->sibling && PyMethod_Check(rec->sibling.ptr()))
  231. rec->sibling = PyMethod_GET_FUNCTION(rec->sibling.ptr());
  232. #endif
  233. detail::function_record *chain = nullptr, *chain_start = rec;
  234. if (rec->sibling) {
  235. if (PyCFunction_Check(rec->sibling.ptr())) {
  236. auto rec_capsule = reinterpret_borrow<capsule>(PyCFunction_GET_SELF(rec->sibling.ptr()));
  237. chain = (detail::function_record *) rec_capsule;
  238. /* Never append a method to an overload chain of a parent class;
  239. instead, hide the parent's overloads in this case */
  240. if (chain->scope != rec->scope)
  241. chain = nullptr;
  242. }
  243. // Don't trigger for things like the default __init__, which are wrapper_descriptors that we are intentionally replacing
  244. else if (!rec->sibling.is_none() && rec->name[0] != '_')
  245. pybind11_fail("Cannot overload existing non-function object \"" + std::string(rec->name) +
  246. "\" with a function of the same name");
  247. }
  248. if (!chain) {
  249. /* No existing overload was found, create a new function object */
  250. rec->def = new PyMethodDef();
  251. memset(rec->def, 0, sizeof(PyMethodDef));
  252. rec->def->ml_name = rec->name;
  253. rec->def->ml_meth = reinterpret_cast<PyCFunction>(*dispatcher);
  254. rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
  255. capsule rec_capsule(rec, [](void *ptr) {
  256. destruct((detail::function_record *) ptr);
  257. });
  258. object scope_module;
  259. if (rec->scope) {
  260. if (hasattr(rec->scope, "__module__")) {
  261. scope_module = rec->scope.attr("__module__");
  262. } else if (hasattr(rec->scope, "__name__")) {
  263. scope_module = rec->scope.attr("__name__");
  264. }
  265. }
  266. m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
  267. if (!m_ptr)
  268. pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
  269. } else {
  270. /* Append at the end of the overload chain */
  271. m_ptr = rec->sibling.ptr();
  272. inc_ref();
  273. chain_start = chain;
  274. while (chain->next)
  275. chain = chain->next;
  276. chain->next = rec;
  277. }
  278. std::string signatures;
  279. int index = 0;
  280. /* Create a nice pydoc rec including all signatures and
  281. docstrings of the functions in the overload chain */
  282. if (chain && options::show_function_signatures()) {
  283. // First a generic signature
  284. signatures += rec->name;
  285. signatures += "(*args, **kwargs)\n";
  286. signatures += "Overloaded function.\n\n";
  287. }
  288. // Then specific overload signatures
  289. bool first_user_def = true;
  290. for (auto it = chain_start; it != nullptr; it = it->next) {
  291. if (options::show_function_signatures()) {
  292. if (index > 0) signatures += "\n";
  293. if (chain)
  294. signatures += std::to_string(++index) + ". ";
  295. signatures += rec->name;
  296. signatures += it->signature;
  297. signatures += "\n";
  298. }
  299. if (it->doc && strlen(it->doc) > 0 && options::show_user_defined_docstrings()) {
  300. // If we're appending another docstring, and aren't printing function signatures, we
  301. // need to append a newline first:
  302. if (!options::show_function_signatures()) {
  303. if (first_user_def) first_user_def = false;
  304. else signatures += "\n";
  305. }
  306. if (options::show_function_signatures()) signatures += "\n";
  307. signatures += it->doc;
  308. if (options::show_function_signatures()) signatures += "\n";
  309. }
  310. }
  311. /* Install docstring */
  312. PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
  313. if (func->m_ml->ml_doc)
  314. std::free(const_cast<char *>(func->m_ml->ml_doc));
  315. func->m_ml->ml_doc = strdup(signatures.c_str());
  316. if (rec->is_method) {
  317. m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->scope.ptr());
  318. if (!m_ptr)
  319. pybind11_fail("cpp_function::cpp_function(): Could not allocate instance method object");
  320. Py_DECREF(func);
  321. }
  322. }
  323. /// When a cpp_function is GCed, release any memory allocated by pybind11
  324. static void destruct(detail::function_record *rec) {
  325. while (rec) {
  326. detail::function_record *next = rec->next;
  327. if (rec->free_data)
  328. rec->free_data(rec);
  329. std::free((char *) rec->name);
  330. std::free((char *) rec->doc);
  331. std::free((char *) rec->signature);
  332. for (auto &arg: rec->args) {
  333. std::free(const_cast<char *>(arg.name));
  334. std::free(const_cast<char *>(arg.descr));
  335. arg.value.dec_ref();
  336. }
  337. if (rec->def) {
  338. std::free(const_cast<char *>(rec->def->ml_doc));
  339. delete rec->def;
  340. }
  341. delete rec;
  342. rec = next;
  343. }
  344. }
  345. /// Main dispatch logic for calls to functions bound using pybind11
  346. static PyObject *dispatcher(PyObject *self, PyObject *args_in, PyObject *kwargs_in) {
  347. using namespace detail;
  348. /* Iterator over the list of potentially admissible overloads */
  349. function_record *overloads = (function_record *) PyCapsule_GetPointer(self, nullptr),
  350. *it = overloads;
  351. /* Need to know how many arguments + keyword arguments there are to pick the right overload */
  352. const size_t n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
  353. handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr,
  354. result = PYBIND11_TRY_NEXT_OVERLOAD;
  355. try {
  356. // We do this in two passes: in the first pass, we load arguments with `convert=false`;
  357. // in the second, we allow conversion (except for arguments with an explicit
  358. // py::arg().noconvert()). This lets us prefer calls without conversion, with
  359. // conversion as a fallback.
  360. std::vector<function_call> second_pass;
  361. // However, if there are no overloads, we can just skip the no-convert pass entirely
  362. const bool overloaded = it != nullptr && it->next != nullptr;
  363. for (; it != nullptr; it = it->next) {
  364. /* For each overload:
  365. 1. Copy all positional arguments we were given, also checking to make sure that
  366. named positional arguments weren't *also* specified via kwarg.
  367. 2. If we weren't given enough, try to make up the omitted ones by checking
  368. whether they were provided by a kwarg matching the `py::arg("name")` name. If
  369. so, use it (and remove it from kwargs; if not, see if the function binding
  370. provided a default that we can use.
  371. 3. Ensure that either all keyword arguments were "consumed", or that the function
  372. takes a kwargs argument to accept unconsumed kwargs.
  373. 4. Any positional arguments still left get put into a tuple (for args), and any
  374. leftover kwargs get put into a dict.
  375. 5. Pack everything into a vector; if we have py::args or py::kwargs, they are an
  376. extra tuple or dict at the end of the positional arguments.
  377. 6. Call the function call dispatcher (function_record::impl)
  378. If one of these fail, move on to the next overload and keep trying until we get a
  379. result other than PYBIND11_TRY_NEXT_OVERLOAD.
  380. */
  381. function_record &func = *it;
  382. size_t pos_args = func.nargs; // Number of positional arguments that we need
  383. if (func.has_args) --pos_args; // (but don't count py::args
  384. if (func.has_kwargs) --pos_args; // or py::kwargs)
  385. if (!func.has_args && n_args_in > pos_args)
  386. continue; // Too many arguments for this overload
  387. if (n_args_in < pos_args && func.args.size() < pos_args)
  388. continue; // Not enough arguments given, and not enough defaults to fill in the blanks
  389. function_call call(func, parent);
  390. size_t args_to_copy = std::min(pos_args, n_args_in);
  391. size_t args_copied = 0;
  392. // 1. Copy any position arguments given.
  393. bool bad_kwarg = false;
  394. for (; args_copied < args_to_copy; ++args_copied) {
  395. if (kwargs_in && args_copied < func.args.size() && func.args[args_copied].name
  396. && PyDict_GetItemString(kwargs_in, func.args[args_copied].name)) {
  397. bad_kwarg = true;
  398. break;
  399. }
  400. call.args.push_back(PyTuple_GET_ITEM(args_in, args_copied));
  401. call.args_convert.push_back(args_copied < func.args.size() ? func.args[args_copied].convert : true);
  402. }
  403. if (bad_kwarg)
  404. continue; // Maybe it was meant for another overload (issue #688)
  405. // We'll need to copy this if we steal some kwargs for defaults
  406. dict kwargs = reinterpret_borrow<dict>(kwargs_in);
  407. // 2. Check kwargs and, failing that, defaults that may help complete the list
  408. if (args_copied < pos_args) {
  409. bool copied_kwargs = false;
  410. for (; args_copied < pos_args; ++args_copied) {
  411. const auto &arg = func.args[args_copied];
  412. handle value;
  413. if (kwargs_in && arg.name)
  414. value = PyDict_GetItemString(kwargs.ptr(), arg.name);
  415. if (value) {
  416. // Consume a kwargs value
  417. if (!copied_kwargs) {
  418. kwargs = reinterpret_steal<dict>(PyDict_Copy(kwargs.ptr()));
  419. copied_kwargs = true;
  420. }
  421. PyDict_DelItemString(kwargs.ptr(), arg.name);
  422. } else if (arg.value) {
  423. value = arg.value;
  424. }
  425. if (value) {
  426. call.args.push_back(value);
  427. call.args_convert.push_back(arg.convert);
  428. }
  429. else
  430. break;
  431. }
  432. if (args_copied < pos_args)
  433. continue; // Not enough arguments, defaults, or kwargs to fill the positional arguments
  434. }
  435. // 3. Check everything was consumed (unless we have a kwargs arg)
  436. if (kwargs && kwargs.size() > 0 && !func.has_kwargs)
  437. continue; // Unconsumed kwargs, but no py::kwargs argument to accept them
  438. // 4a. If we have a py::args argument, create a new tuple with leftovers
  439. tuple extra_args;
  440. if (func.has_args) {
  441. if (args_to_copy == 0) {
  442. // We didn't copy out any position arguments from the args_in tuple, so we
  443. // can reuse it directly without copying:
  444. extra_args = reinterpret_borrow<tuple>(args_in);
  445. } else if (args_copied >= n_args_in) {
  446. extra_args = tuple(0);
  447. } else {
  448. size_t args_size = n_args_in - args_copied;
  449. extra_args = tuple(args_size);
  450. for (size_t i = 0; i < args_size; ++i) {
  451. handle item = PyTuple_GET_ITEM(args_in, args_copied + i);
  452. extra_args[i] = item.inc_ref().ptr();
  453. }
  454. }
  455. call.args.push_back(extra_args);
  456. call.args_convert.push_back(false);
  457. }
  458. // 4b. If we have a py::kwargs, pass on any remaining kwargs
  459. if (func.has_kwargs) {
  460. if (!kwargs.ptr())
  461. kwargs = dict(); // If we didn't get one, send an empty one
  462. call.args.push_back(kwargs);
  463. call.args_convert.push_back(false);
  464. }
  465. // 5. Put everything in a vector. Not technically step 5, we've been building it
  466. // in `call.args` all along.
  467. #if !defined(NDEBUG)
  468. if (call.args.size() != func.nargs || call.args_convert.size() != func.nargs)
  469. pybind11_fail("Internal error: function call dispatcher inserted wrong number of arguments!");
  470. #endif
  471. std::vector<bool> second_pass_convert;
  472. if (overloaded) {
  473. // We're in the first no-convert pass, so swap out the conversion flags for a
  474. // set of all-false flags. If the call fails, we'll swap the flags back in for
  475. // the conversion-allowed call below.
  476. second_pass_convert.resize(func.nargs, false);
  477. call.args_convert.swap(second_pass_convert);
  478. }
  479. // 6. Call the function.
  480. try {
  481. result = func.impl(call);
  482. } catch (reference_cast_error &) {
  483. result = PYBIND11_TRY_NEXT_OVERLOAD;
  484. }
  485. if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
  486. break;
  487. if (overloaded) {
  488. // The (overloaded) call failed; if the call has at least one argument that
  489. // permits conversion (i.e. it hasn't been explicitly specified `.noconvert()`)
  490. // then add this call to the list of second pass overloads to try.
  491. for (size_t i = func.is_method ? 1 : 0; i < pos_args; i++) {
  492. if (second_pass_convert[i]) {
  493. // Found one: swap the converting flags back in and store the call for
  494. // the second pass.
  495. call.args_convert.swap(second_pass_convert);
  496. second_pass.push_back(std::move(call));
  497. break;
  498. }
  499. }
  500. }
  501. }
  502. if (overloaded && !second_pass.empty() && result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
  503. // The no-conversion pass finished without success, try again with conversion allowed
  504. for (auto &call : second_pass) {
  505. try {
  506. result = call.func.impl(call);
  507. } catch (reference_cast_error &) {
  508. result = PYBIND11_TRY_NEXT_OVERLOAD;
  509. }
  510. if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
  511. break;
  512. }
  513. }
  514. } catch (error_already_set &e) {
  515. e.restore();
  516. return nullptr;
  517. } catch (...) {
  518. /* When an exception is caught, give each registered exception
  519. translator a chance to translate it to a Python exception
  520. in reverse order of registration.
  521. A translator may choose to do one of the following:
  522. - catch the exception and call PyErr_SetString or PyErr_SetObject
  523. to set a standard (or custom) Python exception, or
  524. - do nothing and let the exception fall through to the next translator, or
  525. - delegate translation to the next translator by throwing a new type of exception. */
  526. auto last_exception = std::current_exception();
  527. auto &registered_exception_translators = get_internals().registered_exception_translators;
  528. for (auto& translator : registered_exception_translators) {
  529. try {
  530. translator(last_exception);
  531. } catch (...) {
  532. last_exception = std::current_exception();
  533. continue;
  534. }
  535. return nullptr;
  536. }
  537. PyErr_SetString(PyExc_SystemError, "Exception escaped from default exception translator!");
  538. return nullptr;
  539. }
  540. if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
  541. if (overloads->is_operator)
  542. return handle(Py_NotImplemented).inc_ref().ptr();
  543. std::string msg = std::string(overloads->name) + "(): incompatible " +
  544. std::string(overloads->is_constructor ? "constructor" : "function") +
  545. " arguments. The following argument types are supported:\n";
  546. int ctr = 0;
  547. for (function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
  548. msg += " "+ std::to_string(++ctr) + ". ";
  549. bool wrote_sig = false;
  550. if (overloads->is_constructor) {
  551. // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as `Object(arg0, ...)`
  552. std::string sig = it2->signature;
  553. size_t start = sig.find('(') + 7; // skip "(self: "
  554. if (start < sig.size()) {
  555. // End at the , for the next argument
  556. size_t end = sig.find(", "), next = end + 2;
  557. size_t ret = sig.rfind(" -> ");
  558. // Or the ), if there is no comma:
  559. if (end >= sig.size()) next = end = sig.find(')');
  560. if (start < end && next < sig.size()) {
  561. msg.append(sig, start, end - start);
  562. msg += '(';
  563. msg.append(sig, next, ret - next);
  564. wrote_sig = true;
  565. }
  566. }
  567. }
  568. if (!wrote_sig) msg += it2->signature;
  569. msg += "\n";
  570. }
  571. msg += "\nInvoked with: ";
  572. auto args_ = reinterpret_borrow<tuple>(args_in);
  573. bool some_args = false;
  574. for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
  575. if (!some_args) some_args = true;
  576. else msg += ", ";
  577. msg += pybind11::repr(args_[ti]);
  578. }
  579. if (kwargs_in) {
  580. auto kwargs = reinterpret_borrow<dict>(kwargs_in);
  581. if (kwargs.size() > 0) {
  582. if (some_args) msg += "; ";
  583. msg += "kwargs: ";
  584. bool first = true;
  585. for (auto kwarg : kwargs) {
  586. if (first) first = false;
  587. else msg += ", ";
  588. msg += pybind11::str("{}={!r}").format(kwarg.first, kwarg.second);
  589. }
  590. }
  591. }
  592. PyErr_SetString(PyExc_TypeError, msg.c_str());
  593. return nullptr;
  594. } else if (!result) {
  595. std::string msg = "Unable to convert function return value to a "
  596. "Python type! The signature was\n\t";
  597. msg += it->signature;
  598. PyErr_SetString(PyExc_TypeError, msg.c_str());
  599. return nullptr;
  600. } else {
  601. if (overloads->is_constructor) {
  602. /* When a constructor ran successfully, the corresponding
  603. holder type (e.g. std::unique_ptr) must still be initialized. */
  604. auto tinfo = get_type_info(Py_TYPE(parent.ptr()));
  605. tinfo->init_holder(parent.ptr(), nullptr);
  606. }
  607. return result.ptr();
  608. }
  609. }
  610. };
  611. /// Wrapper for Python extension modules
  612. class module : public object {
  613. public:
  614. PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
  615. /// Create a new top-level Python module with the given name and docstring
  616. explicit module(const char *name, const char *doc = nullptr) {
  617. if (!options::show_user_defined_docstrings()) doc = nullptr;
  618. #if PY_MAJOR_VERSION >= 3
  619. PyModuleDef *def = new PyModuleDef();
  620. memset(def, 0, sizeof(PyModuleDef));
  621. def->m_name = name;
  622. def->m_doc = doc;
  623. def->m_size = -1;
  624. Py_INCREF(def);
  625. m_ptr = PyModule_Create(def);
  626. #else
  627. m_ptr = Py_InitModule3(name, nullptr, doc);
  628. #endif
  629. if (m_ptr == nullptr)
  630. pybind11_fail("Internal error in module::module()");
  631. inc_ref();
  632. }
  633. /** \rst
  634. Create Python binding for a new function within the module scope. ``Func``
  635. can be a plain C++ function, a function pointer, or a lambda function. For
  636. details on the ``Extra&& ... extra`` argument, see section :ref:`extras`.
  637. \endrst */
  638. template <typename Func, typename... Extra>
  639. module &def(const char *name_, Func &&f, const Extra& ... extra) {
  640. cpp_function func(std::forward<Func>(f), name(name_), scope(*this),
  641. sibling(getattr(*this, name_, none())), extra...);
  642. // NB: allow overwriting here because cpp_function sets up a chain with the intention of
  643. // overwriting (and has already checked internally that it isn't overwriting non-functions).
  644. add_object(name_, func, true /* overwrite */);
  645. return *this;
  646. }
  647. /** \rst
  648. Create and return a new Python submodule with the given name and docstring.
  649. This also works recursively, i.e.
  650. .. code-block:: cpp
  651. py::module m("example", "pybind11 example plugin");
  652. py::module m2 = m.def_submodule("sub", "A submodule of 'example'");
  653. py::module m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'");
  654. \endrst */
  655. module def_submodule(const char *name, const char *doc = nullptr) {
  656. std::string full_name = std::string(PyModule_GetName(m_ptr))
  657. + std::string(".") + std::string(name);
  658. auto result = reinterpret_borrow<module>(PyImport_AddModule(full_name.c_str()));
  659. if (doc && options::show_user_defined_docstrings())
  660. result.attr("__doc__") = pybind11::str(doc);
  661. attr(name) = result;
  662. return result;
  663. }
  664. /// Import and return a module or throws `error_already_set`.
  665. static module import(const char *name) {
  666. PyObject *obj = PyImport_ImportModule(name);
  667. if (!obj)
  668. throw error_already_set();
  669. return reinterpret_steal<module>(obj);
  670. }
  671. // Adds an object to the module using the given name. Throws if an object with the given name
  672. // already exists.
  673. //
  674. // overwrite should almost always be false: attempting to overwrite objects that pybind11 has
  675. // established will, in most cases, break things.
  676. PYBIND11_NOINLINE void add_object(const char *name, object &obj, bool overwrite = false) {
  677. if (!overwrite && hasattr(*this, name))
  678. pybind11_fail("Error during initialization: multiple incompatible definitions with name \"" +
  679. std::string(name) + "\"");
  680. obj.inc_ref(); // PyModule_AddObject() steals a reference
  681. PyModule_AddObject(ptr(), name, obj.ptr());
  682. }
  683. };
  684. NAMESPACE_BEGIN(detail)
  685. /// Generic support for creating new Python heap types
  686. class generic_type : public object {
  687. template <typename...> friend class class_;
  688. public:
  689. PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
  690. protected:
  691. void initialize(const type_record &rec) {
  692. if (rec.scope && hasattr(rec.scope, rec.name))
  693. pybind11_fail("generic_type: cannot initialize type \"" + std::string(rec.name) +
  694. "\": an object with that name is already defined");
  695. if (get_type_info(*rec.type))
  696. pybind11_fail("generic_type: type \"" + std::string(rec.name) +
  697. "\" is already registered!");
  698. m_ptr = make_new_python_type(rec);
  699. /* Register supplemental type information in C++ dict */
  700. auto *tinfo = new detail::type_info();
  701. tinfo->type = (PyTypeObject *) m_ptr;
  702. tinfo->type_size = rec.type_size;
  703. tinfo->operator_new = rec.operator_new;
  704. tinfo->init_holder = rec.init_holder;
  705. tinfo->dealloc = rec.dealloc;
  706. auto &internals = get_internals();
  707. auto tindex = std::type_index(*rec.type);
  708. tinfo->direct_conversions = &internals.direct_conversions[tindex];
  709. tinfo->default_holder = rec.default_holder;
  710. internals.registered_types_cpp[tindex] = tinfo;
  711. internals.registered_types_py[m_ptr] = tinfo;
  712. if (rec.bases.size() > 1 || rec.multiple_inheritance)
  713. mark_parents_nonsimple(tinfo->type);
  714. }
  715. /// Helper function which tags all parents of a type using mult. inheritance
  716. void mark_parents_nonsimple(PyTypeObject *value) {
  717. auto t = reinterpret_borrow<tuple>(value->tp_bases);
  718. for (handle h : t) {
  719. auto tinfo2 = get_type_info((PyTypeObject *) h.ptr());
  720. if (tinfo2)
  721. tinfo2->simple_type = false;
  722. mark_parents_nonsimple((PyTypeObject *) h.ptr());
  723. }
  724. }
  725. void install_buffer_funcs(
  726. buffer_info *(*get_buffer)(PyObject *, void *),
  727. void *get_buffer_data) {
  728. PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
  729. auto tinfo = detail::get_type_info(&type->ht_type);
  730. if (!type->ht_type.tp_as_buffer)
  731. pybind11_fail(
  732. "To be able to register buffer protocol support for the type '" +
  733. std::string(tinfo->type->tp_name) +
  734. "' the associated class<>(..) invocation must "
  735. "include the pybind11::buffer_protocol() annotation!");
  736. tinfo->get_buffer = get_buffer;
  737. tinfo->get_buffer_data = get_buffer_data;
  738. }
  739. void def_property_static_impl(const char *name,
  740. handle fget, handle fset,
  741. detail::function_record *rec_fget) {
  742. const auto is_static = !(rec_fget->is_method && rec_fget->scope);
  743. const auto has_doc = rec_fget->doc && pybind11::options::show_user_defined_docstrings();
  744. auto property = handle((PyObject *) (is_static ? get_internals().static_property_type
  745. : &PyProperty_Type));
  746. attr(name) = property(fget.ptr() ? fget : none(),
  747. fset.ptr() ? fset : none(),
  748. /*deleter*/none(),
  749. pybind11::str(has_doc ? rec_fget->doc : ""));
  750. }
  751. };
  752. /// Set the pointer to operator new if it exists. The cast is needed because it can be overloaded.
  753. template <typename T, typename = void_t<decltype(static_cast<void *(*)(size_t)>(T::operator new))>>
  754. void set_operator_new(type_record *r) { r->operator_new = &T::operator new; }
  755. template <typename> void set_operator_new(...) { }
  756. /// Call class-specific delete if it exists or global otherwise. Can also be an overload set.
  757. template <typename T, typename = void_t<decltype(static_cast<void (*)(void *)>(T::operator delete))>>
  758. void call_operator_delete(T *p) { T::operator delete(p); }
  759. inline void call_operator_delete(void *p) { ::operator delete(p); }
  760. NAMESPACE_END(detail)
  761. template <typename type_, typename... options>
  762. class class_ : public detail::generic_type {
  763. template <typename T> using is_holder = detail::is_holder_type<type_, T>;
  764. template <typename T> using is_subtype = detail::bool_constant<std::is_base_of<type_, T>::value && !std::is_same<T, type_>::value>;
  765. template <typename T> using is_base = detail::bool_constant<std::is_base_of<T, type_>::value && !std::is_same<T, type_>::value>;
  766. // struct instead of using here to help MSVC:
  767. template <typename T> struct is_valid_class_option :
  768. detail::any_of<is_holder<T>, is_subtype<T>, is_base<T>> {};
  769. public:
  770. using type = type_;
  771. using type_alias = detail::first_of_t<is_subtype, void, options...>;
  772. constexpr static bool has_alias = !std::is_void<type_alias>::value;
  773. using holder_type = detail::first_of_t<is_holder, std::unique_ptr<type>, options...>;
  774. using instance_type = detail::instance<type, holder_type>;
  775. static_assert(detail::all_of<is_valid_class_option<options>...>::value,
  776. "Unknown/invalid class_ template parameters provided");
  777. PYBIND11_OBJECT(class_, generic_type, PyType_Check)
  778. template <typename... Extra>
  779. class_(handle scope, const char *name, const Extra &... extra) {
  780. using namespace detail;
  781. // MI can only be specified via class_ template options, not constructor parameters
  782. static_assert(
  783. none_of<is_pyobject<Extra>...>::value || // no base class arguments, or:
  784. ( constexpr_sum(is_pyobject<Extra>::value...) == 1 && // Exactly one base
  785. constexpr_sum(is_base<options>::value...) == 0 && // no template option bases
  786. none_of<std::is_same<multiple_inheritance, Extra>...>::value), // no multiple_inheritance attr
  787. "Error: multiple inheritance bases must be specified via class_ template options");
  788. type_record record;
  789. record.scope = scope;
  790. record.name = name;
  791. record.type = &typeid(type);
  792. record.type_size = sizeof(conditional_t<has_alias, type_alias, type>);
  793. record.instance_size = sizeof(instance_type);
  794. record.init_holder = init_holder;
  795. record.dealloc = dealloc;
  796. record.default_holder = std::is_same<holder_type, std::unique_ptr<type>>::value;
  797. set_operator_new<type>(&record);
  798. /* Register base classes specified via template arguments to class_, if any */
  799. bool unused[] = { (add_base<options>(record), false)..., false };
  800. (void) unused;
  801. /* Process optional arguments, if any */
  802. process_attributes<Extra...>::init(extra..., &record);
  803. generic_type::initialize(record);
  804. if (has_alias) {
  805. auto &instances = get_internals().registered_types_cpp;
  806. instances[std::type_index(typeid(type_alias))] = instances[std::type_index(typeid(type))];
  807. }
  808. }
  809. template <typename Base, detail::enable_if_t<is_base<Base>::value, int> = 0>
  810. static void add_base(detail::type_record &rec) {
  811. rec.add_base(&typeid(Base), [](void *src) -> void * {
  812. return static_cast<Base *>(reinterpret_cast<type *>(src));
  813. });
  814. }
  815. template <typename Base, detail::enable_if_t<!is_base<Base>::value, int> = 0>
  816. static void add_base(detail::type_record &) { }
  817. template <typename Func, typename... Extra>
  818. class_ &def(const char *name_, Func&& f, const Extra&... extra) {
  819. cpp_function cf(std::forward<Func>(f), name(name_), is_method(*this),
  820. sibling(getattr(*this, name_, none())), extra...);
  821. attr(cf.name()) = cf;
  822. return *this;
  823. }
  824. template <typename Func, typename... Extra> class_ &
  825. def_static(const char *name_, Func &&f, const Extra&... extra) {
  826. static_assert(!std::is_member_function_pointer<Func>::value,
  827. "def_static(...) called with a non-static member function pointer");
  828. cpp_function cf(std::forward<Func>(f), name(name_), scope(*this),
  829. sibling(getattr(*this, name_, none())), extra...);
  830. attr(cf.name()) = cf;
  831. return *this;
  832. }
  833. template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
  834. class_ &def(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
  835. op.execute(*this, extra...);
  836. return *this;
  837. }
  838. template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
  839. class_ & def_cast(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
  840. op.execute_cast(*this, extra...);
  841. return *this;
  842. }
  843. template <typename... Args, typename... Extra>
  844. class_ &def(const detail::init<Args...> &init, const Extra&... extra) {
  845. init.execute(*this, extra...);
  846. return *this;
  847. }
  848. template <typename... Args, typename... Extra>
  849. class_ &def(const detail::init_alias<Args...> &init, const Extra&... extra) {
  850. init.execute(*this, extra...);
  851. return *this;
  852. }
  853. template <typename Func> class_& def_buffer(Func &&func) {
  854. struct capture { Func func; };
  855. capture *ptr = new capture { std::forward<Func>(func) };
  856. install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
  857. detail::make_caster<type> caster;
  858. if (!caster.load(obj, false))
  859. return nullptr;
  860. return new buffer_info(((capture *) ptr)->func(caster));
  861. }, ptr);
  862. return *this;
  863. }
  864. template <typename C, typename D, typename... Extra>
  865. class_ &def_readwrite(const char *name, D C::*pm, const Extra&... extra) {
  866. cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; }, is_method(*this)),
  867. fset([pm](C &c, const D &value) { c.*pm = value; }, is_method(*this));
  868. def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
  869. return *this;
  870. }
  871. template <typename C, typename D, typename... Extra>
  872. class_ &def_readonly(const char *name, const D C::*pm, const Extra& ...extra) {
  873. cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; }, is_method(*this));
  874. def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
  875. return *this;
  876. }
  877. template <typename D, typename... Extra>
  878. class_ &def_readwrite_static(const char *name, D *pm, const Extra& ...extra) {
  879. cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this)),
  880. fset([pm](object, const D &value) { *pm = value; }, scope(*this));
  881. def_property_static(name, fget, fset, return_value_policy::reference, extra...);
  882. return *this;
  883. }
  884. template <typename D, typename... Extra>
  885. class_ &def_readonly_static(const char *name, const D *pm, const Extra& ...extra) {
  886. cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this));
  887. def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
  888. return *this;
  889. }
  890. /// Uses return_value_policy::reference_internal by default
  891. template <typename Getter, typename... Extra>
  892. class_ &def_property_readonly(const char *name, const Getter &fget, const Extra& ...extra) {
  893. return def_property_readonly(name, cpp_function(fget), return_value_policy::reference_internal, extra...);
  894. }
  895. /// Uses cpp_function's return_value_policy by default
  896. template <typename... Extra>
  897. class_ &def_property_readonly(const char *name, const cpp_function &fget, const Extra& ...extra) {
  898. return def_property(name, fget, cpp_function(), extra...);
  899. }
  900. /// Uses return_value_policy::reference by default
  901. template <typename Getter, typename... Extra>
  902. class_ &def_property_readonly_static(const char *name, const Getter &fget, const Extra& ...extra) {
  903. return def_property_readonly_static(name, cpp_function(fget), return_value_policy::reference, extra...);
  904. }
  905. /// Uses cpp_function's return_value_policy by default
  906. template <typename... Extra>
  907. class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const Extra& ...extra) {
  908. return def_property_static(name, fget, cpp_function(), extra...);
  909. }
  910. /// Uses return_value_policy::reference_internal by default
  911. template <typename Getter, typename... Extra>
  912. class_ &def_property(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
  913. return def_property(name, cpp_function(fget), fset, return_value_policy::reference_internal, extra...);
  914. }
  915. /// Uses cpp_function's return_value_policy by default
  916. template <typename... Extra>
  917. class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
  918. return def_property_static(name, fget, fset, is_method(*this), extra...);
  919. }
  920. /// Uses return_value_policy::reference by default
  921. template <typename Getter, typename... Extra>
  922. class_ &def_property_static(const char *name, const Getter &fget, const cpp_function &fset, const Extra& ...extra) {
  923. return def_property_static(name, cpp_function(fget), fset, return_value_policy::reference, extra...);
  924. }
  925. /// Uses cpp_function's return_value_policy by default
  926. template <typename... Extra>
  927. class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
  928. auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
  929. char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific documentation string */
  930. detail::process_attributes<Extra...>::init(extra..., rec_fget);
  931. if (rec_fget->doc && rec_fget->doc != doc_prev) {
  932. free(doc_prev);
  933. rec_fget->doc = strdup(rec_fget->doc);
  934. }
  935. if (rec_fset) {
  936. doc_prev = rec_fset->doc;
  937. detail::process_attributes<Extra...>::init(extra..., rec_fset);
  938. if (rec_fset->doc && rec_fset->doc != doc_prev) {
  939. free(doc_prev);
  940. rec_fset->doc = strdup(rec_fset->doc);
  941. }
  942. }
  943. def_property_static_impl(name, fget, fset, rec_fget);
  944. return *this;
  945. }
  946. private:
  947. /// Initialize holder object, variant 1: object derives from enable_shared_from_this
  948. template <typename T>
  949. static void init_holder_helper(instance_type *inst, const holder_type * /* unused */, const std::enable_shared_from_this<T> * /* dummy */) {
  950. try {
  951. new (&inst->holder) holder_type(std::static_pointer_cast<typename holder_type::element_type>(inst->value->shared_from_this()));
  952. inst->holder_constructed = true;
  953. } catch (const std::bad_weak_ptr &) {
  954. if (inst->owned) {
  955. new (&inst->holder) holder_type(inst->value);
  956. inst->holder_constructed = true;
  957. }
  958. }
  959. }
  960. static void init_holder_from_existing(instance_type *inst, const holder_type *holder_ptr,
  961. std::true_type /*is_copy_constructible*/) {
  962. new (&inst->holder) holder_type(*holder_ptr);
  963. }
  964. static void init_holder_from_existing(instance_type *inst, const holder_type *holder_ptr,
  965. std::false_type /*is_copy_constructible*/) {
  966. new (&inst->holder) holder_type(std::move(*const_cast<holder_type *>(holder_ptr)));
  967. }
  968. /// Initialize holder object, variant 2: try to construct from existing holder object, if possible
  969. static void init_holder_helper(instance_type *inst, const holder_type *holder_ptr, const void * /* dummy */) {
  970. if (holder_ptr) {
  971. init_holder_from_existing(inst, holder_ptr, std::is_copy_constructible<holder_type>());
  972. inst->holder_constructed = true;
  973. } else if (inst->owned || detail::always_construct_holder<holder_type>::value) {
  974. new (&inst->holder) holder_type(inst->value);
  975. inst->holder_constructed = true;
  976. }
  977. }
  978. /// Initialize holder object of an instance, possibly given a pointer to an existing holder
  979. static void init_holder(PyObject *inst_, const void *holder_ptr) {
  980. auto inst = (instance_type *) inst_;
  981. init_holder_helper(inst, (const holder_type *) holder_ptr, inst->value);
  982. }
  983. static void dealloc(PyObject *inst_) {
  984. instance_type *inst = (instance_type *) inst_;
  985. if (inst->holder_constructed)
  986. inst->holder.~holder_type();
  987. else if (inst->owned)
  988. detail::call_operator_delete(inst->value);
  989. }
  990. static detail::function_record *get_function_record(handle h) {
  991. h = detail::get_function(h);
  992. return h ? (detail::function_record *) reinterpret_borrow<capsule>(PyCFunction_GET_SELF(h.ptr()))
  993. : nullptr;
  994. }
  995. };
  996. /// Binds C++ enumerations and enumeration classes to Python
  997. template <typename Type> class enum_ : public class_<Type> {
  998. public:
  999. using class_<Type>::def;
  1000. using class_<Type>::def_property_readonly_static;
  1001. using Scalar = typename std::underlying_type<Type>::type;
  1002. template <typename T> using arithmetic_tag = std::is_same<T, arithmetic>;
  1003. template <typename... Extra>
  1004. enum_(const handle &scope, const char *name, const Extra&... extra)
  1005. : class_<Type>(scope, name, extra...), m_entries(), m_parent(scope) {
  1006. constexpr bool is_arithmetic =
  1007. !std::is_same<detail::first_of_t<arithmetic_tag, void, Extra...>,
  1008. void>::value;
  1009. auto m_entries_ptr = m_entries.inc_ref().ptr();
  1010. def("__repr__", [name, m_entries_ptr](Type value) -> pybind11::str {
  1011. for (const auto &kv : reinterpret_borrow<dict>(m_entries_ptr)) {
  1012. if (pybind11::cast<Type>(kv.second) == value)
  1013. return pybind11::str("{}.{}").format(name, kv.first);
  1014. }
  1015. return pybind11::str("{}.???").format(name);
  1016. });
  1017. def_property_readonly_static("__members__", [m_entries_ptr](object /* self */) {
  1018. dict m;
  1019. for (const auto &kv : reinterpret_borrow<dict>(m_entries_ptr))
  1020. m[kv.first] = kv.second;
  1021. return m;
  1022. }, return_value_policy::copy);
  1023. def("__init__", [](Type& value, Scalar i) { value = (Type)i; });
  1024. def("__int__", [](Type value) { return (Scalar) value; });
  1025. def("__eq__", [](const Type &value, Type *value2) { return value2 && value == *value2; });
  1026. def("__ne__", [](const Type &value, Type *value2) { return !value2 || value != *value2; });
  1027. if (is_arithmetic) {
  1028. def("__lt__", [](const Type &value, Type *value2) { return value2 && value < *value2; });
  1029. def("__gt__", [](const Type &value, Type *value2) { return value2 && value > *value2; });
  1030. def("__le__", [](const Type &value, Type *value2) { return value2 && value <= *value2; });
  1031. def("__ge__", [](const Type &value, Type *value2) { return value2 && value >= *value2; });
  1032. }
  1033. if (std::is_convertible<Type, Scalar>::value) {
  1034. // Don't provide comparison with the underlying type if the enum isn't convertible,
  1035. // i.e. if Type is a scoped enum, mirroring the C++ behaviour. (NB: we explicitly
  1036. // convert Type to Scalar below anyway because this needs to compile).
  1037. def("__eq__", [](const Type &value, Scalar value2) { return (Scalar) value == value2; });
  1038. def("__ne__", [](const Type &value, Scalar value2) { return (Scalar) value != value2; });
  1039. if (is_arithmetic) {
  1040. def("__lt__", [](const Type &value, Scalar value2) { return (Scalar) value < value2; });
  1041. def("__gt__", [](const Type &value, Scalar value2) { return (Scalar) value > value2; });
  1042. def("__le__", [](const Type &value, Scalar value2) { return (Scalar) value <= value2; });
  1043. def("__ge__", [](const Type &value, Scalar value2) { return (Scalar) value >= value2; });
  1044. def("__invert__", [](const Type &value) { return ~((Scalar) value); });
  1045. def("__and__", [](const Type &value, Scalar value2) { return (Scalar) value & value2; });
  1046. def("__or__", [](const Type &value, Scalar value2) { return (Scalar) value | value2; });
  1047. def("__xor__", [](const Type &value, Scalar value2) { return (Scalar) value ^ value2; });
  1048. def("__rand__", [](const Type &value, Scalar value2) { return (Scalar) value & value2; });
  1049. def("__ror__", [](const Type &value, Scalar value2) { return (Scalar) value | value2; });
  1050. def("__rxor__", [](const Type &value, Scalar value2) { return (Scalar) value ^ value2; });
  1051. def("__and__", [](const Type &value, const Type &value2) { return (Scalar) value & (Scalar) value2; });
  1052. def("__or__", [](const Type &value, const Type &value2) { return (Scalar) value | (Scalar) value2; });
  1053. def("__xor__", [](const Type &value, const Type &value2) { return (Scalar) value ^ (Scalar) value2; });
  1054. }
  1055. }
  1056. def("__hash__", [](const Type &value) { return (Scalar) value; });
  1057. // Pickling and unpickling -- needed for use with the 'multiprocessing' module
  1058. def("__getstate__", [](const Type &value) { return pybind11::make_tuple((Scalar) value); });
  1059. def("__setstate__", [](Type &p, tuple t) { new (&p) Type((Type) t[0].cast<Scalar>()); });
  1060. }
  1061. /// Export enumeration entries into the parent scope
  1062. enum_& export_values() {
  1063. for (const auto &kv : m_entries)
  1064. m_parent.attr(kv.first) = kv.second;
  1065. return *this;
  1066. }
  1067. /// Add an enumeration entry
  1068. enum_& value(char const* name, Type value) {
  1069. auto v = pybind11::cast(value, return_value_policy::copy);
  1070. this->attr(name) = v;
  1071. m_entries[pybind11::str(name)] = v;
  1072. return *this;
  1073. }
  1074. private:
  1075. dict m_entries;
  1076. handle m_parent;
  1077. };
  1078. NAMESPACE_BEGIN(detail)
  1079. template <typename... Args> struct init {
  1080. template <typename Class, typename... Extra, enable_if_t<!Class::has_alias, int> = 0>
  1081. static void execute(Class &cl, const Extra&... extra) {
  1082. using Base = typename Class::type;
  1083. /// Function which calls a specific C++ in-place constructor
  1084. cl.def("__init__", [](Base *self_, Args... args) { new (self_) Base(args...); }, extra...);
  1085. }
  1086. template <typename Class, typename... Extra,
  1087. enable_if_t<Class::has_alias &&
  1088. std::is_constructible<typename Class::type, Args...>::value, int> = 0>
  1089. static void execute(Class &cl, const Extra&... extra) {
  1090. using Base = typename Class::type;
  1091. using Alias = typename Class::type_alias;
  1092. handle cl_type = cl;
  1093. cl.def("__init__", [cl_type](handle self_, Args... args) {
  1094. if (self_.get_type() == cl_type)
  1095. new (self_.cast<Base *>()) Base(args...);
  1096. else
  1097. new (self_.cast<Alias *>()) Alias(args...);
  1098. }, extra...);
  1099. }
  1100. template <typename Class, typename... Extra,
  1101. enable_if_t<Class::has_alias &&
  1102. !std::is_constructible<typename Class::type, Args...>::value, int> = 0>
  1103. static void execute(Class &cl, const Extra&... extra) {
  1104. init_alias<Args...>::execute(cl, extra...);
  1105. }
  1106. };
  1107. template <typename... Args> struct init_alias {
  1108. template <typename Class, typename... Extra,
  1109. enable_if_t<Class::has_alias && std::is_constructible<typename Class::type_alias, Args...>::value, int> = 0>
  1110. static void execute(Class &cl, const Extra&... extra) {
  1111. using Alias = typename Class::type_alias;
  1112. cl.def("__init__", [](Alias *self_, Args... args) { new (self_) Alias(args...); }, extra...);
  1113. }
  1114. };
  1115. inline void keep_alive_impl(handle nurse, handle patient) {
  1116. /* Clever approach based on weak references taken from Boost.Python */
  1117. if (!nurse || !patient)
  1118. pybind11_fail("Could not activate keep_alive!");
  1119. if (patient.is_none() || nurse.is_none())
  1120. return; /* Nothing to keep alive or nothing to be kept alive by */
  1121. cpp_function disable_lifesupport(
  1122. [patient](handle weakref) { patient.dec_ref(); weakref.dec_ref(); });
  1123. weakref wr(nurse, disable_lifesupport);
  1124. patient.inc_ref(); /* reference patient and leak the weak reference */
  1125. (void) wr.release();
  1126. }
  1127. PYBIND11_NOINLINE inline void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret) {
  1128. keep_alive_impl(
  1129. Nurse == 0 ? ret : Nurse <= call.args.size() ? call.args[Nurse - 1] : handle(),
  1130. Patient == 0 ? ret : Patient <= call.args.size() ? call.args[Patient - 1] : handle()
  1131. );
  1132. }
  1133. template <typename Iterator, typename Sentinel, bool KeyIterator, return_value_policy Policy>
  1134. struct iterator_state {
  1135. Iterator it;
  1136. Sentinel end;
  1137. bool first;
  1138. };
  1139. NAMESPACE_END(detail)
  1140. template <typename... Args> detail::init<Args...> init() { return detail::init<Args...>(); }
  1141. template <typename... Args> detail::init_alias<Args...> init_alias() { return detail::init_alias<Args...>(); }
  1142. /// Makes a python iterator from a first and past-the-end C++ InputIterator.
  1143. template <return_value_policy Policy = return_value_policy::reference_internal,
  1144. typename Iterator,
  1145. typename Sentinel,
  1146. typename ValueType = decltype(*std::declval<Iterator>()),
  1147. typename... Extra>
  1148. iterator make_iterator(Iterator first, Sentinel last, Extra &&... extra) {
  1149. typedef detail::iterator_state<Iterator, Sentinel, false, Policy> state;
  1150. if (!detail::get_type_info(typeid(state), false)) {
  1151. class_<state>(handle(), "iterator")
  1152. .def("__iter__", [](state &s) -> state& { return s; })
  1153. .def("__next__", [](state &s) -> ValueType {
  1154. if (!s.first)
  1155. ++s.it;
  1156. else
  1157. s.first = false;
  1158. if (s.it == s.end)
  1159. throw stop_iteration();
  1160. return *s.it;
  1161. }, std::forward<Extra>(extra)..., Policy);
  1162. }
  1163. return (iterator) cast(state { first, last, true });
  1164. }
  1165. /// Makes an python iterator over the keys (`.first`) of a iterator over pairs from a
  1166. /// first and past-the-end InputIterator.
  1167. template <return_value_policy Policy = return_value_policy::reference_internal,
  1168. typename Iterator,
  1169. typename Sentinel,
  1170. typename KeyType = decltype((*std::declval<Iterator>()).first),
  1171. typename... Extra>
  1172. iterator make_key_iterator(Iterator first, Sentinel last, Extra &&... extra) {
  1173. typedef detail::iterator_state<Iterator, Sentinel, true, Policy> state;
  1174. if (!detail::get_type_info(typeid(state), false)) {
  1175. class_<state>(handle(), "iterator")
  1176. .def("__iter__", [](state &s) -> state& { return s; })
  1177. .def("__next__", [](state &s) -> KeyType {
  1178. if (!s.first)
  1179. ++s.it;
  1180. else
  1181. s.first = false;
  1182. if (s.it == s.end)
  1183. throw stop_iteration();
  1184. return (*s.it).first;
  1185. }, std::forward<Extra>(extra)..., Policy);
  1186. }
  1187. return (iterator) cast(state { first, last, true });
  1188. }
  1189. /// Makes an iterator over values of an stl container or other container supporting
  1190. /// `std::begin()`/`std::end()`
  1191. template <return_value_policy Policy = return_value_policy::reference_internal,
  1192. typename Type, typename... Extra> iterator make_iterator(Type &value, Extra&&... extra) {
  1193. return make_iterator<Policy>(std::begin(value), std::end(value), extra...);
  1194. }
  1195. /// Makes an iterator over the keys (`.first`) of a stl map-like container supporting
  1196. /// `std::begin()`/`std::end()`
  1197. template <return_value_policy Policy = return_value_policy::reference_internal,
  1198. typename Type, typename... Extra> iterator make_key_iterator(Type &value, Extra&&... extra) {
  1199. return make_key_iterator<Policy>(std::begin(value), std::end(value), extra...);
  1200. }
  1201. template <typename InputType, typename OutputType> void implicitly_convertible() {
  1202. auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
  1203. if (!detail::make_caster<InputType>().load(obj, false))
  1204. return nullptr;
  1205. tuple args(1);
  1206. args[0] = obj;
  1207. PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
  1208. if (result == nullptr)
  1209. PyErr_Clear();
  1210. return result;
  1211. };
  1212. if (auto tinfo = detail::get_type_info(typeid(OutputType)))
  1213. tinfo->implicit_conversions.push_back(implicit_caster);
  1214. else
  1215. pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
  1216. }
  1217. template <typename ExceptionTranslator>
  1218. void register_exception_translator(ExceptionTranslator&& translator) {
  1219. detail::get_internals().registered_exception_translators.push_front(
  1220. std::forward<ExceptionTranslator>(translator));
  1221. }
  1222. /* Wrapper to generate a new Python exception type.
  1223. *
  1224. * This should only be used with PyErr_SetString for now.
  1225. * It is not (yet) possible to use as a py::base.
  1226. * Template type argument is reserved for future use.
  1227. */
  1228. template <typename type>
  1229. class exception : public object {
  1230. public:
  1231. exception(handle scope, const char *name, PyObject *base = PyExc_Exception) {
  1232. std::string full_name = scope.attr("__name__").cast<std::string>() +
  1233. std::string(".") + name;
  1234. m_ptr = PyErr_NewException(const_cast<char *>(full_name.c_str()), base, NULL);
  1235. if (hasattr(scope, name))
  1236. pybind11_fail("Error during initialization: multiple incompatible "
  1237. "definitions with name \"" + std::string(name) + "\"");
  1238. scope.attr(name) = *this;
  1239. }
  1240. // Sets the current python exception to this exception object with the given message
  1241. void operator()(const char *message) {
  1242. PyErr_SetString(m_ptr, message);
  1243. }
  1244. };
  1245. /** Registers a Python exception in `m` of the given `name` and installs an exception translator to
  1246. * translate the C++ exception to the created Python exception using the exceptions what() method.
  1247. * This is intended for simple exception translations; for more complex translation, register the
  1248. * exception object and translator directly.
  1249. */
  1250. template <typename CppException>
  1251. exception<CppException> &register_exception(handle scope,
  1252. const char *name,
  1253. PyObject *base = PyExc_Exception) {
  1254. static exception<CppException> ex(scope, name, base);
  1255. register_exception_translator([](std::exception_ptr p) {
  1256. if (!p) return;
  1257. try {
  1258. std::rethrow_exception(p);
  1259. } catch (const CppException &e) {
  1260. ex(e.what());
  1261. }
  1262. });
  1263. return ex;
  1264. }
  1265. NAMESPACE_BEGIN(detail)
  1266. PYBIND11_NOINLINE inline void print(tuple args, dict kwargs) {
  1267. auto strings = tuple(args.size());
  1268. for (size_t i = 0; i < args.size(); ++i) {
  1269. strings[i] = str(args[i]);
  1270. }
  1271. auto sep = kwargs.contains("sep") ? kwargs["sep"] : cast(" ");
  1272. auto line = sep.attr("join")(strings);
  1273. object file;
  1274. if (kwargs.contains("file")) {
  1275. file = kwargs["file"].cast<object>();
  1276. } else {
  1277. try {
  1278. file = module::import("sys").attr("stdout");
  1279. } catch (const error_already_set &) {
  1280. /* If print() is called from code that is executed as
  1281. part of garbage collection during interpreter shutdown,
  1282. importing 'sys' can fail. Give up rather than crashing the
  1283. interpreter in this case. */
  1284. return;
  1285. }
  1286. }
  1287. auto write = file.attr("write");
  1288. write(line);
  1289. write(kwargs.contains("end") ? kwargs["end"] : cast("\n"));
  1290. if (kwargs.contains("flush") && kwargs["flush"].cast<bool>())
  1291. file.attr("flush")();
  1292. }
  1293. NAMESPACE_END(detail)
  1294. template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
  1295. void print(Args &&...args) {
  1296. auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
  1297. detail::print(c.args(), c.kwargs());
  1298. }
  1299. #if defined(WITH_THREAD) && !defined(PYPY_VERSION)
  1300. /* The functions below essentially reproduce the PyGILState_* API using a RAII
  1301. * pattern, but there are a few important differences:
  1302. *
  1303. * 1. When acquiring the GIL from an non-main thread during the finalization
  1304. * phase, the GILState API blindly terminates the calling thread, which
  1305. * is often not what is wanted. This API does not do this.
  1306. *
  1307. * 2. The gil_scoped_release function can optionally cut the relationship
  1308. * of a PyThreadState and its associated thread, which allows moving it to
  1309. * another thread (this is a fairly rare/advanced use case).
  1310. *
  1311. * 3. The reference count of an acquired thread state can be controlled. This
  1312. * can be handy to prevent cases where callbacks issued from an external
  1313. * thread would otherwise constantly construct and destroy thread state data
  1314. * structures.
  1315. *
  1316. * See the Python bindings of NanoGUI (http://github.com/wjakob/nanogui) for an
  1317. * example which uses features 2 and 3 to migrate the Python thread of
  1318. * execution to another thread (to run the event loop on the original thread,
  1319. * in this case).
  1320. */
  1321. class gil_scoped_acquire {
  1322. public:
  1323. PYBIND11_NOINLINE gil_scoped_acquire() {
  1324. auto const &internals = detail::get_internals();
  1325. tstate = (PyThreadState *) PyThread_get_key_value(internals.tstate);
  1326. if (!tstate) {
  1327. tstate = PyThreadState_New(internals.istate);
  1328. #if !defined(NDEBUG)
  1329. if (!tstate)
  1330. pybind11_fail("scoped_acquire: could not create thread state!");
  1331. #endif
  1332. tstate->gilstate_counter = 0;
  1333. #if PY_MAJOR_VERSION < 3
  1334. PyThread_delete_key_value(internals.tstate);
  1335. #endif
  1336. PyThread_set_key_value(internals.tstate, tstate);
  1337. } else {
  1338. release = detail::get_thread_state_unchecked() != tstate;
  1339. }
  1340. if (release) {
  1341. /* Work around an annoying assertion in PyThreadState_Swap */
  1342. #if defined(Py_DEBUG)
  1343. PyInterpreterState *interp = tstate->interp;
  1344. tstate->interp = nullptr;
  1345. #endif
  1346. PyEval_AcquireThread(tstate);
  1347. #if defined(Py_DEBUG)
  1348. tstate->interp = interp;
  1349. #endif
  1350. }
  1351. inc_ref();
  1352. }
  1353. void inc_ref() {
  1354. ++tstate->gilstate_counter;
  1355. }
  1356. PYBIND11_NOINLINE void dec_ref() {
  1357. --tstate->gilstate_counter;
  1358. #if !defined(NDEBUG)
  1359. if (detail::get_thread_state_unchecked() != tstate)
  1360. pybind11_fail("scoped_acquire::dec_ref(): thread state must be current!");
  1361. if (tstate->gilstate_counter < 0)
  1362. pybind11_fail("scoped_acquire::dec_ref(): reference count underflow!");
  1363. #endif
  1364. if (tstate->gilstate_counter == 0) {
  1365. #if !defined(NDEBUG)
  1366. if (!release)
  1367. pybind11_fail("scoped_acquire::dec_ref(): internal error!");
  1368. #endif
  1369. PyThreadState_Clear(tstate);
  1370. PyThreadState_DeleteCurrent();
  1371. PyThread_delete_key_value(detail::get_internals().tstate);
  1372. release = false;
  1373. }
  1374. }
  1375. PYBIND11_NOINLINE ~gil_scoped_acquire() {
  1376. dec_ref();
  1377. if (release)
  1378. PyEval_SaveThread();
  1379. }
  1380. private:
  1381. PyThreadState *tstate = nullptr;
  1382. bool release = true;
  1383. };
  1384. class gil_scoped_release {
  1385. public:
  1386. explicit gil_scoped_release(bool disassoc = false) : disassoc(disassoc) {
  1387. tstate = PyEval_SaveThread();
  1388. if (disassoc) {
  1389. auto key = detail::get_internals().tstate;
  1390. #if PY_MAJOR_VERSION < 3
  1391. PyThread_delete_key_value(key);
  1392. #else
  1393. PyThread_set_key_value(key, nullptr);
  1394. #endif
  1395. }
  1396. }
  1397. ~gil_scoped_release() {
  1398. if (!tstate)
  1399. return;
  1400. PyEval_RestoreThread(tstate);
  1401. if (disassoc) {
  1402. auto key = detail::get_internals().tstate;
  1403. #if PY_MAJOR_VERSION < 3
  1404. PyThread_delete_key_value(key);
  1405. #endif
  1406. PyThread_set_key_value(key, tstate);
  1407. }
  1408. }
  1409. private:
  1410. PyThreadState *tstate;
  1411. bool disassoc;
  1412. };
  1413. #elif defined(PYPY_VERSION)
  1414. class gil_scoped_acquire {
  1415. PyGILState_STATE state;
  1416. public:
  1417. gil_scoped_acquire() { state = PyGILState_Ensure(); }
  1418. ~gil_scoped_acquire() { PyGILState_Release(state); }
  1419. };
  1420. class gil_scoped_release {
  1421. PyThreadState *state;
  1422. public:
  1423. gil_scoped_release() { state = PyEval_SaveThread(); }
  1424. ~gil_scoped_release() { PyEval_RestoreThread(state); }
  1425. };
  1426. #else
  1427. class gil_scoped_acquire { };
  1428. class gil_scoped_release { };
  1429. #endif
  1430. error_already_set::~error_already_set() {
  1431. if (value) {
  1432. gil_scoped_acquire gil;
  1433. clear();
  1434. }
  1435. }
  1436. inline function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
  1437. handle self = detail::get_object_handle(this_ptr, this_type);
  1438. if (!self)
  1439. return function();
  1440. handle type = self.get_type();
  1441. auto key = std::make_pair(type.ptr(), name);
  1442. /* Cache functions that aren't overloaded in Python to avoid
  1443. many costly Python dictionary lookups below */
  1444. auto &cache = detail::get_internals().inactive_overload_cache;
  1445. if (cache.find(key) != cache.end())
  1446. return function();
  1447. function overload = getattr(self, name, function());
  1448. if (overload.is_cpp_function()) {
  1449. cache.insert(key);
  1450. return function();
  1451. }
  1452. /* Don't call dispatch code if invoked from overridden function.
  1453. Unfortunately this doesn't work on PyPy. */
  1454. #if !defined(PYPY_VERSION)
  1455. PyFrameObject *frame = PyThreadState_Get()->frame;
  1456. if (frame && (std::string) str(frame->f_code->co_name) == name &&
  1457. frame->f_code->co_argcount > 0) {
  1458. PyFrame_FastToLocals(frame);
  1459. PyObject *self_caller = PyDict_GetItem(
  1460. frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
  1461. if (self_caller == self.ptr())
  1462. return function();
  1463. }
  1464. #else
  1465. /* PyPy currently doesn't provide a detailed cpyext emulation of
  1466. frame objects, so we have to emulate this using Python. This
  1467. is going to be slow..*/
  1468. dict d; d["self"] = self; d["name"] = pybind11::str(name);
  1469. PyObject *result = PyRun_String(
  1470. "import inspect\n"
  1471. "frame = inspect.currentframe()\n"
  1472. "if frame is not None:\n"
  1473. " frame = frame.f_back\n"
  1474. " if frame is not None and str(frame.f_code.co_name) == name and "
  1475. "frame.f_code.co_argcount > 0:\n"
  1476. " self_caller = frame.f_locals[frame.f_code.co_varnames[0]]\n"
  1477. " if self_caller == self:\n"
  1478. " self = None\n",
  1479. Py_file_input, d.ptr(), d.ptr());
  1480. if (result == nullptr)
  1481. throw error_already_set();
  1482. if ((handle) d["self"] == Py_None)
  1483. return function();
  1484. Py_DECREF(result);
  1485. #endif
  1486. return overload;
  1487. }
  1488. template <class T> function get_overload(const T *this_ptr, const char *name) {
  1489. auto tinfo = detail::get_type_info(typeid(T));
  1490. return tinfo ? get_type_overload(this_ptr, tinfo, name) : function();
  1491. }
  1492. #define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) { \
  1493. pybind11::gil_scoped_acquire gil; \
  1494. pybind11::function overload = pybind11::get_overload(static_cast<const cname *>(this), name); \
  1495. if (overload) { \
  1496. auto o = overload(__VA_ARGS__); \
  1497. if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
  1498. static pybind11::detail::overload_caster_t<ret_type> caster; \
  1499. return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
  1500. } \
  1501. else return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
  1502. } \
  1503. }
  1504. #define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
  1505. PYBIND11_OVERLOAD_INT(ret_type, cname, name, __VA_ARGS__) \
  1506. return cname::fn(__VA_ARGS__)
  1507. #define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
  1508. PYBIND11_OVERLOAD_INT(ret_type, cname, name, __VA_ARGS__) \
  1509. pybind11::pybind11_fail("Tried to call pure virtual function \"" #cname "::" name "\"");
  1510. #define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
  1511. PYBIND11_OVERLOAD_NAME(ret_type, cname, #fn, fn, __VA_ARGS__)
  1512. #define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
  1513. PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, #fn, fn, __VA_ARGS__)
  1514. NAMESPACE_END(pybind11)
  1515. #if defined(_MSC_VER)
  1516. # pragma warning(pop)
  1517. #elif defined(__INTEL_COMPILER)
  1518. /* Leave ignored warnings on */
  1519. #elif defined(__GNUG__) && !defined(__clang__)
  1520. # pragma GCC diagnostic pop
  1521. #endif