blob: ba3f8909bb37e2dd0d176b280195dcd7b8789b5f [file] [log] [blame]
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001/*
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02002 pybind11/pybind11.h: Main header file of the C++11 python binding generator library
Wenzel Jakob38bd7112015-07-05 20:05:44 +02003
4 Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch>
5
6 All rights reserved. Use of this source code is governed by a
7 BSD-style license that can be found in the LICENSE file.
8*/
9
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020010#pragma once
Wenzel Jakob38bd7112015-07-05 20:05:44 +020011
12#if defined(_MSC_VER)
13#pragma warning(push)
14#pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
15#pragma warning(disable: 4800) // warning C4800: 'int': forcing value to bool 'true' or 'false' (performance warning)
16#pragma warning(disable: 4996) // warning C4996: The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name
17#pragma warning(disable: 4100) // warning C4100: Unreferenced formal parameter
18#pragma warning(disable: 4512) // warning C4512: Assignment operator was implicitly defined as deleted
Wenzel Jakobcd5cda72015-08-03 12:17:54 +020019#elif defined(__GNUG__) and !defined(__clang__)
Wenzel Jakob281aa0e2015-07-30 15:29:00 +020020#pragma GCC diagnostic push
21#pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
22#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
23#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
Wenzel Jakob38bd7112015-07-05 20:05:44 +020024#endif
25
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020026#include "cast.h"
Wenzel Jakob38bd7112015-07-05 20:05:44 +020027
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020028NAMESPACE_BEGIN(pybind11)
Wenzel Jakob38bd7112015-07-05 20:05:44 +020029
Wenzel Jakob71867832015-07-29 17:43:52 +020030template <typename T> struct arg_t;
31
32/// Annotation for keyword arguments
33struct arg {
34 arg(const char *name) : name(name) { }
Wenzel Jakob54289302015-10-26 20:10:24 +010035 template <typename T> arg_t<T> operator=(const T &value);
Wenzel Jakob71867832015-07-29 17:43:52 +020036 const char *name;
37};
38
39/// Annotation for keyword arguments with default values
40template <typename T> struct arg_t : public arg {
Wenzel Jakob66c9a402016-01-17 22:36:36 +010041 arg_t(const char *name, const T &value, const char *descr = nullptr)
42 : arg(name), value(value), descr(descr) { }
Wenzel Jakob71867832015-07-29 17:43:52 +020043 T value;
Wenzel Jakob66c9a402016-01-17 22:36:36 +010044 const char *descr;
Wenzel Jakob71867832015-07-29 17:43:52 +020045};
Wenzel Jakob2ac50442016-01-17 22:36:35 +010046
Wenzel Jakob54289302015-10-26 20:10:24 +010047template <typename T> arg_t<T> arg::operator=(const T &value) { return arg_t<T>(name, value); }
Wenzel Jakob71867832015-07-29 17:43:52 +020048
49/// Annotation for methods
Wenzel Jakob54289302015-10-26 20:10:24 +010050struct is_method { PyObject *class_; is_method(object *o) : class_(o->ptr()) { } };
Wenzel Jakob71867832015-07-29 17:43:52 +020051
52/// Annotation for documentation
53struct doc { const char *value; doc(const char *value) : value(value) { } };
54
55/// Annotation for function names
56struct name { const char *value; name(const char *value) : value(value) { } };
57
58/// Annotation for function siblings
59struct sibling { PyObject *value; sibling(handle value) : value(value.ptr()) { } };
60
Wenzel Jakob5f218b32016-01-17 22:36:39 +010061/// Keep patient alive while nurse lives
62template <int Nurse, int Patient> struct keep_alive { };
63
64NAMESPACE_BEGIN(detail)
65template <typename... Args> struct process_dynamic;
66template <typename T> struct process_dynamic<T> {
67 static void precall(PyObject *) { }
68 static void postcall(PyObject *, PyObject *) { }
69};
70template <> struct process_dynamic<> : public process_dynamic<void> { };
71template <typename T, typename... Args> struct process_dynamic<T, Args...> {
72 static void precall(PyObject *arg) {
73 process_dynamic<T>::precall(arg);
74 process_dynamic<Args...>::precall(arg);
75 }
76 static void postcall(PyObject *arg, PyObject *ret) {
77 process_dynamic<T>::postcall(arg, ret);
78 process_dynamic<Args...>::postcall(arg, ret);
79 }
80};
81NAMESPACE_END(detail)
82
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020083/// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020084class cpp_function : public function {
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020085private:
Wenzel Jakob2ac50442016-01-17 22:36:35 +010086 /// Linked list of function overloads
Wenzel Jakob38bd7112015-07-05 20:05:44 +020087 struct function_entry {
Wenzel Jakob2ac50442016-01-17 22:36:35 +010088 /// Function name and user-specified documentation string
Wenzel Jakob66c9a402016-01-17 22:36:36 +010089 char *name = nullptr, *doc = nullptr; /* why no C++ strings? They generate heavier code.. */
90 /// Human-readable version of the function signature
91 char *signature = nullptr;
Wenzel Jakob2ac50442016-01-17 22:36:35 +010092 /// List of registered keyword arguments
Wenzel Jakob66c9a402016-01-17 22:36:36 +010093 std::vector<detail::argument_entry> args;
94 /// Pointer to lambda function which converts arguments and performs the actual call
Wenzel Jakob2ac50442016-01-17 22:36:35 +010095 PyObject * (*impl) (function_entry *, PyObject *, PyObject *) = nullptr;
96 /// Storage for the wrapped function pointer and captured data, if any
Wenzel Jakob281aa0e2015-07-30 15:29:00 +020097 void *data = nullptr;
Wenzel Jakob2ac50442016-01-17 22:36:35 +010098 /// Pointer to custom destructor for 'data' (if needed)
Wenzel Jakob66c9a402016-01-17 22:36:36 +010099 void (*free_data) (void *ptr) = nullptr;
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100100 /// Return value policy associated with this function
Wenzel Jakob71867832015-07-29 17:43:52 +0200101 return_value_policy policy = return_value_policy::automatic;
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100102 /// True if name == '__init__'
103 bool is_constructor = false;
104 /// Python method object
105 PyMethodDef *def = nullptr;
106 /// Pointer to class (if this is method)
Wenzel Jakob57082212015-09-04 23:42:12 +0200107 PyObject *class_ = nullptr;
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100108 /// Pointer to first registered function in overload chain
Wenzel Jakob71867832015-07-29 17:43:52 +0200109 PyObject *sibling = nullptr;
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100110 /// Pointer to next overload
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200111 function_entry *next = nullptr;
112 };
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200113
Wenzel Jakob57082212015-09-04 23:42:12 +0200114 function_entry *m_entry;
115
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200116 /// Picks a suitable return value converter from cast.h
117 template <typename T> using return_value_caster =
118 detail::type_caster<typename std::conditional<
Wenzel Jakob4177ed42016-01-17 22:36:38 +0100119 std::is_void<T>::value, detail::void_type, typename detail::intrinsic_type<T>::type>::type>;
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200120
121 /// Picks a suitable argument value converter from cast.h
Wenzel Jakob71867832015-07-29 17:43:52 +0200122 template <typename... T> using arg_value_caster =
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200123 detail::type_caster<typename std::tuple<T...>>;
Wenzel Jakob71867832015-07-29 17:43:52 +0200124
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100125 template <typename... T> static void process_static(const std::tuple<T...> &args, function_entry *entry) {
126 process_static(args, entry, typename detail::make_index_sequence<sizeof...(T)>::type());
Wenzel Jakob71867832015-07-29 17:43:52 +0200127 }
128
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100129 template <typename... T, size_t ... Index> static void process_static(const std::tuple<T...> &args,
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100130 function_entry *entry, detail::index_sequence<Index...>) {
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100131 int unused[] = { 0, (process_static(std::get<Index>(args), entry), 0)... };
Wenzel Jakob71867832015-07-29 17:43:52 +0200132 (void) unused;
133 }
134
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100135 template <int Nurse, int Patient>
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100136 static void process_static(const keep_alive<Nurse, Patient> &, function_entry *) { }
137 static void process_static(const char *doc, function_entry *entry) { entry->doc = (char *) doc; }
138 static void process_static(const pybind11::doc &d, function_entry *entry) { entry->doc = (char *) d.value; }
139 static void process_static(const pybind11::name &n, function_entry *entry) { entry->name = (char *) n.value; }
140 static void process_static(const pybind11::return_value_policy p, function_entry *entry) { entry->policy = p; }
141 static void process_static(const pybind11::sibling s, function_entry *entry) { entry->sibling = s.value; }
142 static void process_static(const pybind11::is_method &m, function_entry *entry) { entry->class_ = m.class_; }
143 static void process_static(const pybind11::arg &a, function_entry *entry) {
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100144 if (entry->class_ && entry->args.empty())
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100145 entry->args.emplace_back("self", nullptr, nullptr);
146 entry->args.emplace_back(a.name, nullptr, nullptr);
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200147 }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200148
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200149 template <typename T>
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100150 static void process_static(const pybind11::arg_t<T> &a, function_entry *entry) {
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100151 if (entry->class_ && entry->args.empty())
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100152 entry->args.emplace_back("self", nullptr, nullptr);
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200153
Wenzel Jakob4177ed42016-01-17 22:36:38 +0100154 PyObject *obj = detail::type_caster<typename detail::intrinsic_type<T>::type>::cast(
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200155 a.value, return_value_policy::automatic, nullptr);
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100156
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100157 if (obj == nullptr)
158 throw std::runtime_error("arg(): could not convert default keyword "
159 "argument into a Python object (type not "
160 "registered yet?)");
161
162 entry->args.emplace_back(a.name, a.descr, obj);
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200163 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200164public:
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200165 cpp_function() { }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200166
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200167 /// Vanilla function pointers
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100168 template <typename Return, typename... Args, typename... Extra>
169 cpp_function(Return (*f)(Args...), Extra&&... extra) {
170 using detail::descr;
Wenzel Jakob57082212015-09-04 23:42:12 +0200171 m_entry = new function_entry();
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100172 m_entry->data = (void *) f;
Wenzel Jakob71867832015-07-29 17:43:52 +0200173
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100174 typedef arg_value_caster<Args...> cast_in;
Wenzel Jakob71867832015-07-29 17:43:52 +0200175 typedef return_value_caster<Return> cast_out;
176
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100177 m_entry->impl = [](function_entry *entry, PyObject *pyArgs, PyObject *parent) -> PyObject * {
Wenzel Jakob71867832015-07-29 17:43:52 +0200178 cast_in args;
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100179 if (!args.load(pyArgs, true))
Wenzel Jakobb3ee3ea2015-10-04 15:17:34 +0200180 return (PyObject *) 1; /* Special return code: try next overload */
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100181 detail::process_dynamic<Extra...>::precall(pyArgs);
182 PyObject *result = cast_out::cast(args.template call<Return>((Return (*)(Args...)) entry->data), entry->policy, parent);
183 detail::process_dynamic<Extra...>::postcall(pyArgs, result);
184 return result;
Wenzel Jakob71867832015-07-29 17:43:52 +0200185 };
186
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100187 process_static(std::make_tuple(std::forward<Extra>(extra)...), m_entry);
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100188 PYBIND11_DESCR signature = cast_in::name() + detail::_(" -> ") + cast_out::name();
189 initialize(signature.text(), signature.types(), sizeof...(Args));
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200190 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200191
192 /// Delegating helper constructor to deal with lambda functions
Wenzel Jakob71867832015-07-29 17:43:52 +0200193 template <typename Func, typename... Extra> cpp_function(Func &&f, Extra&&... extra) {
194 initialize(std::forward<Func>(f),
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200195 (typename detail::remove_class<decltype(
Wenzel Jakob71867832015-07-29 17:43:52 +0200196 &std::remove_reference<Func>::type::operator())>::type *) nullptr,
197 std::forward<Extra>(extra)...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200198 }
199
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200200 /// Class methods (non-const)
Wenzel Jakob71867832015-07-29 17:43:52 +0200201 template <typename Return, typename Class, typename... Arg, typename... Extra> cpp_function(
202 Return (Class::*f)(Arg...), Extra&&... extra) {
203 initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
204 (Return (*) (Class *, Arg...)) nullptr, std::forward<Extra>(extra)...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200205 }
206
207 /// Class methods (const)
Wenzel Jakob71867832015-07-29 17:43:52 +0200208 template <typename Return, typename Class, typename... Arg, typename... Extra> cpp_function(
209 Return (Class::*f)(Arg...) const, Extra&&... extra) {
210 initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
211 (Return (*)(const Class *, Arg ...)) nullptr, std::forward<Extra>(extra)...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200212 }
213
Wenzel Jakob57082212015-09-04 23:42:12 +0200214 /// Return the function name
215 const char *name() const { return m_entry->name; }
216
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200217private:
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200218 /// Functors, lambda functions, etc.
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100219 template <typename Func, typename Return, typename... Args, typename... Extra>
220 void initialize(Func &&f, Return (*)(Args...), Extra&&... extra) {
221 using detail::descr;
222
223 struct capture { typename std::remove_reference<Func>::type f; };
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200224
Wenzel Jakob57082212015-09-04 23:42:12 +0200225 m_entry = new function_entry();
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100226 m_entry->data = new capture { std::forward<Func>(f) };
Wenzel Jakob71867832015-07-29 17:43:52 +0200227
Wenzel Jakob19208fe2015-10-13 17:37:25 +0200228 if (!std::is_trivially_destructible<Func>::value)
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100229 m_entry->free_data = [](void *ptr) { delete (capture *) ptr; };
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100230 else
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100231 m_entry->free_data = operator delete;
Wenzel Jakob19208fe2015-10-13 17:37:25 +0200232
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100233 typedef arg_value_caster<Args...> cast_in;
Wenzel Jakob71867832015-07-29 17:43:52 +0200234 typedef return_value_caster<Return> cast_out;
235
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100236 m_entry->impl = [](function_entry *entry, PyObject *pyArgs, PyObject *parent) -> PyObject *{
Wenzel Jakob71867832015-07-29 17:43:52 +0200237 cast_in args;
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100238 if (!args.load(pyArgs, true))
Wenzel Jakobb3ee3ea2015-10-04 15:17:34 +0200239 return (PyObject *) 1; /* Special return code: try next overload */
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100240 detail::process_dynamic<Extra...>::precall(pyArgs);
241 PyObject *result = cast_out::cast(args.template call<Return>(((capture *) entry->data)->f), entry->policy, parent);
242 detail::process_dynamic<Extra...>::postcall(pyArgs, result);
243 return result;
Wenzel Jakob71867832015-07-29 17:43:52 +0200244 };
245
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100246 process_static(std::make_tuple(std::forward<Extra>(extra)...), m_entry);
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100247 PYBIND11_DESCR signature = cast_in::name() + detail::_(" -> ") + cast_out::name();
248 initialize(signature.text(), signature.types(), sizeof...(Args));
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200249 }
250
Wenzel Jakob52573302015-09-14 16:38:47 +0200251 static PyObject *dispatcher(PyObject *self, PyObject *args, PyObject *kwargs) {
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100252 function_entry *overloads = (function_entry *) PyCapsule_GetPointer(self, nullptr),
253 *it = overloads;
254 int nargs = (int) PyTuple_Size(args),
255 nkwargs = kwargs ? (int) PyDict_Size(kwargs) : 0;
256 PyObject *parent = nargs > 0 ? PyTuple_GetItem(args, 0) : nullptr,
257 *result = (PyObject *) 1;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200258 try {
Wenzel Jakobb3ee3ea2015-10-04 15:17:34 +0200259 for (; it != nullptr; it = it->next) {
Wenzel Jakobf4671f62016-01-17 22:36:36 +0100260 object args_(args, true);
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100261 int kwargs_consumed = 0;
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200262
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100263 if (nargs < (int) it->args.size()) {
Wenzel Jakobf4671f62016-01-17 22:36:36 +0100264 args_ = object(PyTuple_New(it->args.size()), false);
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100265 for (int i = 0; i < nargs; ++i) {
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200266 PyObject *item = PyTuple_GET_ITEM(args, i);
267 Py_INCREF(item);
Wenzel Jakobf4671f62016-01-17 22:36:36 +0100268 PyTuple_SET_ITEM(args_.ptr(), i, item);
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200269 }
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100270 int arg_ctr = 0;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100271 for (auto const &it2 : it->args) {
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100272 int index = arg_ctr++;
Wenzel Jakobf4671f62016-01-17 22:36:36 +0100273 if (PyTuple_GET_ITEM(args_.ptr(), index))
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100274 continue;
275 PyObject *value = nullptr;
276 if (kwargs)
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100277 value = PyDict_GetItemString(kwargs, it2.name);
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100278 if (value)
279 kwargs_consumed++;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100280 else if (it2.value)
281 value = it2.value;
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100282 if (value) {
283 Py_INCREF(value);
Wenzel Jakobf4671f62016-01-17 22:36:36 +0100284 PyTuple_SET_ITEM(args_.ptr(), index, value);
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100285 } else {
286 kwargs_consumed = -1; /* definite failure */
287 break;
288 }
289 }
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200290 }
291
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100292 if (kwargs_consumed == nkwargs)
Wenzel Jakobf4671f62016-01-17 22:36:36 +0100293 result = it->impl(it, args_.ptr(), parent);
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200294
Wenzel Jakobb3ee3ea2015-10-04 15:17:34 +0200295 if (result != (PyObject *) 1)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200296 break;
297 }
Jonas Adler2b9fdbe2015-12-15 11:27:19 +0100298 } catch (const error_already_set &) { return nullptr;
299 } catch (const index_error &e) { PyErr_SetString(PyExc_IndexError, e.what()); return nullptr;
300 } catch (const stop_iteration &e) { PyErr_SetString(PyExc_StopIteration, e.what()); return nullptr;
301 } catch (const std::bad_alloc &e) { PyErr_SetString(PyExc_MemoryError, e.what()); return nullptr;
302 } catch (const std::domain_error &e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr;
303 } catch (const std::invalid_argument &e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr;
304 } catch (const std::length_error &e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr;
305 } catch (const std::out_of_range &e) { PyErr_SetString(PyExc_IndexError, e.what()); return nullptr;
306 } catch (const std::range_error &e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr;
307 } catch (const std::exception &e) { PyErr_SetString(PyExc_RuntimeError, e.what()); return nullptr;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200308 } catch (...) {
309 PyErr_SetString(PyExc_RuntimeError, "Caught an unknown exception!");
310 return nullptr;
311 }
Wenzel Jakobb3ee3ea2015-10-04 15:17:34 +0200312 if (result == (PyObject *) 1) {
313 std::string msg = "Incompatible function arguments. The "
314 "following argument types are supported:\n";
315 int ctr = 0;
Wenzel Jakobd2a902b2015-10-04 20:24:20 +0200316 for (function_entry *it2 = overloads; it2 != nullptr; it2 = it2->next) {
Wenzel Jakobb3ee3ea2015-10-04 15:17:34 +0200317 msg += " "+ std::to_string(++ctr) + ". ";
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100318 msg += it2->signature;
Wenzel Jakobb3ee3ea2015-10-04 15:17:34 +0200319 msg += "\n";
320 }
321 PyErr_SetString(PyExc_TypeError, msg.c_str());
322 return nullptr;
323 } else if (result == nullptr) {
324 std::string msg = "Unable to convert function return value to a "
325 "Python type! The signature was\n\t";
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100326 msg += it->signature;
Wenzel Jakobb3ee3ea2015-10-04 15:17:34 +0200327 PyErr_SetString(PyExc_TypeError, msg.c_str());
328 return nullptr;
329 } else {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200330 if (overloads->is_constructor) {
331 PyObject *inst = PyTuple_GetItem(args, 0);
332 const detail::type_info *type_info =
333 capsule(PyObject_GetAttrString((PyObject *) Py_TYPE(inst),
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200334 const_cast<char *>("__pybind11__")), false);
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100335 type_info->init_holder(inst, nullptr);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200336 }
337 return result;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200338 }
339 }
340
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200341 static void destruct(function_entry *entry) {
342 while (entry) {
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200343 function_entry *next = entry->next;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100344 if (entry->free_data)
345 entry->free_data(entry->data);
346 std::free((char *) entry->name);
347 std::free((char *) entry->doc);
348 std::free((char *) entry->signature);
349 for (auto &arg: entry->args) {
350 std::free((char *) arg.name);
351 std::free((char *) arg.descr);
352 Py_XDECREF(arg.value);
353 }
Wenzel Jakob95d18692016-01-17 22:36:40 +0100354 if (entry->def) {
355 free((char *) entry->def->ml_doc);
356 delete entry->def;
357 }
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200358 delete entry;
359 entry = next;
360 }
361 }
362
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100363 void initialize(const char *text, const std::type_info * const * types, int args) {
364 /* Create copies of all referenced C-style strings */
365 m_entry->name = strdup(m_entry->name ? m_entry->name : "");
366 if (m_entry->doc) m_entry->doc = strdup(m_entry->doc);
367 for (auto &a: m_entry->args) {
368 if (a.name)
369 a.name = strdup(a.name);
370 if (a.descr)
371 a.descr = strdup(a.descr);
372 else if (a.value)
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100373 a.descr = strdup(((std::string) ((object) handle(a.value).attr("__repr__")).call().str()).c_str());
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100374 }
375 auto const &registered_types = detail::get_internals().registered_types;
376
377 /* Generate a proper function signature */
378 std::string signature;
379 size_t type_depth = 0, char_index = 0, type_index = 0, arg_index = 0;
380 while (true) {
381 char c = text[char_index++];
382 if (c == '\0')
383 break;
384
385 if (c == '{') {
386 if (type_depth == 1 && arg_index < m_entry->args.size()) {
387 signature += m_entry->args[arg_index].name;
388 signature += " : ";
389 }
390 ++type_depth;
391 } else if (c == '}') {
392 --type_depth;
393 if (type_depth == 1 && arg_index < m_entry->args.size()) {
394 if (m_entry->args[arg_index].descr) {
395 signature += " = ";
396 signature += m_entry->args[arg_index].descr;
397 }
398 arg_index++;
399 }
400 } else if (c == '%') {
401 const std::type_info *t = types[type_index++];
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100402 if (!t)
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100403 throw std::runtime_error("Internal error while parsing type signature (1)");
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100404 auto it = registered_types.find(t);
405 if (it != registered_types.end()) {
406 signature += it->second.type->tp_name;
407 } else {
408 std::string tname(t->name());
409 detail::clean_type_id(tname);
410 signature += tname;
411 }
412 } else {
413 signature += c;
414 }
415 }
Wenzel Jakob95d18692016-01-17 22:36:40 +0100416 if (type_depth != 0 || types[type_index] != nullptr)
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100417 throw std::runtime_error("Internal error while parsing type signature (2)");
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100418
419 #if !defined(PYBIND11_CPP14)
420 delete[] types;
421 delete[] text;
422 #endif
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200423
Wenzel Jakob57082212015-09-04 23:42:12 +0200424#if PY_MAJOR_VERSION < 3
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100425 if (strcmp(m_entry->name, "__next__") == 0) {
426 free(m_entry->name);
427 m_entry->name = strdup("next");
428 }
Wenzel Jakob57082212015-09-04 23:42:12 +0200429#endif
430
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100431 if (!m_entry->args.empty() && (int) m_entry->args.size() != args)
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200432 throw std::runtime_error(
Wenzel Jakob57082212015-09-04 23:42:12 +0200433 "cpp_function(): function \"" + std::string(m_entry->name) + "\" takes " +
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100434 std::to_string(args) + " arguments, but " + std::to_string(m_entry->args.size()) +
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200435 " pybind11::arg entries were specified!");
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200436
Wenzel Jakob57082212015-09-04 23:42:12 +0200437 m_entry->is_constructor = !strcmp(m_entry->name, "__init__");
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100438 m_entry->signature = strdup(signature.c_str());
439 m_entry->args.shrink_to_fit();
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200440
Wenzel Jakob57082212015-09-04 23:42:12 +0200441#if PY_MAJOR_VERSION < 3
442 if (m_entry->sibling && PyMethod_Check(m_entry->sibling))
443 m_entry->sibling = PyMethod_GET_FUNCTION(m_entry->sibling);
444#endif
445
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200446 function_entry *s_entry = nullptr, *entry = m_entry;
447 if (m_entry->sibling && PyCFunction_Check(m_entry->sibling)) {
448 capsule entry_capsule(PyCFunction_GetSelf(m_entry->sibling), true);
449 s_entry = (function_entry *) entry_capsule;
450 if (s_entry->class_ != m_entry->class_)
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100451 s_entry = nullptr; /* Overridden method, don't append to parent class overloads */
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200452 }
453
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100454 if (!s_entry) { /* No existing overload was found, create a function object */
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200455 m_entry->def = new PyMethodDef();
456 memset(m_entry->def, 0, sizeof(PyMethodDef));
457 m_entry->def->ml_name = m_entry->name;
458 m_entry->def->ml_meth = reinterpret_cast<PyCFunction>(*dispatcher);
459 m_entry->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
460 capsule entry_capsule(m_entry, [](PyObject *o) { destruct((function_entry *) PyCapsule_GetPointer(o, nullptr)); });
461 m_ptr = PyCFunction_New(m_entry->def, entry_capsule.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200462 if (!m_ptr)
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200463 throw std::runtime_error("cpp_function::cpp_function(): Could not allocate function object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200464 } else {
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200465 m_ptr = m_entry->sibling;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200466 inc_ref();
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200467 entry = s_entry;
468 while (s_entry->next)
469 s_entry = s_entry->next;
470 s_entry->next = m_entry;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200471 }
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200472
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200473 std::string signatures;
Wenzel Jakob71867832015-07-29 17:43:52 +0200474 int index = 0;
475 function_entry *it = entry;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100476 while (it) { /* Create pydoc entry including all function signatures and docstrings of the overload chain */
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200477 if (s_entry)
Wenzel Jakob71867832015-07-29 17:43:52 +0200478 signatures += std::to_string(++index) + ". ";
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100479 signatures += "Signature : ";
480 signatures += it->signature;
481 signatures += "\n";
482 if (it->doc && strlen(it->doc) > 0) {
483 signatures += "\n";
484 signatures += it->doc;
485 signatures += "\n";
486 }
Wenzel Jakob71867832015-07-29 17:43:52 +0200487 if (it->next)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200488 signatures += "\n";
Wenzel Jakob71867832015-07-29 17:43:52 +0200489 it = it->next;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200490 }
491 PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
492 if (func->m_ml->ml_doc)
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100493 free((char *) func->m_ml->ml_doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200494 func->m_ml->ml_doc = strdup(signatures.c_str());
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100495 if (entry->class_) {
Wenzel Jakob57082212015-09-04 23:42:12 +0200496#if PY_MAJOR_VERSION >= 3
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200497 m_ptr = PyInstanceMethod_New(m_ptr);
Wenzel Jakob57082212015-09-04 23:42:12 +0200498#else
499 m_ptr = PyMethod_New(m_ptr, nullptr, entry->class_);
500#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200501 if (!m_ptr)
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200502 throw std::runtime_error("cpp_function::cpp_function(): Could not allocate instance method object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200503 Py_DECREF(func);
504 }
505 }
506};
507
508class module : public object {
509public:
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200510 PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200511
512 module(const char *name, const char *doc = nullptr) {
Wenzel Jakob57082212015-09-04 23:42:12 +0200513#if PY_MAJOR_VERSION >= 3
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200514 PyModuleDef *def = new PyModuleDef();
515 memset(def, 0, sizeof(PyModuleDef));
516 def->m_name = name;
517 def->m_doc = doc;
518 def->m_size = -1;
519 Py_INCREF(def);
520 m_ptr = PyModule_Create(def);
Wenzel Jakob57082212015-09-04 23:42:12 +0200521#else
522 m_ptr = Py_InitModule3(name, nullptr, doc);
523#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200524 if (m_ptr == nullptr)
525 throw std::runtime_error("Internal error in module::module()");
526 inc_ref();
527 }
528
Wenzel Jakob71867832015-07-29 17:43:52 +0200529 template <typename Func, typename... Extra>
530 module &def(const char *name_, Func &&f, Extra&& ... extra) {
531 cpp_function func(std::forward<Func>(f), name(name_),
532 sibling((handle) attr(name_)), std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200533 func.inc_ref(); /* The following line steals a reference to 'func' */
Wenzel Jakob71867832015-07-29 17:43:52 +0200534 PyModule_AddObject(ptr(), name_, func.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200535 return *this;
536 }
537
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200538 module def_submodule(const char *name, const char *doc = nullptr) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200539 std::string full_name = std::string(PyModule_GetName(m_ptr))
540 + std::string(".") + std::string(name);
541 module result(PyImport_AddModule(full_name.c_str()), true);
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200542 if (doc)
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200543 result.attr("__doc__") = pybind11::str(doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200544 attr(name) = result;
545 return result;
546 }
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200547
548 static module import(const char *name) {
Wenzel Jakobdd57a342015-12-26 14:04:52 +0100549 PyObject *obj = PyImport_ImportModule(name);
550 if (!obj)
551 throw std::runtime_error("Module \"" + std::string(name) + "\" not found!");
552 return module(obj, false);
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200553 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200554};
555
556NAMESPACE_BEGIN(detail)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200557/// Basic support for creating new Python heap types
558class custom_type : public object {
559public:
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200560 PYBIND11_OBJECT_DEFAULT(custom_type, object, PyType_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200561
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200562 custom_type(object &scope, const char *name_, const std::type_info *tinfo,
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200563 size_t type_size, size_t instance_size,
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100564 void (*init_holder)(PyObject *, const void *), const destructor &dealloc,
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200565 PyObject *parent, const char *doc) {
566 PyHeapTypeObject *type = (PyHeapTypeObject*) PyType_Type.tp_alloc(&PyType_Type, 0);
Wenzel Jakob57082212015-09-04 23:42:12 +0200567#if PY_MAJOR_VERSION >= 3
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200568 PyObject *name = PyUnicode_FromString(name_);
Wenzel Jakob57082212015-09-04 23:42:12 +0200569#else
570 PyObject *name = PyString_FromString(name_);
571#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200572 if (type == nullptr || name == nullptr)
573 throw std::runtime_error("Internal error in custom_type::custom_type()");
574 Py_INCREF(name);
575 std::string full_name(name_);
576
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200577 pybind11::str scope_name = (object) scope.attr("__name__"),
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200578 module_name = (object) scope.attr("__module__");
579
580 if (scope_name.check())
581 full_name = std::string(scope_name) + "." + full_name;
582 if (module_name.check())
583 full_name = std::string(module_name) + "." + full_name;
584
Wenzel Jakob57082212015-09-04 23:42:12 +0200585 type->ht_name = name;
586#if PY_MAJOR_VERSION >= 3
587 type->ht_qualname = name;
588#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200589 type->ht_type.tp_name = strdup(full_name.c_str());
590 type->ht_type.tp_basicsize = instance_size;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200591 type->ht_type.tp_init = (initproc) init;
592 type->ht_type.tp_new = (newfunc) new_instance;
593 type->ht_type.tp_dealloc = dealloc;
594 type->ht_type.tp_flags |=
595 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
596 type->ht_type.tp_flags &= ~Py_TPFLAGS_HAVE_GC;
Wenzel Jakob57082212015-09-04 23:42:12 +0200597#if PY_MAJOR_VERSION < 3
598 type->ht_type.tp_flags |= Py_TPFLAGS_CHECKTYPES;
599#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200600 type->ht_type.tp_as_number = &type->as_number;
601 type->ht_type.tp_as_sequence = &type->as_sequence;
602 type->ht_type.tp_as_mapping = &type->as_mapping;
603 type->ht_type.tp_base = (PyTypeObject *) parent;
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100604 type->ht_type.tp_weaklistoffset = offsetof(instance<void>, weakrefs);
605
Wenzel Jakob5116b022015-09-05 02:09:17 +0200606 if (doc) {
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100607 size_t size = strlen(doc) + 1;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100608 type->ht_type.tp_doc = (char *) PyObject_MALLOC(size);
Wenzel Jakob5116b022015-09-05 02:09:17 +0200609 memcpy((void *) type->ht_type.tp_doc, doc, size);
610 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200611 Py_XINCREF(parent);
612
613 if (PyType_Ready(&type->ht_type) < 0)
614 throw std::runtime_error("Internal error in custom_type::custom_type()");
615 m_ptr = (PyObject *) type;
616
617 /* Needed by pydoc */
Wenzel Jakob04358b02015-10-01 16:45:28 +0200618 attr("__module__") = scope_name;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200619
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100620 auto &registered_types = get_internals().registered_types;
621 auto &type_info = registered_types[tinfo];
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200622 type_info.type = (PyTypeObject *) m_ptr;
623 type_info.type_size = type_size;
624 type_info.init_holder = init_holder;
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200625 attr("__pybind11__") = capsule(&type_info);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200626
627 scope.attr(name) = *this;
628 }
629
630protected:
631 /* Allocate a metaclass on demand (for static properties) */
632 handle metaclass() {
633 auto &ht_type = ((PyHeapTypeObject *) m_ptr)->ht_type;
Wenzel Jakob57082212015-09-04 23:42:12 +0200634#if PY_MAJOR_VERSION >= 3
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200635 auto &ob_type = ht_type.ob_base.ob_base.ob_type;
Wenzel Jakob57082212015-09-04 23:42:12 +0200636#else
637 auto &ob_type = ht_type.ob_type;
638#endif
639
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200640 if (ob_type == &PyType_Type) {
641 std::string name_ = std::string(ht_type.tp_name) + "_meta";
642 PyHeapTypeObject *type = (PyHeapTypeObject*) PyType_Type.tp_alloc(&PyType_Type, 0);
643 PyObject *name = PyUnicode_FromString(name_.c_str());
644 if (type == nullptr || name == nullptr)
645 throw std::runtime_error("Internal error in custom_type::metaclass()");
646 Py_INCREF(name);
Wenzel Jakob57082212015-09-04 23:42:12 +0200647 type->ht_name = name;
648#if PY_MAJOR_VERSION >= 3
649 type->ht_qualname = name;
650#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200651 type->ht_type.tp_name = strdup(name_.c_str());
652 type->ht_type.tp_base = &PyType_Type;
653 type->ht_type.tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
654 type->ht_type.tp_flags &= ~Py_TPFLAGS_HAVE_GC;
655 if (PyType_Ready(&type->ht_type) < 0)
656 throw std::runtime_error("Internal error in custom_type::metaclass()");
657 ob_type = (PyTypeObject *) type;
658 Py_INCREF(type);
659 }
660 return handle((PyObject *) ob_type);
661 }
662
663 static int init(void *self, PyObject *, PyObject *) {
664 std::string msg = std::string(Py_TYPE(self)->tp_name) + ": No constructor defined!";
665 PyErr_SetString(PyExc_TypeError, msg.c_str());
666 return -1;
667 }
668
669 static PyObject *new_instance(PyTypeObject *type, PyObject *, PyObject *) {
670 const detail::type_info *type_info = capsule(
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200671 PyObject_GetAttrString((PyObject *) type, const_cast<char*>("__pybind11__")), false);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200672 instance<void> *self = (instance<void> *) PyType_GenericAlloc(type, 0);
673 self->value = ::operator new(type_info->type_size);
674 self->owned = true;
675 self->parent = nullptr;
676 self->constructed = false;
677 detail::get_internals().registered_instances[self->value] = (PyObject *) self;
678 return (PyObject *) self;
679 }
680
681 static void dealloc(instance<void> *self) {
682 if (self->value) {
683 bool dont_cache = self->parent && ((instance<void> *) self->parent)->value == self->value;
684 if (!dont_cache) { // avoid an issue with internal references matching their parent's address
685 auto &registered_instances = detail::get_internals().registered_instances;
686 auto it = registered_instances.find(self->value);
687 if (it == registered_instances.end())
688 throw std::runtime_error("Deallocating unregistered instance!");
689 registered_instances.erase(it);
690 }
691 Py_XDECREF(self->parent);
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100692 if (self->weakrefs)
693 PyObject_ClearWeakRefs((PyObject *) self);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200694 }
695 Py_TYPE(self)->tp_free((PyObject*) self);
696 }
697
Wenzel Jakob43398a82015-07-28 16:12:20 +0200698 void install_buffer_funcs(
699 buffer_info *(*get_buffer)(PyObject *, void *),
700 void *get_buffer_data) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200701 PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
702 type->ht_type.tp_as_buffer = &type->as_buffer;
Wenzel Jakob57082212015-09-04 23:42:12 +0200703#if PY_MAJOR_VERSION < 3
704 type->ht_type.tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
705#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200706 type->as_buffer.bf_getbuffer = getbuffer;
707 type->as_buffer.bf_releasebuffer = releasebuffer;
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200708 auto info = ((detail::type_info *) capsule(attr("__pybind11__")));
Wenzel Jakob43398a82015-07-28 16:12:20 +0200709 info->get_buffer = get_buffer;
710 info->get_buffer_data = get_buffer_data;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200711 }
712
713 static int getbuffer(PyObject *obj, Py_buffer *view, int flags) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200714 auto const &typeinfo = ((detail::type_info *) capsule(handle(obj).attr("__pybind11__")));
Wenzel Jakob43398a82015-07-28 16:12:20 +0200715
716 if (view == nullptr || obj == nullptr || !typeinfo || !typeinfo->get_buffer) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200717 PyErr_SetString(PyExc_BufferError, "Internal error");
718 return -1;
719 }
720 memset(view, 0, sizeof(Py_buffer));
Wenzel Jakob43398a82015-07-28 16:12:20 +0200721 buffer_info *info = typeinfo->get_buffer(obj, typeinfo->get_buffer_data);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200722 view->obj = obj;
723 view->ndim = 1;
724 view->internal = info;
725 view->buf = info->ptr;
726 view->itemsize = info->itemsize;
727 view->len = view->itemsize;
728 for (auto s : info->shape)
729 view->len *= s;
730 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
731 view->format = const_cast<char *>(info->format.c_str());
732 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
733 view->ndim = info->ndim;
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100734 view->strides = (ssize_t *) &info->strides[0];
735 view->shape = (ssize_t *) &info->shape[0];
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200736 }
737 Py_INCREF(view->obj);
738 return 0;
739 }
740
741 static void releasebuffer(PyObject *, Py_buffer *view) { delete (buffer_info *) view->internal; }
742};
Wenzel Jakob71867832015-07-29 17:43:52 +0200743
744/* Forward declarations */
745enum op_id : int;
746enum op_type : int;
747struct undefined_t;
748template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t> struct op_;
749template <typename... Args> struct init;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200750NAMESPACE_END(detail)
751
752template <typename type, typename holder_type = std::unique_ptr<type>> class class_ : public detail::custom_type {
753public:
754 typedef detail::instance<type, holder_type> instance_type;
755
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200756 PYBIND11_OBJECT(class_, detail::custom_type, PyType_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200757
758 class_(object &scope, const char *name, const char *doc = nullptr)
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200759 : detail::custom_type(scope, name, &typeid(type), sizeof(type),
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200760 sizeof(instance_type), init_holder, dealloc,
761 nullptr, doc) { }
762
763 class_(object &scope, const char *name, object &parent,
764 const char *doc = nullptr)
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200765 : detail::custom_type(scope, name, &typeid(type), sizeof(type),
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200766 sizeof(instance_type), init_holder, dealloc,
767 parent.ptr(), doc) { }
768
Wenzel Jakob71867832015-07-29 17:43:52 +0200769 template <typename Func, typename... Extra>
770 class_ &def(const char *name_, Func&& f, Extra&&... extra) {
Wenzel Jakob57082212015-09-04 23:42:12 +0200771 cpp_function cf(std::forward<Func>(f), name(name_),
772 sibling(attr(name_)), is_method(this),
773 std::forward<Extra>(extra)...);
774 attr(cf.name()) = cf;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200775 return *this;
776 }
777
Wenzel Jakob71867832015-07-29 17:43:52 +0200778 template <typename Func, typename... Extra> class_ &
779 def_static(const char *name_, Func f, Extra&&... extra) {
Wenzel Jakob57082212015-09-04 23:42:12 +0200780 cpp_function cf(std::forward<Func>(f), name(name_),
781 sibling(attr(name_)),
782 std::forward<Extra>(extra)...);
783 attr(cf.name()) = cf;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200784 return *this;
785 }
786
Wenzel Jakob71867832015-07-29 17:43:52 +0200787 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
788 class_ &def(const detail::op_<id, ot, L, R> &op, Extra&&... extra) {
789 op.template execute<type>(*this, std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200790 return *this;
791 }
792
Wenzel Jakob71867832015-07-29 17:43:52 +0200793 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
794 class_ & def_cast(const detail::op_<id, ot, L, R> &op, Extra&&... extra) {
795 op.template execute_cast<type>(*this, std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200796 return *this;
797 }
798
Wenzel Jakob71867832015-07-29 17:43:52 +0200799 template <typename... Args, typename... Extra>
800 class_ &def(const detail::init<Args...> &init, Extra&&... extra) {
801 init.template execute<type>(*this, std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200802 return *this;
803 }
804
Wenzel Jakob71867832015-07-29 17:43:52 +0200805 template <typename Func> class_& def_buffer(Func &&func) {
Wenzel Jakob43398a82015-07-28 16:12:20 +0200806 struct capture { Func func; };
807 capture *ptr = new capture { std::forward<Func>(func) };
808 install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200809 detail::type_caster<type> caster;
810 if (!caster.load(obj, false))
811 return nullptr;
Wenzel Jakob43398a82015-07-28 16:12:20 +0200812 return new buffer_info(((capture *) ptr)->func(caster));
813 }, ptr);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200814 return *this;
815 }
816
Wenzel Jakob71867832015-07-29 17:43:52 +0200817 template <typename C, typename D, typename... Extra>
818 class_ &def_readwrite(const char *name, D C::*pm, Extra&&... extra) {
819 cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; },
820 return_value_policy::reference_internal,
Wenzel Jakob57082212015-09-04 23:42:12 +0200821 is_method(this), extra...),
Wenzel Jakob71867832015-07-29 17:43:52 +0200822 fset([pm](C &c, const D &value) { c.*pm = value; },
Wenzel Jakob57082212015-09-04 23:42:12 +0200823 is_method(this), extra...);
Wenzel Jakob71867832015-07-29 17:43:52 +0200824 def_property(name, fget, fset);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200825 return *this;
826 }
827
Wenzel Jakob71867832015-07-29 17:43:52 +0200828 template <typename C, typename D, typename... Extra>
829 class_ &def_readonly(const char *name, const D C::*pm, Extra&& ...extra) {
830 cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; },
831 return_value_policy::reference_internal,
Wenzel Jakob57082212015-09-04 23:42:12 +0200832 is_method(this), std::forward<Extra>(extra)...);
Wenzel Jakob71867832015-07-29 17:43:52 +0200833 def_property_readonly(name, fget);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200834 return *this;
835 }
836
Wenzel Jakob71867832015-07-29 17:43:52 +0200837 template <typename D, typename... Extra>
838 class_ &def_readwrite_static(const char *name, D *pm, Extra&& ...extra) {
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200839 cpp_function fget([pm](object) -> const D &{ return *pm; }, nullptr,
Wenzel Jakob71867832015-07-29 17:43:52 +0200840 return_value_policy::reference_internal, extra...),
841 fset([pm](object, const D &value) { *pm = value; }, extra...);
842 def_property_static(name, fget, fset);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200843 return *this;
844 }
845
Wenzel Jakob71867832015-07-29 17:43:52 +0200846 template <typename D, typename... Extra>
847 class_ &def_readonly_static(const char *name, const D *pm, Extra&& ...extra) {
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200848 cpp_function fget([pm](object) -> const D &{ return *pm; }, nullptr,
Wenzel Jakob71867832015-07-29 17:43:52 +0200849 return_value_policy::reference_internal, std::forward<Extra>(extra)...);
850 def_property_readonly_static(name, fget);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200851 return *this;
852 }
853
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200854 class_ &def_property_readonly(const char *name, const cpp_function &fget, const char *doc = nullptr) {
855 def_property(name, fget, cpp_function(), doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200856 return *this;
857 }
858
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200859 class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const char *doc = nullptr) {
860 def_property_static(name, fget, cpp_function(), doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200861 return *this;
862 }
863
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200864 class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const char *doc = nullptr) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200865 object doc_obj = doc ? pybind11::str(doc) : (object) const_cast<cpp_function&>(fget).attr("__doc__");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200866 object property(
867 PyObject_CallFunction((PyObject *)&PyProperty_Type,
Wenzel Jakob71867832015-07-29 17:43:52 +0200868 const_cast<char *>("OOOO"), fget.ptr() ? fget.ptr() : Py_None,
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200869 fset.ptr() ? fset.ptr() : Py_None, Py_None, doc_obj.ptr()), false);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200870 attr(name) = property;
871 return *this;
872 }
873
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200874 class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const char *doc = nullptr) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200875 object doc_obj = doc ? pybind11::str(doc) : (object) const_cast<cpp_function&>(fget).attr("__doc__");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200876 object property(
877 PyObject_CallFunction((PyObject *)&PyProperty_Type,
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200878 const_cast<char *>("OOOs"), fget.ptr() ? fget.ptr() : Py_None,
879 fset.ptr() ? fset.ptr() : Py_None, Py_None, doc_obj.ptr()), false);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200880 metaclass().attr(name) = property;
881 return *this;
882 }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200883
884 template <typename target> class_ alias() {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200885 auto &instances = pybind11::detail::get_internals().registered_types;
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200886 instances[&typeid(target)] = instances[&typeid(type)];
887 return *this;
888 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200889private:
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100890 /// Initialize holder object, variant 1: object derives from enable_shared_from_this
891 template <typename T>
892 static void init_holder_helper(instance_type *inst, const holder_type * /* unused */, const std::enable_shared_from_this<T> * /* dummy */) {
Wenzel Jakob6e213c92015-11-24 23:05:58 +0100893 try {
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100894 new (&inst->holder) holder_type(inst->value->shared_from_this());
Wenzel Jakob6e213c92015-11-24 23:05:58 +0100895 } catch (const std::bad_weak_ptr &) {
896 new (&inst->holder) holder_type(inst->value);
897 }
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100898 }
899
900 /// Initialize holder object, variant 2: try to construct from existing holder object, if possible
901 template <typename T = holder_type,
902 typename std::enable_if<std::is_copy_constructible<T>::value, int>::type = 0>
903 static void init_holder_helper(instance_type *inst, const holder_type *holder_ptr, const void * /* dummy */) {
904 if (holder_ptr)
905 new (&inst->holder) holder_type(*holder_ptr);
906 else
907 new (&inst->holder) holder_type(inst->value);
908 }
909
910 /// Initialize holder object, variant 3: holder is not copy constructible (e.g. unique_ptr), always initialize from raw pointer
911 template <typename T = holder_type,
912 typename std::enable_if<!std::is_copy_constructible<T>::value, int>::type = 0>
913 static void init_holder_helper(instance_type *inst, const holder_type * /* unused */, const void * /* dummy */) {
914 new (&inst->holder) holder_type(inst->value);
915 }
916
917 /// Initialize holder object of an instance, possibly given a pointer to an existing holder
918 static void init_holder(PyObject *inst_, const void *holder_ptr) {
919 auto inst = (instance_type *) inst_;
920 init_holder_helper(inst, (const holder_type *) holder_ptr, inst->value);
Wenzel Jakob6e213c92015-11-24 23:05:58 +0100921 inst->constructed = true;
922 }
923
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200924 static void dealloc(PyObject *inst_) {
925 instance_type *inst = (instance_type *) inst_;
926 if (inst->owned) {
927 if (inst->constructed)
928 inst->holder.~holder_type();
929 else
930 ::operator delete(inst->value);
931 }
932 custom_type::dealloc((detail::instance<void> *) inst);
933 }
934};
935
936/// Binds C++ enumerations and enumeration classes to Python
937template <typename Type> class enum_ : public class_<Type> {
938public:
939 enum_(object &scope, const char *name, const char *doc = nullptr)
940 : class_<Type>(scope, name, doc), m_parent(scope) {
941 auto entries = new std::unordered_map<int, const char *>();
Wenzel Jakob8456a4d2015-10-13 02:42:20 +0200942 this->def("__repr__", [name, entries](Type value) -> std::string {
Wenzel Jakoba7500312015-08-29 02:08:32 +0200943 auto it = entries->find((int) value);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200944 return std::string(name) + "." +
945 ((it == entries->end()) ? std::string("???")
946 : std::string(it->second));
947 });
Wenzel Jakob69189222015-10-01 21:32:23 +0200948 this->def("__int__", [](Type value) { return (int) value; });
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200949 m_entries = entries;
950 }
951
952 /// Export enumeration entries into the parent scope
953 void export_values() {
954 PyObject *dict = ((PyTypeObject *) this->m_ptr)->tp_dict;
955 PyObject *key, *value;
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100956 ssize_t pos = 0;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200957 while (PyDict_Next(dict, &pos, &key, &value))
958 if (PyObject_IsInstance(value, this->m_ptr))
959 m_parent.attr(key) = value;
960 }
961
962 /// Add an enumeration entry
963 enum_& value(char const* name, Type value) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200964 this->attr(name) = pybind11::cast(value, return_value_policy::copy);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200965 (*m_entries)[(int) value] = name;
966 return *this;
967 }
968private:
969 std::unordered_map<int, const char *> *m_entries;
970 object &m_parent;
971};
972
973NAMESPACE_BEGIN(detail)
Wenzel Jakob71867832015-07-29 17:43:52 +0200974template <typename... Args> struct init {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200975 template <typename Base, typename Holder, typename... Extra> void execute(pybind11::class_<Base, Holder> &class_, Extra&&... extra) const {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200976 /// Function which calls a specific C++ in-place constructor
Wenzel Jakob71867832015-07-29 17:43:52 +0200977 class_.def("__init__", [](Base *instance, Args... args) { new (instance) Base(args...); }, std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200978 }
979};
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100980
981PYBIND11_NOINLINE inline void keep_alive_impl(int Nurse, int Patient, PyObject *arg, PyObject *ret) {
982 /* Clever approach based on weak references taken from Boost.Python */
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100983 handle nurse (Nurse > 0 ? PyTuple_GetItem(arg, Nurse - 1) : ret);
984 handle patient(Patient > 0 ? PyTuple_GetItem(arg, Patient - 1) : ret);
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100985
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100986 if (!nurse || !patient)
987 throw std::runtime_error("Could not activate keep_alive!");
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100988
989 cpp_function disable_lifesupport(
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100990 [patient](handle weakref) { patient.dec_ref(); weakref.dec_ref(); });
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100991
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100992 weakref wr(nurse, disable_lifesupport);
993 if (!wr)
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100994 throw std::runtime_error("Could not allocate weak reference!");
995
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100996 patient.inc_ref(); /* reference patient and leak the weak reference */
997 (void) wr.release();
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100998}
999
1000template <int Nurse, int Patient> struct process_dynamic<keep_alive<Nurse, Patient>> : public process_dynamic<void> {
1001 template <int N = Nurse, int P = Patient, typename std::enable_if<N != 0 && P != 0, int>::type = 0>
1002 static void precall(PyObject *arg) { keep_alive_impl(Nurse, Patient, arg, nullptr); }
1003 template <int N = Nurse, int P = Patient, typename std::enable_if<N != 0 && P != 0, int>::type = 0>
1004 static void postcall(PyObject *, PyObject *) { }
1005 template <int N = Nurse, int P = Patient, typename std::enable_if<N == 0 || P == 0, int>::type = 0>
1006 static void precall(PyObject *) { }
1007 template <int N = Nurse, int P = Patient, typename std::enable_if<N == 0 || P == 0, int>::type = 0>
1008 static void postcall(PyObject *arg, PyObject *ret) { keep_alive_impl(Nurse, Patient, arg, ret); }
1009};
1010
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001011NAMESPACE_END(detail)
1012
1013template <typename... Args> detail::init<Args...> init() { return detail::init<Args...>(); };
1014
1015template <typename InputType, typename OutputType> void implicitly_convertible() {
Wenzel Jakob2ac50442016-01-17 22:36:35 +01001016 auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001017 if (!detail::type_caster<InputType>().load(obj, false))
1018 return nullptr;
1019 tuple args(1);
1020 args[0] = obj;
1021 PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
1022 if (result == nullptr)
1023 PyErr_Clear();
1024 return result;
1025 };
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001026 auto & registered_types = detail::get_internals().registered_types;
Wenzel Jakobf5fae922015-08-24 15:31:24 +02001027 auto it = registered_types.find(&typeid(OutputType));
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001028 if (it == registered_types.end())
Wenzel Jakobf5fae922015-08-24 15:31:24 +02001029 throw std::runtime_error("implicitly_convertible: Unable to find type " + type_id<OutputType>());
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001030 it->second.implicit_conversions.push_back(implicit_caster);
1031}
1032
1033inline void init_threading() { PyEval_InitThreads(); }
1034
1035class gil_scoped_acquire {
1036 PyGILState_STATE state;
1037public:
1038 inline gil_scoped_acquire() { state = PyGILState_Ensure(); }
1039 inline ~gil_scoped_acquire() { PyGILState_Release(state); }
1040};
1041
1042class gil_scoped_release {
1043 PyThreadState *state;
1044public:
1045 inline gil_scoped_release() { state = PyEval_SaveThread(); }
1046 inline ~gil_scoped_release() { PyEval_RestoreThread(state); }
1047};
1048
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001049inline function get_overload(const void *this_ptr, const char *name) {
1050 handle py_object = detail::get_object_handle(this_ptr);
Wenzel Jakobac0fde92015-10-01 18:37:26 +02001051 if (!py_object)
1052 return function();
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001053 handle type = py_object.get_type();
1054 auto key = std::make_pair(type.ptr(), name);
1055
1056 /* Cache functions that aren't overloaded in python to avoid
1057 many costly dictionary lookups in Python */
1058 auto &cache = detail::get_internals().inactive_overload_cache;
1059 if (cache.find(key) != cache.end())
1060 return function();
1061
1062 function overload = (function) py_object.attr(name);
1063 if (overload.is_cpp_function()) {
1064 cache.insert(key);
1065 return function();
1066 }
Wenzel Jakob27e8e102016-01-17 22:36:37 +01001067
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001068 PyFrameObject *frame = PyThreadState_Get()->frame;
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02001069 pybind11::str caller = pybind11::handle(frame->f_code->co_name).str();
Wenzel Jakob27e8e102016-01-17 22:36:37 +01001070 if ((std::string) caller == name)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001071 return function();
1072 return overload;
1073}
1074
Wenzel Jakobb1b71402015-10-18 16:48:30 +02001075#define PYBIND11_OVERLOAD_INT(ret_type, class_name, name, ...) { \
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02001076 pybind11::gil_scoped_acquire gil; \
1077 pybind11::function overload = pybind11::get_overload(this, #name); \
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001078 if (overload) \
1079 return overload.call(__VA_ARGS__).cast<ret_type>(); }
1080
Wenzel Jakobb1b71402015-10-18 16:48:30 +02001081#define PYBIND11_OVERLOAD(ret_type, class_name, name, ...) \
1082 PYBIND11_OVERLOAD_INT(ret_type, class_name, name, __VA_ARGS__) \
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001083 return class_name::name(__VA_ARGS__)
1084
Wenzel Jakobb1b71402015-10-18 16:48:30 +02001085#define PYBIND11_OVERLOAD_PURE(ret_type, class_name, name, ...) \
1086 PYBIND11_OVERLOAD_INT(ret_type, class_name, name, __VA_ARGS__) \
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001087 throw std::runtime_error("Tried to call pure virtual function \"" #name "\"");
1088
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02001089NAMESPACE_END(pybind11)
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001090
1091#if defined(_MSC_VER)
1092#pragma warning(pop)
Wenzel Jakobcd5cda72015-08-03 12:17:54 +02001093#elif defined(__GNUG__) and !defined(__clang__)
Wenzel Jakob281aa0e2015-07-30 15:29:00 +02001094#pragma GCC diagnostic pop
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001095#endif
Wenzel Jakob281aa0e2015-07-30 15:29:00 +02001096