blob: 22044feeb9337b696384d01da1900145b6751e18 [file] [log] [blame]
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001/*
Wenzel Jakob48548ea2016-01-17 22:36:44 +01002 pybind11/pybind11.h: Main header file of the C++11 python
3 binding generator library
Wenzel Jakob38bd7112015-07-05 20:05:44 +02004
5 Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch>
6
7 All rights reserved. Use of this source code is governed by a
8 BSD-style license that can be found in the LICENSE file.
9*/
10
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020011#pragma once
Wenzel Jakob38bd7112015-07-05 20:05:44 +020012
13#if defined(_MSC_VER)
Wenzel Jakob48548ea2016-01-17 22:36:44 +010014# pragma warning(push)
15# pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
16# pragma warning(disable: 4800) // warning C4800: 'int': forcing value to bool 'true' or 'false' (performance warning)
17# pragma warning(disable: 4996) // warning C4996: The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name
18# pragma warning(disable: 4100) // warning C4100: Unreferenced formal parameter
19# pragma warning(disable: 4512) // warning C4512: Assignment operator was implicitly defined as deleted
Ben Pritchard70ee47d2016-02-18 13:06:43 -050020#elif defined(__ICC) || defined(__INTEL_COMPILER)
Ben Pritchard33f34302016-02-18 15:25:51 -050021# pragma warning(push)
Ben Pritchard70ee47d2016-02-18 13:06:43 -050022# pragma warning(disable:2196) // warning #2196: routine is both "inline" and "noinline"
Wenzel Jakobcd5cda72015-08-03 12:17:54 +020023#elif defined(__GNUG__) and !defined(__clang__)
Wenzel Jakob48548ea2016-01-17 22:36:44 +010024# 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"
Wenzel Jakob38bd7112015-07-05 20:05:44 +020028#endif
29
Wenzel Jakob48548ea2016-01-17 22:36:44 +010030#include "attr.h"
Wenzel Jakob38bd7112015-07-05 20:05:44 +020031
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020032NAMESPACE_BEGIN(pybind11)
Wenzel Jakob38bd7112015-07-05 20:05:44 +020033
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020034/// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020035class cpp_function : public function {
Wenzel Jakobd561cb02016-01-17 22:36:41 +010036protected:
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020037 /// Picks a suitable return value converter from cast.h
38 template <typename T> using return_value_caster =
39 detail::type_caster<typename std::conditional<
Wenzel Jakob4177ed42016-01-17 22:36:38 +010040 std::is_void<T>::value, detail::void_type, typename detail::intrinsic_type<T>::type>::type>;
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020041
42 /// Picks a suitable argument value converter from cast.h
Wenzel Jakob71867832015-07-29 17:43:52 +020043 template <typename... T> using arg_value_caster =
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020044 detail::type_caster<typename std::tuple<T...>>;
45public:
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020046 cpp_function() { }
Wenzel Jakob38bd7112015-07-05 20:05:44 +020047
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020048 /// Vanilla function pointers
Wenzel Jakob66c9a402016-01-17 22:36:36 +010049 template <typename Return, typename... Args, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +010050 cpp_function(Return (*f)(Args...), const Extra&... extra) {
51 auto rec = new detail::function_record();
52 rec->data = (void *) f;
Wenzel Jakob71867832015-07-29 17:43:52 +020053
Wenzel Jakob66c9a402016-01-17 22:36:36 +010054 typedef arg_value_caster<Args...> cast_in;
Wenzel Jakob71867832015-07-29 17:43:52 +020055 typedef return_value_caster<Return> cast_out;
56
Wenzel Jakobd561cb02016-01-17 22:36:41 +010057 /* Dispatch code which converts function arguments and performs the actual function call */
Wenzel Jakob48548ea2016-01-17 22:36:44 +010058 rec->impl = [](detail::function_record *rec, handle pyArgs, handle parent) -> handle {
Wenzel Jakob71867832015-07-29 17:43:52 +020059 cast_in args;
Wenzel Jakobd561cb02016-01-17 22:36:41 +010060
61 /* Try to cast the function arguments into the C++ domain */
Wenzel Jakob2ac50442016-01-17 22:36:35 +010062 if (!args.load(pyArgs, true))
Wenzel Jakobd561cb02016-01-17 22:36:41 +010063 return PYBIND11_TRY_NEXT_OVERLOAD;
64
Wenzel Jakob48548ea2016-01-17 22:36:44 +010065 /* Invoke call policy pre-call hook */
66 detail::process_attributes<Extra...>::precall(pyArgs);
Wenzel Jakobd561cb02016-01-17 22:36:41 +010067
68 /* Do the call and convert the return value back into the Python domain */
Wenzel Jakob48548ea2016-01-17 22:36:44 +010069 handle result = cast_out::cast(
70 args.template call<Return>((Return (*) (Args...)) rec->data),
71 rec->policy, parent);
Wenzel Jakobd561cb02016-01-17 22:36:41 +010072
Wenzel Jakob48548ea2016-01-17 22:36:44 +010073 /* Invoke call policy post-call hook */
74 detail::process_attributes<Extra...>::postcall(pyArgs, result);
75
Wenzel Jakob5f218b32016-01-17 22:36:39 +010076 return result;
Wenzel Jakob71867832015-07-29 17:43:52 +020077 };
78
Wenzel Jakob48548ea2016-01-17 22:36:44 +010079 /* Process any user-provided function attributes */
80 detail::process_attributes<Extra...>::init(extra..., rec);
Wenzel Jakobd561cb02016-01-17 22:36:41 +010081
82 /* Generate a readable signature describing the function's arguments and return value types */
Wenzel Jakob48548ea2016-01-17 22:36:44 +010083 using detail::descr;
Sylvain Corlay4c7bf9b2016-03-08 18:44:04 -050084 PYBIND11_DESCR signature = cast_in::name() + detail::_(" -> ") + cast_out::name();
Wenzel Jakobd561cb02016-01-17 22:36:41 +010085
86 /* Register the function with Python from generic (non-templated) code */
Wenzel Jakob48548ea2016-01-17 22:36:44 +010087 initialize(rec, signature.text(), signature.types(), sizeof...(Args));
Wenzel Jakob38bd7112015-07-05 20:05:44 +020088 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020089
90 /// Delegating helper constructor to deal with lambda functions
Wenzel Jakob48548ea2016-01-17 22:36:44 +010091 template <typename Func, typename... Extra> cpp_function(Func &&f, const Extra&... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +020092 initialize(std::forward<Func>(f),
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020093 (typename detail::remove_class<decltype(
Wenzel Jakob48548ea2016-01-17 22:36:44 +010094 &std::remove_reference<Func>::type::operator())>::type *) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020095 }
96
Wenzel Jakobd561cb02016-01-17 22:36:41 +010097 /// Delegating helper constructor to deal with class methods (non-const)
Wenzel Jakob71867832015-07-29 17:43:52 +020098 template <typename Return, typename Class, typename... Arg, typename... Extra> cpp_function(
Wenzel Jakob48548ea2016-01-17 22:36:44 +010099 Return (Class::*f)(Arg...), const Extra&... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +0200100 initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100101 (Return (*) (Class *, Arg...)) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200102 }
103
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100104 /// Delegating helper constructor to deal with class methods (const)
Wenzel Jakob71867832015-07-29 17:43:52 +0200105 template <typename Return, typename Class, typename... Arg, typename... Extra> cpp_function(
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100106 Return (Class::*f)(Arg...) const, const Extra&... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +0200107 initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100108 (Return (*)(const Class *, Arg ...)) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200109 }
110
Wenzel Jakob57082212015-09-04 23:42:12 +0200111 /// Return the function name
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100112 object name() const { return attr("__name__"); }
Wenzel Jakob57082212015-09-04 23:42:12 +0200113
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100114protected:
115 /// Special internal constructor for functors, lambda functions, etc.
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100116 template <typename Func, typename Return, typename... Args, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100117 void initialize(Func &&f, Return (*)(Args...), const Extra&... extra) {
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100118 struct capture { typename std::remove_reference<Func>::type f; };
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200119
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100120 /* Store the function including any extra state it might have (e.g. a lambda capture object) */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100121 auto rec = new detail::function_record();
122 rec->data = new capture { std::forward<Func>(f) };
Wenzel Jakob71867832015-07-29 17:43:52 +0200123
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100124 /* Create a cleanup handler, but only if we have to (less generated code) */
Wenzel Jakob19208fe2015-10-13 17:37:25 +0200125 if (!std::is_trivially_destructible<Func>::value)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100126 rec->free_data = [](void *ptr) { delete (capture *) ptr; };
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100127 else
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100128 rec->free_data = operator delete;
Wenzel Jakob19208fe2015-10-13 17:37:25 +0200129
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100130 typedef arg_value_caster<Args...> cast_in;
Wenzel Jakob71867832015-07-29 17:43:52 +0200131 typedef return_value_caster<Return> cast_out;
132
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100133 /* Dispatch code which converts function arguments and performs the actual function call */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100134 rec->impl = [](detail::function_record *rec, handle pyArgs, handle parent) -> handle {
Wenzel Jakob71867832015-07-29 17:43:52 +0200135 cast_in args;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100136
137 /* Try to cast the function arguments into the C++ domain */
Wenzel Jakob2ac50442016-01-17 22:36:35 +0100138 if (!args.load(pyArgs, true))
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100139 return PYBIND11_TRY_NEXT_OVERLOAD;
140
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100141 /* Invoke call policy pre-call hook */
142 detail::process_attributes<Extra...>::precall(pyArgs);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100143
144 /* Do the call and convert the return value back into the Python domain */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100145 handle result = cast_out::cast(
146 args.template call<Return>(((capture *) rec->data)->f),
147 rec->policy, parent);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100148
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100149 /* Invoke call policy post-call hook */
150 detail::process_attributes<Extra...>::postcall(pyArgs, result);
151
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100152 return result;
Wenzel Jakob71867832015-07-29 17:43:52 +0200153 };
154
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100155 /* Process any user-provided function attributes */
156 detail::process_attributes<Extra...>::init(extra..., rec);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100157
158 /* Generate a readable signature describing the function's arguments and return value types */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100159 using detail::descr;
Sylvain Corlay4c7bf9b2016-03-08 18:44:04 -0500160 PYBIND11_DESCR signature = cast_in::name() + detail::_(" -> ") + cast_out::name();
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100161
162 /* Register the function with Python from generic (non-templated) code */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100163 initialize(rec, signature.text(), signature.types(), sizeof...(Args));
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200164 }
165
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100166 /// Register a function call with Python (generic non-templated code goes here)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100167 void initialize(detail::function_record *rec, const char *text,
168 const std::type_info *const *types, int args) {
169
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100170 /* Create copies of all referenced C-style strings */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100171 rec->name = strdup(rec->name ? rec->name : "");
172 if (rec->doc) rec->doc = strdup(rec->doc);
173 for (auto &a: rec->args) {
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100174 if (a.name)
175 a.name = strdup(a.name);
176 if (a.descr)
177 a.descr = strdup(a.descr);
178 else if (a.value)
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100179 a.descr = strdup(((std::string) ((object) handle(a.value).attr("__repr__")).call().str()).c_str());
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100180 }
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100181 auto const &registered_types = detail::get_internals().registered_types_cpp;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100182
183 /* Generate a proper function signature */
184 std::string signature;
185 size_t type_depth = 0, char_index = 0, type_index = 0, arg_index = 0;
186 while (true) {
187 char c = text[char_index++];
188 if (c == '\0')
189 break;
190
191 if (c == '{') {
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100192 if (type_depth == 1 && arg_index < rec->args.size()) {
193 signature += rec->args[arg_index].name;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100194 signature += " : ";
195 }
196 ++type_depth;
197 } else if (c == '}') {
198 --type_depth;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100199 if (type_depth == 1 && arg_index < rec->args.size()) {
200 if (rec->args[arg_index].descr) {
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100201 signature += " = ";
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100202 signature += rec->args[arg_index].descr;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100203 }
204 arg_index++;
205 }
206 } else if (c == '%') {
207 const std::type_info *t = types[type_index++];
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100208 if (!t)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100209 pybind11_fail("Internal error while parsing type signature (1)");
Wenzel Jakobb6cf75d2016-01-29 11:39:32 +0100210 auto it = registered_types.find(std::type_index(*t));
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100211 if (it != registered_types.end()) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100212 signature += ((const detail::type_info *) it->second)->type->tp_name;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100213 } else {
214 std::string tname(t->name());
215 detail::clean_type_id(tname);
216 signature += tname;
217 }
218 } else {
219 signature += c;
220 }
221 }
Wenzel Jakob95d18692016-01-17 22:36:40 +0100222 if (type_depth != 0 || types[type_index] != nullptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100223 pybind11_fail("Internal error while parsing type signature (2)");
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100224
225 #if !defined(PYBIND11_CPP14)
226 delete[] types;
227 delete[] text;
228 #endif
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200229
Wenzel Jakob57082212015-09-04 23:42:12 +0200230#if PY_MAJOR_VERSION < 3
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100231 if (strcmp(rec->name, "__next__") == 0) {
232 std::free(rec->name);
233 rec->name = strdup("next");
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100234 }
Wenzel Jakob57082212015-09-04 23:42:12 +0200235#endif
236
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100237 if (!rec->args.empty() && (int) rec->args.size() != args)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100238 pybind11_fail(
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100239 "cpp_function(): function \"" + std::string(rec->name) + "\" takes " +
240 std::to_string(args) + " arguments, but " + std::to_string(rec->args.size()) +
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200241 " pybind11::arg entries were specified!");
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200242
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100243 rec->is_constructor = !strcmp(rec->name, "__init__");
244 rec->signature = strdup(signature.c_str());
245 rec->args.shrink_to_fit();
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200246
Wenzel Jakob57082212015-09-04 23:42:12 +0200247#if PY_MAJOR_VERSION < 3
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100248 if (rec->sibling && PyMethod_Check(rec->sibling.ptr()))
249 rec->sibling = PyMethod_GET_FUNCTION(rec->sibling.ptr());
Wenzel Jakob57082212015-09-04 23:42:12 +0200250#endif
251
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100252 detail::function_record *chain = nullptr, *chain_start = rec;
253 if (rec->sibling && PyCFunction_Check(rec->sibling.ptr())) {
254 capsule rec_capsule(PyCFunction_GetSelf(rec->sibling.ptr()), true);
255 chain = (detail::function_record *) rec_capsule;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100256 /* Never append a method to an overload chain of a parent class;
257 instead, hide the parent's overloads in this case */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100258 if (chain->class_ != rec->class_)
259 chain = nullptr;
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200260 }
261
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100262 if (!chain) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100263 /* No existing overload was found, create a new function object */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100264 rec->def = new PyMethodDef();
265 memset(rec->def, 0, sizeof(PyMethodDef));
266 rec->def->ml_name = rec->name;
267 rec->def->ml_meth = reinterpret_cast<PyCFunction>(*dispatcher);
268 rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
Wenzel Jakoba6501792016-02-04 23:02:07 +0100269
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100270 capsule rec_capsule(rec, [](PyObject *o) {
271 destruct((detail::function_record *) PyCapsule_GetPointer(o, nullptr));
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100272 });
Wenzel Jakoba6501792016-02-04 23:02:07 +0100273
274 object scope_module;
275 if (rec->scope) {
276 scope_module = (object) rec->scope.attr("__module__");
277 if (!scope_module)
278 scope_module = (object) rec->scope.attr("__name__");
279 }
280
281 m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200282 if (!m_ptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100283 pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200284 } else {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100285 /* Append at the end of the overload chain */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100286 m_ptr = rec->sibling.ptr();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200287 inc_ref();
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100288 chain_start = chain;
289 while (chain->next)
290 chain = chain->next;
291 chain->next = rec;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200292 }
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200293
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200294 std::string signatures;
Wenzel Jakob71867832015-07-29 17:43:52 +0200295 int index = 0;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100296 /* Create a nice pydoc rec including all signatures and
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100297 docstrings of the functions in the overload chain */
Sylvain Corlay0e04fdf2016-03-08 16:42:12 -0500298 if (chain) {
299 // First a generic signature
300 signatures += rec->name;
301 signatures += "(*args, **kwargs)\n";
302 signatures += "Overloaded function.\n\n";
303 }
304 // Then specific overload signatures
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100305 for (auto it = chain_start; it != nullptr; it = it->next) {
306 if (chain)
Wenzel Jakob71867832015-07-29 17:43:52 +0200307 signatures += std::to_string(++index) + ". ";
Sylvain Corlay13b22bf2016-02-28 21:23:39 -0500308 signatures += rec->name;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100309 signatures += it->signature;
310 signatures += "\n";
311 if (it->doc && strlen(it->doc) > 0) {
312 signatures += "\n";
Wenzel Jakob218b6ce2016-02-28 23:52:37 +0100313 signatures += it->doc;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100314 signatures += "\n";
315 }
Wenzel Jakob71867832015-07-29 17:43:52 +0200316 if (it->next)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200317 signatures += "\n";
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200318 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100319
320 /* Install docstring */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200321 PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
322 if (func->m_ml->ml_doc)
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100323 std::free((char *) func->m_ml->ml_doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200324 func->m_ml->ml_doc = strdup(signatures.c_str());
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100325
326 if (rec->class_) {
327 m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->class_.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200328 if (!m_ptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100329 pybind11_fail("cpp_function::cpp_function(): Could not allocate instance method object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200330 Py_DECREF(func);
331 }
332 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100333
334 /// When a cpp_function is GCed, release any memory allocated by pybind11
335 static void destruct(detail::function_record *rec) {
336 while (rec) {
337 detail::function_record *next = rec->next;
338 if (rec->free_data)
339 rec->free_data(rec->data);
340 std::free((char *) rec->name);
341 std::free((char *) rec->doc);
342 std::free((char *) rec->signature);
343 for (auto &arg: rec->args) {
344 std::free((char *) arg.name);
345 std::free((char *) arg.descr);
346 arg.value.dec_ref();
347 }
348 if (rec->def) {
349 std::free((char *) rec->def->ml_doc);
350 delete rec->def;
351 }
352 delete rec;
353 rec = next;
354 }
355 }
356
357 /// Main dispatch logic for calls to functions bound using pybind11
358 static PyObject *dispatcher(PyObject *self, PyObject *args, PyObject *kwargs) {
359 /* Iterator over the list of potentially admissible overloads */
360 detail::function_record *overloads = (detail::function_record *) PyCapsule_GetPointer(self, nullptr),
361 *it = overloads;
362
363 /* Need to know how many arguments + keyword arguments there are to pick the right overload */
364 int nargs = (int) PyTuple_Size(args),
365 nkwargs = kwargs ? (int) PyDict_Size(kwargs) : 0;
366
367 handle parent = nargs > 0 ? PyTuple_GetItem(args, 0) : nullptr,
368 result = PYBIND11_TRY_NEXT_OVERLOAD;
369 try {
370 for (; it != nullptr; it = it->next) {
371 tuple args_(args, true);
372 int kwargs_consumed = 0;
373
374 /* For each overload:
375 1. If the required list of arguments is longer than the
376 actually provided amount, create a copy of the argument
377 list and fill in any available keyword/default arguments.
378 2. Ensure that all keyword arguments were "consumed"
379 3. Call the function call dispatcher (function_record::impl)
380 */
381
382 if (nargs < (int) it->args.size()) {
383 args_ = tuple(it->args.size());
384 for (int i = 0; i < nargs; ++i) {
385 handle item = PyTuple_GET_ITEM(args, i);
386 PyTuple_SET_ITEM(args_.ptr(), i, item.inc_ref().ptr());
387 }
388
389 int arg_ctr = 0;
390 for (auto const &it2 : it->args) {
391 int index = arg_ctr++;
392 if (PyTuple_GET_ITEM(args_.ptr(), index))
393 continue;
394
395 handle value;
396 if (kwargs)
397 value = PyDict_GetItemString(kwargs, it2.name);
398
399 if (value)
400 kwargs_consumed++;
401 else if (it2.value)
402 value = it2.value;
403
404 if (value) {
405 PyTuple_SET_ITEM(args_.ptr(), index, value.inc_ref().ptr());
406 } else {
407 kwargs_consumed = -1; /* definite failure */
408 break;
409 }
410 }
411 }
412
413 if (kwargs_consumed == nkwargs)
414 result = it->impl(it, args_, parent);
415
416 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
417 break;
418 }
419 } catch (const error_already_set &) { return nullptr;
420 } catch (const index_error &e) { PyErr_SetString(PyExc_IndexError, e.what()); return nullptr;
421 } catch (const stop_iteration &e) { PyErr_SetString(PyExc_StopIteration, e.what()); return nullptr;
422 } catch (const std::bad_alloc &e) { PyErr_SetString(PyExc_MemoryError, e.what()); return nullptr;
423 } catch (const std::domain_error &e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr;
424 } catch (const std::invalid_argument &e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr;
425 } catch (const std::length_error &e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr;
426 } catch (const std::out_of_range &e) { PyErr_SetString(PyExc_IndexError, e.what()); return nullptr;
427 } catch (const std::range_error &e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr;
428 } catch (const std::exception &e) { PyErr_SetString(PyExc_RuntimeError, e.what()); return nullptr;
429 } catch (...) {
430 PyErr_SetString(PyExc_RuntimeError, "Caught an unknown exception!");
431 return nullptr;
432 }
433
434 if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
435 std::string msg = "Incompatible function arguments. The "
436 "following argument types are supported:\n";
437 int ctr = 0;
438 for (detail::function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
439 msg += " "+ std::to_string(++ctr) + ". ";
440 msg += it2->signature;
441 msg += "\n";
442 }
443 PyErr_SetString(PyExc_TypeError, msg.c_str());
444 return nullptr;
445 } else if (!result) {
446 std::string msg = "Unable to convert function return value to a "
447 "Python type! The signature was\n\t";
448 msg += it->signature;
449 PyErr_SetString(PyExc_TypeError, msg.c_str());
450 return nullptr;
451 } else {
452 if (overloads->is_constructor) {
453 /* When a construtor ran successfully, the corresponding
454 holder type (e.g. std::unique_ptr) must still be initialized. */
455 PyObject *inst = PyTuple_GetItem(args, 0);
456 auto tinfo = detail::get_type_info(Py_TYPE(inst));
457 tinfo->init_holder(inst, nullptr);
458 }
459 return result.ptr();
460 }
461 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200462};
463
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100464/// Wrapper for Python extension modules
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200465class module : public object {
466public:
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200467 PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200468
469 module(const char *name, const char *doc = nullptr) {
Wenzel Jakob57082212015-09-04 23:42:12 +0200470#if PY_MAJOR_VERSION >= 3
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200471 PyModuleDef *def = new PyModuleDef();
472 memset(def, 0, sizeof(PyModuleDef));
473 def->m_name = name;
474 def->m_doc = doc;
475 def->m_size = -1;
476 Py_INCREF(def);
477 m_ptr = PyModule_Create(def);
Wenzel Jakob57082212015-09-04 23:42:12 +0200478#else
479 m_ptr = Py_InitModule3(name, nullptr, doc);
480#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200481 if (m_ptr == nullptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100482 pybind11_fail("Internal error in module::module()");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200483 inc_ref();
484 }
485
Wenzel Jakob71867832015-07-29 17:43:52 +0200486 template <typename Func, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100487 module &def(const char *name_, Func &&f, const Extra& ... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +0200488 cpp_function func(std::forward<Func>(f), name(name_),
Wenzel Jakoba6501792016-02-04 23:02:07 +0100489 sibling((handle) attr(name_)), scope(*this), extra...);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100490 /* PyModule_AddObject steals a reference to 'func' */
491 PyModule_AddObject(ptr(), name_, func.inc_ref().ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200492 return *this;
493 }
494
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200495 module def_submodule(const char *name, const char *doc = nullptr) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200496 std::string full_name = std::string(PyModule_GetName(m_ptr))
497 + std::string(".") + std::string(name);
498 module result(PyImport_AddModule(full_name.c_str()), true);
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200499 if (doc)
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200500 result.attr("__doc__") = pybind11::str(doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200501 attr(name) = result;
502 return result;
503 }
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200504
505 static module import(const char *name) {
Wenzel Jakobdd57a342015-12-26 14:04:52 +0100506 PyObject *obj = PyImport_ImportModule(name);
507 if (!obj)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100508 pybind11_fail("Module \"" + std::string(name) + "\" not found!");
Wenzel Jakobdd57a342015-12-26 14:04:52 +0100509 return module(obj, false);
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200510 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200511};
512
513NAMESPACE_BEGIN(detail)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100514/// Generic support for creating new Python heap types
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100515class generic_type : public object {
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100516 template <typename type, typename holder_type> friend class class_;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200517public:
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100518 PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100519protected:
520 void initialize(type_record *rec) {
521 if (rec->base_type) {
522 if (rec->base_handle)
523 pybind11_fail("generic_type: specified base type multiple times!");
524 rec->base_handle = detail::get_type_handle(*(rec->base_type));
525 if (!rec->base_handle) {
526 std::string tname(rec->base_type->name());
527 detail::clean_type_id(tname);
528 pybind11_fail("generic_type: type \"" + std::string(rec->name) +
529 "\" referenced unknown base type \"" + tname + "\"");
530 }
531 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200532
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100533 object type_holder(PyType_Type.tp_alloc(&PyType_Type, 0), false);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100534 object name(PYBIND11_FROM_STRING(rec->name), false);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100535 auto type = (PyHeapTypeObject*) type_holder.ptr();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200536
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100537 if (!type_holder || !name)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100538 pybind11_fail("generic_type: unable to create type object!");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200539
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100540 /* Register supplemental type information in C++ dict */
541 auto &internals = get_internals();
542 detail::type_info *tinfo = new detail::type_info();
543 tinfo->type = (PyTypeObject *) type;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100544 tinfo->type_size = rec->type_size;
545 tinfo->init_holder = rec->init_holder;
Wenzel Jakobb6cf75d2016-01-29 11:39:32 +0100546 internals.registered_types_cpp[std::type_index(*(rec->type))] = tinfo;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100547 internals.registered_types_py[type] = tinfo;
548
Wenzel Jakobb2825952016-04-13 23:33:00 +0200549 object scope_module;
550 if (rec->scope) {
551 scope_module = (object) rec->scope.attr("__module__");
552 if (!scope_module)
553 scope_module = (object) rec->scope.attr("__name__");
554 }
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100555
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100556 std::string full_name = (scope_module ? ((std::string) scope_module.str() + "." + rec->name)
557 : std::string(rec->name));
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100558 /* Basic type attributes */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200559 type->ht_type.tp_name = strdup(full_name.c_str());
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100560 type->ht_type.tp_basicsize = rec->instance_size;
561 type->ht_type.tp_base = (PyTypeObject *) rec->base_handle.ptr();
562 rec->base_handle.inc_ref();
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100563
564#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
565 /* Qualified names for Python >= 3.3 */
Wenzel Jakobb2825952016-04-13 23:33:00 +0200566 object scope_qualname;
567 if (rec->scope)
568 scope_qualname = (object) rec->scope.attr("__qualname__");
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100569 if (scope_qualname) {
570 type->ht_qualname = PyUnicode_FromFormat(
571 "%U.%U", scope_qualname.ptr(), name.ptr());
572 } else {
573 type->ht_qualname = name.ptr();
574 name.inc_ref();
575 }
Wenzel Jakob57082212015-09-04 23:42:12 +0200576#endif
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100577 type->ht_name = name.release().ptr();
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100578
579 /* Supported protocols */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200580 type->ht_type.tp_as_number = &type->as_number;
581 type->ht_type.tp_as_sequence = &type->as_sequence;
582 type->ht_type.tp_as_mapping = &type->as_mapping;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100583
584 /* Supported elementary operations */
585 type->ht_type.tp_init = (initproc) init;
586 type->ht_type.tp_new = (newfunc) new_instance;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100587 type->ht_type.tp_dealloc = rec->dealloc;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100588
589 /* Support weak references (needed for the keep_alive feature) */
Wenzel Jakob88d1d042016-01-20 01:26:42 +0100590 type->ht_type.tp_weaklistoffset = offsetof(instance_essentials<void>, weakrefs);
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100591
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100592 /* Flags */
593 type->ht_type.tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
594#if PY_MAJOR_VERSION < 3
595 type->ht_type.tp_flags |= Py_TPFLAGS_CHECKTYPES;
596#endif
597 type->ht_type.tp_flags &= ~Py_TPFLAGS_HAVE_GC;
598
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100599 if (rec->doc) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100600 /* Allocate memory for docstring (using PyObject_MALLOC, since
601 Python will free this later on) */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100602 size_t size = strlen(rec->doc) + 1;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100603 type->ht_type.tp_doc = (char *) PyObject_MALLOC(size);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100604 memcpy((void *) type->ht_type.tp_doc, rec->doc, size);
Wenzel Jakob5116b022015-09-05 02:09:17 +0200605 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200606
607 if (PyType_Ready(&type->ht_type) < 0)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100608 pybind11_fail("generic_type: PyType_Ready failed!");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200609
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100610 m_ptr = type_holder.ptr();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200611
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100612 if (scope_module) // Needed by pydoc
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100613 attr("__module__") = scope_module;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200614
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100615 /* Register type with the parent scope */
Wenzel Jakobb2825952016-04-13 23:33:00 +0200616 if (rec->scope)
617 rec->scope.attr(handle(type->ht_name)) = *this;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100618
619 type_holder.release();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200620 }
621
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100622 /// Allocate a metaclass on demand (for static properties)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200623 handle metaclass() {
624 auto &ht_type = ((PyHeapTypeObject *) m_ptr)->ht_type;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100625 auto &ob_type = PYBIND11_OB_TYPE(ht_type);
Wenzel Jakob57082212015-09-04 23:42:12 +0200626
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200627 if (ob_type == &PyType_Type) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100628 std::string name_ = std::string(ht_type.tp_name) + "__Meta";
629 object type_holder(PyType_Type.tp_alloc(&PyType_Type, 0), false);
630 object name(PYBIND11_FROM_STRING(name_.c_str()), false);
631 if (!type_holder || !name)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100632 pybind11_fail("generic_type::metaclass(): unable to create type object!");
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100633
634 auto type = (PyHeapTypeObject*) type_holder.ptr();
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100635 type->ht_name = name.release().ptr();
636#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
637 /* Qualified names for Python >= 3.3 */
638 type->ht_qualname = PyUnicode_FromFormat(
639 "%U__Meta", ((object) attr("__qualname__")).ptr());
640#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200641 type->ht_type.tp_name = strdup(name_.c_str());
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100642 type->ht_type.tp_base = ob_type;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100643 type->ht_type.tp_flags |= (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE) &
644 ~Py_TPFLAGS_HAVE_GC;
645
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200646 if (PyType_Ready(&type->ht_type) < 0)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100647 pybind11_fail("generic_type::metaclass(): PyType_Ready failed!");
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100648
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100649 ob_type = (PyTypeObject *) type_holder.release().ptr();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200650 }
651 return handle((PyObject *) ob_type);
652 }
653
654 static int init(void *self, PyObject *, PyObject *) {
655 std::string msg = std::string(Py_TYPE(self)->tp_name) + ": No constructor defined!";
656 PyErr_SetString(PyExc_TypeError, msg.c_str());
657 return -1;
658 }
659
660 static PyObject *new_instance(PyTypeObject *type, PyObject *, PyObject *) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100661 instance<void> *self = (instance<void> *) PyType_GenericAlloc((PyTypeObject *) type, 0);
662 auto tinfo = detail::get_type_info(type);
663 self->value = ::operator new(tinfo->type_size);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200664 self->owned = true;
665 self->parent = nullptr;
666 self->constructed = false;
667 detail::get_internals().registered_instances[self->value] = (PyObject *) self;
668 return (PyObject *) self;
669 }
670
671 static void dealloc(instance<void> *self) {
672 if (self->value) {
673 bool dont_cache = self->parent && ((instance<void> *) self->parent)->value == self->value;
674 if (!dont_cache) { // avoid an issue with internal references matching their parent's address
675 auto &registered_instances = detail::get_internals().registered_instances;
676 auto it = registered_instances.find(self->value);
677 if (it == registered_instances.end())
Wenzel Jakob678d7872016-01-17 22:36:41 +0100678 pybind11_fail("generic_type::dealloc(): Tried to deallocate unregistered instance!");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200679 registered_instances.erase(it);
680 }
681 Py_XDECREF(self->parent);
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100682 if (self->weakrefs)
683 PyObject_ClearWeakRefs((PyObject *) self);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200684 }
685 Py_TYPE(self)->tp_free((PyObject*) self);
686 }
687
Wenzel Jakob43398a82015-07-28 16:12:20 +0200688 void install_buffer_funcs(
689 buffer_info *(*get_buffer)(PyObject *, void *),
690 void *get_buffer_data) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200691 PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
692 type->ht_type.tp_as_buffer = &type->as_buffer;
Wenzel Jakob57082212015-09-04 23:42:12 +0200693#if PY_MAJOR_VERSION < 3
694 type->ht_type.tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
695#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200696 type->as_buffer.bf_getbuffer = getbuffer;
697 type->as_buffer.bf_releasebuffer = releasebuffer;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100698 auto tinfo = detail::get_type_info(&type->ht_type);
699 tinfo->get_buffer = get_buffer;
700 tinfo->get_buffer_data = get_buffer_data;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200701 }
702
703 static int getbuffer(PyObject *obj, Py_buffer *view, int flags) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100704 auto tinfo = detail::get_type_info(Py_TYPE(obj));
705 if (view == nullptr || obj == nullptr || !tinfo || !tinfo->get_buffer) {
706 PyErr_SetString(PyExc_BufferError, "generic_type::getbuffer(): Internal error");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200707 return -1;
708 }
709 memset(view, 0, sizeof(Py_buffer));
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100710 buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200711 view->obj = obj;
712 view->ndim = 1;
713 view->internal = info;
714 view->buf = info->ptr;
715 view->itemsize = info->itemsize;
716 view->len = view->itemsize;
717 for (auto s : info->shape)
718 view->len *= s;
719 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
720 view->format = const_cast<char *>(info->format.c_str());
721 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
722 view->ndim = info->ndim;
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100723 view->strides = (ssize_t *) &info->strides[0];
724 view->shape = (ssize_t *) &info->shape[0];
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200725 }
726 Py_INCREF(view->obj);
727 return 0;
728 }
729
730 static void releasebuffer(PyObject *, Py_buffer *view) { delete (buffer_info *) view->internal; }
731};
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200732NAMESPACE_END(detail)
733
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100734template <typename type, typename holder_type = std::unique_ptr<type>>
735class class_ : public detail::generic_type {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200736public:
737 typedef detail::instance<type, holder_type> instance_type;
738
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100739 PYBIND11_OBJECT(class_, detail::generic_type, PyType_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200740
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100741 template <typename... Extra>
742 class_(handle scope, const char *name, const Extra &... extra) {
743 detail::type_record record;
744 record.scope = scope;
745 record.name = name;
746 record.type = &typeid(type);
747 record.type_size = sizeof(type);
748 record.instance_size = sizeof(instance_type);
749 record.init_holder = init_holder;
750 record.dealloc = dealloc;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200751
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100752 /* Process optional arguments, if any */
753 detail::process_attributes<Extra...>::init(extra..., &record);
754
755 detail::generic_type::initialize(&record);
756 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200757
Wenzel Jakob71867832015-07-29 17:43:52 +0200758 template <typename Func, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100759 class_ &def(const char *name_, Func&& f, const Extra&... extra) {
Wenzel Jakob57082212015-09-04 23:42:12 +0200760 cpp_function cf(std::forward<Func>(f), name(name_),
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100761 sibling(attr(name_)), is_method(*this),
762 extra...);
Wenzel Jakob57082212015-09-04 23:42:12 +0200763 attr(cf.name()) = cf;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200764 return *this;
765 }
766
Wenzel Jakob71867832015-07-29 17:43:52 +0200767 template <typename Func, typename... Extra> class_ &
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100768 def_static(const char *name_, Func f, const Extra&... extra) {
Wenzel Jakob57082212015-09-04 23:42:12 +0200769 cpp_function cf(std::forward<Func>(f), name(name_),
Wenzel Jakoba6501792016-02-04 23:02:07 +0100770 sibling(attr(name_)), scope(*this), extra...);
Wenzel Jakob57082212015-09-04 23:42:12 +0200771 attr(cf.name()) = cf;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200772 return *this;
773 }
774
Wenzel Jakob71867832015-07-29 17:43:52 +0200775 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100776 class_ &def(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
Wenzel Jakobe2065642016-02-04 23:29:29 +0100777 op.template execute<type>(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200778 return *this;
779 }
780
Wenzel Jakob71867832015-07-29 17:43:52 +0200781 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100782 class_ & def_cast(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
Wenzel Jakobe2065642016-02-04 23:29:29 +0100783 op.template execute_cast<type>(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200784 return *this;
785 }
786
Wenzel Jakob71867832015-07-29 17:43:52 +0200787 template <typename... Args, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100788 class_ &def(const detail::init<Args...> &init, const Extra&... extra) {
Wenzel Jakobe2065642016-02-04 23:29:29 +0100789 init.template execute<type>(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200790 return *this;
791 }
792
Wenzel Jakob71867832015-07-29 17:43:52 +0200793 template <typename Func> class_& def_buffer(Func &&func) {
Wenzel Jakob43398a82015-07-28 16:12:20 +0200794 struct capture { Func func; };
795 capture *ptr = new capture { std::forward<Func>(func) };
796 install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200797 detail::type_caster<type> caster;
798 if (!caster.load(obj, false))
799 return nullptr;
Wenzel Jakob43398a82015-07-28 16:12:20 +0200800 return new buffer_info(((capture *) ptr)->func(caster));
801 }, ptr);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200802 return *this;
803 }
804
Wenzel Jakob71867832015-07-29 17:43:52 +0200805 template <typename C, typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100806 class_ &def_readwrite(const char *name, D C::*pm, const Extra&... extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +0100807 cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; }, is_method(*this)),
808 fset([pm](C &c, const D &value) { c.*pm = value; }, is_method(*this));
809 def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200810 return *this;
811 }
812
Wenzel Jakob71867832015-07-29 17:43:52 +0200813 template <typename C, typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100814 class_ &def_readonly(const char *name, const D C::*pm, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +0100815 cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; }, is_method(*this));
816 def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200817 return *this;
818 }
819
Wenzel Jakob71867832015-07-29 17:43:52 +0200820 template <typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100821 class_ &def_readwrite_static(const char *name, D *pm, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +0100822 cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this)),
823 fset([pm](object, const D &value) { *pm = value; }, scope(*this));
824 def_property_static(name, fget, fset, return_value_policy::reference, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200825 return *this;
826 }
827
Wenzel Jakob71867832015-07-29 17:43:52 +0200828 template <typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100829 class_ &def_readonly_static(const char *name, const D *pm, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +0100830 cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this));
831 def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200832 return *this;
833 }
834
Wenzel Jakob84ec78f2016-03-21 17:54:24 +0100835 template <typename... Extra>
836 class_ &def_property_readonly(const char *name, const cpp_function &fget, const Extra& ...extra) {
837 def_property(name, fget, cpp_function(), extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200838 return *this;
839 }
840
Wenzel Jakob84ec78f2016-03-21 17:54:24 +0100841 template <typename... Extra>
842 class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const Extra& ...extra) {
843 def_property_static(name, fget, cpp_function(), extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200844 return *this;
845 }
846
Wenzel Jakob84ec78f2016-03-21 17:54:24 +0100847 template <typename... Extra>
848 class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +0100849 return def_property_static(name, fget, fset, is_method(*this), extra...);
Wenzel Jakob84ec78f2016-03-21 17:54:24 +0100850 }
851
852 template <typename... Extra>
853 class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
854 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
855 detail::process_attributes<Extra...>::init(extra..., rec_fget);
856 if (rec_fset)
857 detail::process_attributes<Extra...>::init(extra..., rec_fset);
858 pybind11::str doc_obj = pybind11::str(rec_fget->doc ? rec_fget->doc : "");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200859 object property(
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100860 PyObject_CallFunctionObjArgs((PyObject *) &PyProperty_Type, fget.ptr() ? fget.ptr() : Py_None,
861 fset.ptr() ? fset.ptr() : Py_None, Py_None, doc_obj.ptr(), nullptr), false);
Wenzel Jakob84ec78f2016-03-21 17:54:24 +0100862 if (rec_fget->class_)
863 attr(name) = property;
864 else
865 metaclass().attr(name) = property;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200866 return *this;
867 }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200868
869 template <typename target> class_ alias() {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100870 auto &instances = pybind11::detail::get_internals().registered_types_cpp;
Wenzel Jakobb6cf75d2016-01-29 11:39:32 +0100871 instances[std::type_index(typeid(target))] = instances[std::type_index(typeid(type))];
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200872 return *this;
873 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200874private:
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100875 /// Initialize holder object, variant 1: object derives from enable_shared_from_this
876 template <typename T>
877 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 +0100878 try {
Wenzel Jakob309a85b2016-03-08 17:59:10 +0100879 new (&inst->holder) holder_type(std::static_pointer_cast<type>(inst->value->shared_from_this()));
Wenzel Jakob6e213c92015-11-24 23:05:58 +0100880 } catch (const std::bad_weak_ptr &) {
881 new (&inst->holder) holder_type(inst->value);
882 }
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100883 }
884
885 /// Initialize holder object, variant 2: try to construct from existing holder object, if possible
886 template <typename T = holder_type,
887 typename std::enable_if<std::is_copy_constructible<T>::value, int>::type = 0>
888 static void init_holder_helper(instance_type *inst, const holder_type *holder_ptr, const void * /* dummy */) {
889 if (holder_ptr)
890 new (&inst->holder) holder_type(*holder_ptr);
891 else
892 new (&inst->holder) holder_type(inst->value);
893 }
894
895 /// Initialize holder object, variant 3: holder is not copy constructible (e.g. unique_ptr), always initialize from raw pointer
896 template <typename T = holder_type,
897 typename std::enable_if<!std::is_copy_constructible<T>::value, int>::type = 0>
898 static void init_holder_helper(instance_type *inst, const holder_type * /* unused */, const void * /* dummy */) {
899 new (&inst->holder) holder_type(inst->value);
900 }
901
902 /// Initialize holder object of an instance, possibly given a pointer to an existing holder
903 static void init_holder(PyObject *inst_, const void *holder_ptr) {
904 auto inst = (instance_type *) inst_;
905 init_holder_helper(inst, (const holder_type *) holder_ptr, inst->value);
Wenzel Jakob6e213c92015-11-24 23:05:58 +0100906 inst->constructed = true;
907 }
908
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200909 static void dealloc(PyObject *inst_) {
910 instance_type *inst = (instance_type *) inst_;
911 if (inst->owned) {
912 if (inst->constructed)
913 inst->holder.~holder_type();
914 else
915 ::operator delete(inst->value);
916 }
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100917 generic_type::dealloc((detail::instance<void> *) inst);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200918 }
Wenzel Jakob84ec78f2016-03-21 17:54:24 +0100919
920 static detail::function_record *get_function_record(handle h) {
921 h = detail::get_function(h);
922 return h ? (detail::function_record *) capsule(
923 PyCFunction_GetSelf(h.ptr()), true) : nullptr;
924 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200925};
926
927/// Binds C++ enumerations and enumeration classes to Python
928template <typename Type> class enum_ : public class_<Type> {
929public:
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100930 template <typename... Extra>
931 enum_(const handle &scope, const char *name, const Extra&... extra)
932 : class_<Type>(scope, name, extra...), m_parent(scope) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200933 auto entries = new std::unordered_map<int, const char *>();
Wenzel Jakob8456a4d2015-10-13 02:42:20 +0200934 this->def("__repr__", [name, entries](Type value) -> std::string {
Wenzel Jakoba7500312015-08-29 02:08:32 +0200935 auto it = entries->find((int) value);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200936 return std::string(name) + "." +
937 ((it == entries->end()) ? std::string("???")
938 : std::string(it->second));
939 });
Wenzel Jakob15f6a002016-01-24 14:05:12 +0100940 this->def("__init__", [](Type& value, int i) { value = (Type) i; });
Wenzel Jakob69189222015-10-01 21:32:23 +0200941 this->def("__int__", [](Type value) { return (int) value; });
Wenzel Jakob15f6a002016-01-24 14:05:12 +0100942 this->def("__eq__", [](const Type &value, Type value2) { return value == value2; });
943 this->def("__ne__", [](const Type &value, Type value2) { return value != value2; });
944 this->def("__hash__", [](const Type &value) { return (int) value; });
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200945 m_entries = entries;
946 }
947
948 /// Export enumeration entries into the parent scope
949 void export_values() {
950 PyObject *dict = ((PyTypeObject *) this->m_ptr)->tp_dict;
951 PyObject *key, *value;
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100952 ssize_t pos = 0;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200953 while (PyDict_Next(dict, &pos, &key, &value))
954 if (PyObject_IsInstance(value, this->m_ptr))
955 m_parent.attr(key) = value;
956 }
957
958 /// Add an enumeration entry
959 enum_& value(char const* name, Type value) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200960 this->attr(name) = pybind11::cast(value, return_value_policy::copy);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200961 (*m_entries)[(int) value] = name;
962 return *this;
963 }
964private:
965 std::unordered_map<int, const char *> *m_entries;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100966 handle m_parent;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200967};
968
969NAMESPACE_BEGIN(detail)
Wenzel Jakob71867832015-07-29 17:43:52 +0200970template <typename... Args> struct init {
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100971 template <typename Base, typename Holder, typename... Extra> void execute(pybind11::class_<Base, Holder> &class_, const Extra&... extra) const {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200972 /// Function which calls a specific C++ in-place constructor
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100973 class_.def("__init__", [](Base *instance, Args... args) { new (instance) Base(args...); }, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200974 }
975};
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100976
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100977PYBIND11_NOINLINE inline void keep_alive_impl(int Nurse, int Patient, handle args, handle ret) {
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100978 /* Clever approach based on weak references taken from Boost.Python */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100979 handle nurse (Nurse > 0 ? PyTuple_GetItem(args.ptr(), Nurse - 1) : ret.ptr());
980 handle patient(Patient > 0 ? PyTuple_GetItem(args.ptr(), Patient - 1) : ret.ptr());
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100981
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100982 if (!nurse || !patient)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100983 pybind11_fail("Could not activate keep_alive!");
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100984
985 cpp_function disable_lifesupport(
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100986 [patient](handle weakref) { patient.dec_ref(); weakref.dec_ref(); });
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100987
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100988 weakref wr(nurse, disable_lifesupport);
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100989
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100990 patient.inc_ref(); /* reference patient and leak the weak reference */
991 (void) wr.release();
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100992}
993
Wenzel Jakobb2825952016-04-13 23:33:00 +0200994template <typename Iterator> struct iterator_state { Iterator it, end; };
995
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200996NAMESPACE_END(detail)
997
Ben Pritchard2de6e1d2016-02-18 13:20:15 -0500998template <typename... Args> detail::init<Args...> init() { return detail::init<Args...>(); }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200999
Wenzel Jakobb2825952016-04-13 23:33:00 +02001000template <typename Iterator, typename... Extra> iterator make_iterator(Iterator first, Iterator last, Extra&&... extra) {
1001 typedef detail::iterator_state<Iterator> state;
1002
1003 if (!detail::get_type_info(typeid(state))) {
1004 class_<state>(handle(), "")
1005 .def("__iter__", [](state &s) -> state& { return s; })
1006 .def("__next__", [](state &s) -> decltype(*std::declval<Iterator>()) & {
1007 if (s.it == s.end)
1008 throw stop_iteration();
1009 return *s.it++;
1010 }, return_value_policy::reference_internal, std::forward<Extra>(extra)...);
1011 }
1012
1013 return (iterator) cast(state { first, last });
1014}
1015
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001016template <typename InputType, typename OutputType> void implicitly_convertible() {
Wenzel Jakob2ac50442016-01-17 22:36:35 +01001017 auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001018 if (!detail::type_caster<InputType>().load(obj, false))
1019 return nullptr;
1020 tuple args(1);
1021 args[0] = obj;
1022 PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
1023 if (result == nullptr)
1024 PyErr_Clear();
1025 return result;
1026 };
Wenzel Jakobb6cf75d2016-01-29 11:39:32 +01001027 auto &registered_types = detail::get_internals().registered_types_cpp;
1028 auto it = registered_types.find(std::type_index(typeid(OutputType)));
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001029 if (it == registered_types.end())
Wenzel Jakob678d7872016-01-17 22:36:41 +01001030 pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
Wenzel Jakobd561cb02016-01-17 22:36:41 +01001031 ((detail::type_info *) it->second)->implicit_conversions.push_back(implicit_caster);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001032}
1033
Felipe Lema2547ca42016-01-25 16:22:44 -03001034#if defined(WITH_THREAD)
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001035inline void init_threading() { PyEval_InitThreads(); }
1036
1037class gil_scoped_acquire {
1038 PyGILState_STATE state;
1039public:
1040 inline gil_scoped_acquire() { state = PyGILState_Ensure(); }
1041 inline ~gil_scoped_acquire() { PyGILState_Release(state); }
1042};
1043
1044class gil_scoped_release {
1045 PyThreadState *state;
1046public:
1047 inline gil_scoped_release() { state = PyEval_SaveThread(); }
1048 inline ~gil_scoped_release() { PyEval_RestoreThread(state); }
1049};
Felipe Lema2547ca42016-01-25 16:22:44 -03001050#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001051
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001052inline function get_overload(const void *this_ptr, const char *name) {
1053 handle py_object = detail::get_object_handle(this_ptr);
Wenzel Jakobac0fde92015-10-01 18:37:26 +02001054 if (!py_object)
1055 return function();
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001056 handle type = py_object.get_type();
1057 auto key = std::make_pair(type.ptr(), name);
1058
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02001059 /* Cache functions that aren't overloaded in Python to avoid
1060 many costly Python dictionary lookups below */
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001061 auto &cache = detail::get_internals().inactive_overload_cache;
1062 if (cache.find(key) != cache.end())
1063 return function();
1064
1065 function overload = (function) py_object.attr(name);
1066 if (overload.is_cpp_function()) {
1067 cache.insert(key);
1068 return function();
1069 }
Wenzel Jakob27e8e102016-01-17 22:36:37 +01001070
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02001071 /* Don't call dispatch code if invoked from overridden function */
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001072 PyFrameObject *frame = PyThreadState_Get()->frame;
Wenzel Jakobb2b44a92016-04-15 17:50:40 +02001073 if (frame && (std::string) pybind11::handle(frame->f_code->co_name).str() == name &&
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02001074 frame->f_code->co_argcount > 0) {
1075 PyFrame_FastToLocals(frame);
1076 PyObject *self_caller = PyDict_GetItem(
1077 frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
1078 if (self_caller == py_object.ptr())
1079 return function();
1080 }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001081 return overload;
1082}
1083
Wenzel Jakobb1b71402015-10-18 16:48:30 +02001084#define PYBIND11_OVERLOAD_INT(ret_type, class_name, name, ...) { \
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02001085 pybind11::gil_scoped_acquire gil; \
1086 pybind11::function overload = pybind11::get_overload(this, #name); \
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001087 if (overload) \
Johan Mabille25dd4782016-02-26 13:09:22 +01001088 return overload.call(__VA_ARGS__).template cast<ret_type>(); }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001089
Wenzel Jakobb1b71402015-10-18 16:48:30 +02001090#define PYBIND11_OVERLOAD(ret_type, class_name, name, ...) \
1091 PYBIND11_OVERLOAD_INT(ret_type, class_name, name, __VA_ARGS__) \
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001092 return class_name::name(__VA_ARGS__)
1093
Wenzel Jakobb1b71402015-10-18 16:48:30 +02001094#define PYBIND11_OVERLOAD_PURE(ret_type, class_name, name, ...) \
1095 PYBIND11_OVERLOAD_INT(ret_type, class_name, name, __VA_ARGS__) \
Wenzel Jakob678d7872016-01-17 22:36:41 +01001096 pybind11::pybind11_fail("Tried to call pure virtual function \"" #name "\"");
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001097
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02001098NAMESPACE_END(pybind11)
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001099
1100#if defined(_MSC_VER)
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001101# pragma warning(pop)
Ben Pritchard33f34302016-02-18 15:25:51 -05001102#elif defined(__ICC) || defined(__INTEL_COMPILER)
1103# pragma warning(pop)
Wenzel Jakobcd5cda72015-08-03 12:17:54 +02001104#elif defined(__GNUG__) and !defined(__clang__)
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001105# pragma GCC diagnostic pop
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001106#endif