blob: b602439b7f755e291c23aaa4184ec8eb725a9f9a [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
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +02005 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
Wenzel Jakob38bd7112015-07-05 20:05:44 +02006
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)
Wenzel Jakob1ffce742016-08-25 01:43:33 +020015# pragma warning(disable: 4100) // warning C4100: Unreferenced formal parameter
Wenzel Jakob48548ea2016-01-17 22:36:44 +010016# pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
Wenzel Jakob1ffce742016-08-25 01:43:33 +020017# pragma warning(disable: 4512) // warning C4512: Assignment operator was implicitly defined as deleted
Wenzel Jakob48548ea2016-01-17 22:36:44 +010018# pragma warning(disable: 4800) // warning C4800: 'int': forcing value to bool 'true' or 'false' (performance warning)
19# pragma warning(disable: 4996) // warning C4996: The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name
Wenzel Jakob1ffce742016-08-25 01:43:33 +020020#elif defined(__INTEL_COMPILER)
Ben Pritchard33f34302016-02-18 15:25:51 -050021# pragma warning(push)
Wenzel Jakob1ffce742016-08-25 01:43:33 +020022# pragma warning(disable: 186) // pointless comparison of unsigned integer with zero
23# pragma warning(disable: 1334) // the "template" keyword used for syntactic disambiguation may only be used within a template
24# pragma warning(disable: 2196) // warning #2196: routine is both "inline" and "noinline"
Wenzel Jakob6d252962016-05-01 20:47:49 +020025#elif defined(__GNUG__) && !defined(__clang__)
Wenzel Jakob48548ea2016-01-17 22:36:44 +010026# pragma GCC diagnostic push
27# pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
28# pragma GCC diagnostic ignored "-Wunused-but-set-variable"
29# pragma GCC diagnostic ignored "-Wmissing-field-initializers"
Wenzel Jakobdeeab552016-05-15 23:54:34 +020030# pragma GCC diagnostic ignored "-Wstrict-aliasing"
31# pragma GCC diagnostic ignored "-Wattributes"
Wenzel Jakob38bd7112015-07-05 20:05:44 +020032#endif
33
Wenzel Jakob48548ea2016-01-17 22:36:44 +010034#include "attr.h"
Wenzel Jakob38bd7112015-07-05 20:05:44 +020035
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020036NAMESPACE_BEGIN(pybind11)
Wenzel Jakob38bd7112015-07-05 20:05:44 +020037
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020038/// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020039class cpp_function : public function {
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020040public:
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020041 cpp_function() { }
Wenzel Jakob38bd7112015-07-05 20:05:44 +020042
Wenzel Jakob5984baa2016-05-10 15:05:03 +010043 /// Construct a cpp_function from a vanilla function pointer
Wenzel Jakob66c9a402016-01-17 22:36:36 +010044 template <typename Return, typename... Args, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +010045 cpp_function(Return (*f)(Args...), const Extra&... extra) {
Wenzel Jakob5984baa2016-05-10 15:05:03 +010046 initialize(f, f, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +020047 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020048
Wenzel Jakob5984baa2016-05-10 15:05:03 +010049 /// Construct a cpp_function from a lambda function (possibly with internal state)
Wenzel Jakob48548ea2016-01-17 22:36:44 +010050 template <typename Func, typename... Extra> cpp_function(Func &&f, const Extra&... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +020051 initialize(std::forward<Func>(f),
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020052 (typename detail::remove_class<decltype(
Wenzel Jakob48548ea2016-01-17 22:36:44 +010053 &std::remove_reference<Func>::type::operator())>::type *) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020054 }
55
Wenzel Jakob5984baa2016-05-10 15:05:03 +010056 /// Construct a cpp_function from a class method (non-const)
57 template <typename Return, typename Class, typename... Arg, typename... Extra>
58 cpp_function(Return (Class::*f)(Arg...), const Extra&... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +020059 initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
Wenzel Jakob48548ea2016-01-17 22:36:44 +010060 (Return (*) (Class *, Arg...)) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020061 }
62
Wenzel Jakob5984baa2016-05-10 15:05:03 +010063 /// Construct a cpp_function from a class method (const)
64 template <typename Return, typename Class, typename... Arg, typename... Extra>
65 cpp_function(Return (Class::*f)(Arg...) const, const Extra&... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +020066 initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
Wenzel Jakob48548ea2016-01-17 22:36:44 +010067 (Return (*)(const Class *, Arg ...)) nullptr, extra...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020068 }
69
Wenzel Jakob57082212015-09-04 23:42:12 +020070 /// Return the function name
Wenzel Jakob48548ea2016-01-17 22:36:44 +010071 object name() const { return attr("__name__"); }
Wenzel Jakob57082212015-09-04 23:42:12 +020072
Wenzel Jakobd561cb02016-01-17 22:36:41 +010073protected:
Wenzel Jakob382484a2016-09-10 15:28:37 +090074 /// Space optimization: don't inline this frequently instantiated fragment
75 PYBIND11_NOINLINE detail::function_record *make_function_record() {
76 return new detail::function_record();
77 }
78
Wenzel Jakobd561cb02016-01-17 22:36:41 +010079 /// Special internal constructor for functors, lambda functions, etc.
Wenzel Jakob66c9a402016-01-17 22:36:36 +010080 template <typename Func, typename Return, typename... Args, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +010081 void initialize(Func &&f, Return (*)(Args...), const Extra&... extra) {
Dean Moldovan9e625582016-06-04 00:27:32 +020082 static_assert(detail::expected_num_args<Extra...>(sizeof...(Args)),
83 "The number of named arguments does not match the function signature");
84
Wenzel Jakob66c9a402016-01-17 22:36:36 +010085 struct capture { typename std::remove_reference<Func>::type f; };
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020086
Wenzel Jakobd561cb02016-01-17 22:36:41 +010087 /* Store the function including any extra state it might have (e.g. a lambda capture object) */
Wenzel Jakob382484a2016-09-10 15:28:37 +090088 auto rec = make_function_record();
Wenzel Jakob71867832015-07-29 17:43:52 +020089
Wenzel Jakob5984baa2016-05-10 15:05:03 +010090 /* Store the capture object directly in the function record if there is enough space */
91 if (sizeof(capture) <= sizeof(rec->data)) {
Wenzel Jakob954b7932016-07-10 10:13:18 +020092 /* Without these pragmas, GCC warns that there might not be
93 enough space to use the placement new operator. However, the
94 'if' statement above ensures that this is the case. */
Jason Rhinelander0b12f912016-07-07 16:26:04 -040095#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
Jason Rhinelandercae0e002016-07-07 16:11:42 -040096# pragma GCC diagnostic push
97# pragma GCC diagnostic ignored "-Wplacement-new"
98#endif
Wenzel Jakob5984baa2016-05-10 15:05:03 +010099 new ((capture *) &rec->data) capture { std::forward<Func>(f) };
Jason Rhinelander0b12f912016-07-07 16:26:04 -0400100#if defined(__GNUG__) && !defined(__clang__) && __GNUC__ >= 6
Jason Rhinelandercae0e002016-07-07 16:11:42 -0400101# pragma GCC diagnostic pop
102#endif
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100103 if (!std::is_trivially_destructible<Func>::value)
104 rec->free_data = [](detail::function_record *r) { ((capture *) &r->data)->~capture(); };
105 } else {
106 rec->data[0] = new capture { std::forward<Func>(f) };
107 rec->free_data = [](detail::function_record *r) { delete ((capture *) r->data[0]); };
108 }
Wenzel Jakob19208fe2015-10-13 17:37:25 +0200109
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100110 /* Type casters for the function arguments and return value */
111 typedef detail::type_caster<typename std::tuple<Args...>> cast_in;
112 typedef detail::type_caster<typename std::conditional<
113 std::is_void<Return>::value, detail::void_type,
114 typename detail::intrinsic_type<Return>::type>::type> cast_out;
Wenzel Jakob71867832015-07-29 17:43:52 +0200115
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100116 /* Dispatch code which converts function arguments and performs the actual function call */
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100117 rec->impl = [](detail::function_record *rec, handle args, handle kwargs, handle parent) -> handle {
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100118 cast_in args_converter;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100119
120 /* Try to cast the function arguments into the C++ domain */
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100121 if (!args_converter.load_args(args, kwargs, true))
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100122 return PYBIND11_TRY_NEXT_OVERLOAD;
123
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100124 /* Invoke call policy pre-call hook */
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100125 detail::process_attributes<Extra...>::precall(args);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100126
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100127 /* Get a pointer to the capture object */
128 capture *cap = (capture *) (sizeof(capture) <= sizeof(rec->data)
129 ? &rec->data : rec->data[0]);
130
Wenzel Jakob954b7932016-07-10 10:13:18 +0200131 /* Perform the function call */
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100132 handle result = cast_out::cast(args_converter.template call<Return>(cap->f),
133 rec->policy, parent);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100134
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100135 /* Invoke call policy post-call hook */
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100136 detail::process_attributes<Extra...>::postcall(args, result);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100137
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100138 return result;
Wenzel Jakob71867832015-07-29 17:43:52 +0200139 };
140
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100141 /* Process any user-provided function attributes */
142 detail::process_attributes<Extra...>::init(extra..., rec);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100143
144 /* Generate a readable signature describing the function's arguments and return value types */
Dean Moldovaned23dda2016-08-04 01:40:40 +0200145 using detail::descr; using detail::_;
146 PYBIND11_DESCR signature = _("(") + cast_in::element_names() + _(") -> ") + cast_out::name();
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100147
148 /* Register the function with Python from generic (non-templated) code */
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100149 initialize_generic(rec, signature.text(), signature.types(), sizeof...(Args));
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100150
151 if (cast_in::has_args) rec->has_args = true;
152 if (cast_in::has_kwargs) rec->has_kwargs = true;
Wenzel Jakob954b7932016-07-10 10:13:18 +0200153
154 /* Stash some additional information used by an important optimization in 'functional.h' */
155 using FunctionType = Return (*)(Args...);
156 constexpr bool is_function_ptr =
157 std::is_convertible<Func, FunctionType>::value &&
158 sizeof(capture) == sizeof(void *);
159 if (is_function_ptr) {
160 rec->is_stateless = true;
161 rec->data[1] = (void *) &typeid(FunctionType);
162 }
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200163 }
164
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100165 /// Register a function call with Python (generic non-templated code goes here)
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100166 void initialize_generic(detail::function_record *rec, const char *text,
Dean Moldovanecced6c2016-07-31 20:03:18 +0200167 const std::type_info *const *types, size_t args) {
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100168
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100169 /* Create copies of all referenced C-style strings */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100170 rec->name = strdup(rec->name ? rec->name : "");
171 if (rec->doc) rec->doc = strdup(rec->doc);
172 for (auto &a: rec->args) {
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100173 if (a.name)
174 a.name = strdup(a.name);
175 if (a.descr)
176 a.descr = strdup(a.descr);
177 else if (a.value)
Wenzel Jakob6c03beb2016-05-08 14:34:09 +0200178 a.descr = strdup(((std::string) ((object) handle(a.value).attr("__repr__"))().str()).c_str());
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100179 }
Wenzel Jakob954b7932016-07-10 10:13:18 +0200180
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 == '{') {
Dean Moldovanecced6c2016-07-31 20:03:18 +0200192 // Write arg name for everything except *args, **kwargs and return type.
Dean Moldovaned23dda2016-08-04 01:40:40 +0200193 if (type_depth == 0 && text[char_index] != '*' && arg_index < args) {
Dean Moldovanecced6c2016-07-31 20:03:18 +0200194 if (!rec->args.empty()) {
195 signature += rec->args[arg_index].name;
196 } else if (arg_index == 0 && rec->class_) {
197 signature += "self";
198 } else {
199 signature += "arg" + std::to_string(arg_index - (rec->class_ ? 1 : 0));
200 }
201 signature += ": ";
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100202 }
203 ++type_depth;
204 } else if (c == '}') {
205 --type_depth;
Dean Moldovaned23dda2016-08-04 01:40:40 +0200206 if (type_depth == 0) {
Dean Moldovanecced6c2016-07-31 20:03:18 +0200207 if (arg_index < rec->args.size() && rec->args[arg_index].descr) {
208 signature += "=";
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100209 signature += rec->args[arg_index].descr;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100210 }
211 arg_index++;
212 }
213 } else if (c == '%') {
214 const std::type_info *t = types[type_index++];
Wenzel Jakobb2c2c792016-01-17 22:36:40 +0100215 if (!t)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100216 pybind11_fail("Internal error while parsing type signature (1)");
Wenzel Jakobb6cf75d2016-01-29 11:39:32 +0100217 auto it = registered_types.find(std::type_index(*t));
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100218 if (it != registered_types.end()) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100219 signature += ((const detail::type_info *) it->second)->type->tp_name;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100220 } else {
221 std::string tname(t->name());
222 detail::clean_type_id(tname);
223 signature += tname;
224 }
225 } else {
226 signature += c;
227 }
228 }
Wenzel Jakob95d18692016-01-17 22:36:40 +0100229 if (type_depth != 0 || types[type_index] != nullptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100230 pybind11_fail("Internal error while parsing type signature (2)");
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100231
232 #if !defined(PYBIND11_CPP14)
233 delete[] types;
234 delete[] text;
235 #endif
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200236
Wenzel Jakob57082212015-09-04 23:42:12 +0200237#if PY_MAJOR_VERSION < 3
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100238 if (strcmp(rec->name, "__next__") == 0) {
239 std::free(rec->name);
240 rec->name = strdup("next");
Wenzel Jakobd1bfc4e2016-05-16 18:52:46 +0200241 } else if (strcmp(rec->name, "__bool__") == 0) {
242 std::free(rec->name);
243 rec->name = strdup("__nonzero__");
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100244 }
Wenzel Jakob57082212015-09-04 23:42:12 +0200245#endif
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100246 rec->signature = strdup(signature.c_str());
247 rec->args.shrink_to_fit();
Wenzel Jakoba380ed92016-05-15 23:54:13 +0200248 rec->is_constructor = !strcmp(rec->name, "__init__") || !strcmp(rec->name, "__setstate__");
Wenzel Jakobaffb9f42016-05-15 23:55:06 +0200249 rec->nargs = (uint16_t) args;
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200250
Wenzel Jakob57082212015-09-04 23:42:12 +0200251#if PY_MAJOR_VERSION < 3
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100252 if (rec->sibling && PyMethod_Check(rec->sibling.ptr()))
253 rec->sibling = PyMethod_GET_FUNCTION(rec->sibling.ptr());
Wenzel Jakob57082212015-09-04 23:42:12 +0200254#endif
255
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100256 detail::function_record *chain = nullptr, *chain_start = rec;
257 if (rec->sibling && PyCFunction_Check(rec->sibling.ptr())) {
258 capsule rec_capsule(PyCFunction_GetSelf(rec->sibling.ptr()), true);
259 chain = (detail::function_record *) rec_capsule;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100260 /* Never append a method to an overload chain of a parent class;
261 instead, hide the parent's overloads in this case */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100262 if (chain->class_ != rec->class_)
263 chain = nullptr;
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +0200264 }
265
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100266 if (!chain) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100267 /* No existing overload was found, create a new function object */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100268 rec->def = new PyMethodDef();
269 memset(rec->def, 0, sizeof(PyMethodDef));
270 rec->def->ml_name = rec->name;
271 rec->def->ml_meth = reinterpret_cast<PyCFunction>(*dispatcher);
272 rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
Wenzel Jakoba6501792016-02-04 23:02:07 +0100273
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100274 capsule rec_capsule(rec, [](PyObject *o) {
275 destruct((detail::function_record *) PyCapsule_GetPointer(o, nullptr));
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100276 });
Wenzel Jakoba6501792016-02-04 23:02:07 +0100277
278 object scope_module;
279 if (rec->scope) {
280 scope_module = (object) rec->scope.attr("__module__");
281 if (!scope_module)
282 scope_module = (object) rec->scope.attr("__name__");
283 }
284
285 m_ptr = PyCFunction_NewEx(rec->def, rec_capsule.ptr(), scope_module.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200286 if (!m_ptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100287 pybind11_fail("cpp_function::cpp_function(): Could not allocate function object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200288 } else {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100289 /* Append at the end of the overload chain */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100290 m_ptr = rec->sibling.ptr();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200291 inc_ref();
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100292 chain_start = chain;
293 while (chain->next)
294 chain = chain->next;
295 chain->next = rec;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200296 }
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200297
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200298 std::string signatures;
Wenzel Jakob71867832015-07-29 17:43:52 +0200299 int index = 0;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100300 /* Create a nice pydoc rec including all signatures and
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100301 docstrings of the functions in the overload chain */
Sylvain Corlay0e04fdf2016-03-08 16:42:12 -0500302 if (chain) {
303 // First a generic signature
304 signatures += rec->name;
305 signatures += "(*args, **kwargs)\n";
306 signatures += "Overloaded function.\n\n";
307 }
308 // Then specific overload signatures
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100309 for (auto it = chain_start; it != nullptr; it = it->next) {
310 if (chain)
Wenzel Jakob71867832015-07-29 17:43:52 +0200311 signatures += std::to_string(++index) + ". ";
Sylvain Corlay13b22bf2016-02-28 21:23:39 -0500312 signatures += rec->name;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100313 signatures += it->signature;
314 signatures += "\n";
315 if (it->doc && strlen(it->doc) > 0) {
316 signatures += "\n";
Wenzel Jakob218b6ce2016-02-28 23:52:37 +0100317 signatures += it->doc;
Wenzel Jakob66c9a402016-01-17 22:36:36 +0100318 signatures += "\n";
319 }
Wenzel Jakob71867832015-07-29 17:43:52 +0200320 if (it->next)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200321 signatures += "\n";
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200322 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100323
324 /* Install docstring */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200325 PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
326 if (func->m_ml->ml_doc)
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100327 std::free((char *) func->m_ml->ml_doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200328 func->m_ml->ml_doc = strdup(signatures.c_str());
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100329
330 if (rec->class_) {
331 m_ptr = PYBIND11_INSTANCE_METHOD_NEW(m_ptr, rec->class_.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200332 if (!m_ptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100333 pybind11_fail("cpp_function::cpp_function(): Could not allocate instance method object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200334 Py_DECREF(func);
335 }
336 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100337
338 /// When a cpp_function is GCed, release any memory allocated by pybind11
339 static void destruct(detail::function_record *rec) {
340 while (rec) {
341 detail::function_record *next = rec->next;
342 if (rec->free_data)
Wenzel Jakob5984baa2016-05-10 15:05:03 +0100343 rec->free_data(rec);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100344 std::free((char *) rec->name);
345 std::free((char *) rec->doc);
346 std::free((char *) rec->signature);
347 for (auto &arg: rec->args) {
348 std::free((char *) arg.name);
349 std::free((char *) arg.descr);
350 arg.value.dec_ref();
351 }
352 if (rec->def) {
353 std::free((char *) rec->def->ml_doc);
354 delete rec->def;
355 }
356 delete rec;
357 rec = next;
358 }
359 }
360
361 /// Main dispatch logic for calls to functions bound using pybind11
362 static PyObject *dispatcher(PyObject *self, PyObject *args, PyObject *kwargs) {
363 /* Iterator over the list of potentially admissible overloads */
364 detail::function_record *overloads = (detail::function_record *) PyCapsule_GetPointer(self, nullptr),
365 *it = overloads;
366
367 /* Need to know how many arguments + keyword arguments there are to pick the right overload */
Wenzel Jakob0a078052016-05-29 13:40:40 +0200368 size_t nargs = (size_t) PyTuple_GET_SIZE(args),
369 nkwargs = kwargs ? (size_t) PyDict_Size(kwargs) : 0;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100370
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100371 handle parent = nargs > 0 ? PyTuple_GET_ITEM(args, 0) : nullptr,
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100372 result = PYBIND11_TRY_NEXT_OVERLOAD;
373 try {
374 for (; it != nullptr; it = it->next) {
375 tuple args_(args, true);
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100376 size_t kwargs_consumed = 0;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100377
378 /* For each overload:
379 1. If the required list of arguments is longer than the
380 actually provided amount, create a copy of the argument
381 list and fill in any available keyword/default arguments.
382 2. Ensure that all keyword arguments were "consumed"
383 3. Call the function call dispatcher (function_record::impl)
384 */
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100385 size_t nargs_ = nargs;
386 if (nargs < it->args.size()) {
387 nargs_ = it->args.size();
388 args_ = tuple(nargs_);
389 for (size_t i = 0; i < nargs; ++i) {
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100390 handle item = PyTuple_GET_ITEM(args, i);
391 PyTuple_SET_ITEM(args_.ptr(), i, item.inc_ref().ptr());
392 }
393
394 int arg_ctr = 0;
395 for (auto const &it2 : it->args) {
396 int index = arg_ctr++;
397 if (PyTuple_GET_ITEM(args_.ptr(), index))
398 continue;
399
400 handle value;
401 if (kwargs)
402 value = PyDict_GetItemString(kwargs, it2.name);
403
404 if (value)
405 kwargs_consumed++;
406 else if (it2.value)
407 value = it2.value;
408
409 if (value) {
410 PyTuple_SET_ITEM(args_.ptr(), index, value.inc_ref().ptr());
411 } else {
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100412 kwargs_consumed = (size_t) -1; /* definite failure */
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100413 break;
414 }
415 }
416 }
Wenzel Jakobbd57eb42016-05-01 14:42:20 +0200417
418 try {
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100419 if ((kwargs_consumed == nkwargs || it->has_kwargs) &&
420 (nargs_ == it->nargs || it->has_args))
421 result = it->impl(it, args_, kwargs, parent);
Wenzel Jakob00062592016-07-01 16:07:35 +0200422 } catch (reference_cast_error &) {
Wenzel Jakobbd57eb42016-05-01 14:42:20 +0200423 result = PYBIND11_TRY_NEXT_OVERLOAD;
424 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100425
426 if (result.ptr() != PYBIND11_TRY_NEXT_OVERLOAD)
427 break;
428 }
Dean Moldovan135ba8d2016-09-10 11:58:02 +0200429 } catch (error_already_set &e) {
430 e.restore();
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400431 return nullptr;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100432 } catch (...) {
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400433 /* When an exception is caught, give each registered exception
434 translator a chance to translate it to a Python exception
435 in reverse order of registration.
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200436
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400437 A translator may choose to do one of the following:
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200438
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400439 - catch the exception and call PyErr_SetString or PyErr_SetObject
440 to set a standard (or custom) Python exception, or
441 - do nothing and let the exception fall through to the next translator, or
442 - delegate translation to the next translator by throwing a new type of exception. */
443
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200444 auto last_exception = std::current_exception();
Pim Schellart5a7d17f2016-06-17 17:35:59 -0400445 auto &registered_exception_translators = pybind11::detail::get_internals().registered_exception_translators;
446 for (auto& translator : registered_exception_translators) {
447 try {
448 translator(last_exception);
449 } catch (...) {
450 last_exception = std::current_exception();
451 continue;
452 }
453 return nullptr;
454 }
455 PyErr_SetString(PyExc_SystemError, "Exception escaped from default exception translator!");
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100456 return nullptr;
457 }
458
459 if (result.ptr() == PYBIND11_TRY_NEXT_OVERLOAD) {
Wenzel Jakob382484a2016-09-10 15:28:37 +0900460 if (overloads->is_operator)
461 return handle(Py_NotImplemented).inc_ref().ptr();
462
Wenzel Jakobe99ebae2016-09-12 11:44:37 +0900463 std::string msg = std::string(overloads->name) + "(): incompatible " +
464 std::string(overloads->is_constructor ? "constructor" : "function") +
465 " arguments. The following argument types are supported:\n";
466
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100467 int ctr = 0;
468 for (detail::function_record *it2 = overloads; it2 != nullptr; it2 = it2->next) {
469 msg += " "+ std::to_string(++ctr) + ". ";
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400470
471 bool wrote_sig = false;
472 if (overloads->is_constructor) {
Dean Moldovanecced6c2016-07-31 20:03:18 +0200473 // For a constructor, rewrite `(self: Object, arg0, ...) -> NoneType` as `Object(arg0, ...)`
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400474 std::string sig = it2->signature;
Dean Moldovanecced6c2016-07-31 20:03:18 +0200475 size_t start = sig.find('(') + 7; // skip "(self: "
Jason Rhinelander4e45e182016-07-17 17:43:00 -0400476 if (start < sig.size()) {
477 // End at the , for the next argument
478 size_t end = sig.find(", "), next = end + 2;
479 size_t ret = sig.rfind(" -> ");
480 // Or the ), if there is no comma:
481 if (end >= sig.size()) next = end = sig.find(')');
482 if (start < end && next < sig.size()) {
483 msg.append(sig, start, end - start);
484 msg += '(';
485 msg.append(sig, next, ret - next);
486 wrote_sig = true;
487 }
488 }
489 }
490 if (!wrote_sig) msg += it2->signature;
491
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100492 msg += "\n";
493 }
Wenzel Jakobe99ebae2016-09-12 11:44:37 +0900494 msg += "\nInvoked with: ";
Andreas Bergmeier16d43942016-05-24 09:19:35 +0200495 tuple args_(args, true);
Wenzel Jakob1f66a582016-07-18 10:47:10 +0200496 for (size_t ti = overloads->is_constructor ? 1 : 0; ti < args_.size(); ++ti) {
Andreas Bergmeier16d43942016-05-24 09:19:35 +0200497 msg += static_cast<std::string>(static_cast<object>(args_[ti]).str());
498 if ((ti + 1) != args_.size() )
499 msg += ", ";
500 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100501 PyErr_SetString(PyExc_TypeError, msg.c_str());
502 return nullptr;
503 } else if (!result) {
504 std::string msg = "Unable to convert function return value to a "
505 "Python type! The signature was\n\t";
506 msg += it->signature;
507 PyErr_SetString(PyExc_TypeError, msg.c_str());
508 return nullptr;
509 } else {
510 if (overloads->is_constructor) {
Wenzel Jakob772c6d52016-04-30 19:56:10 +0200511 /* When a constructor ran successfully, the corresponding
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100512 holder type (e.g. std::unique_ptr) must still be initialized. */
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100513 PyObject *inst = PyTuple_GET_ITEM(args, 0);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100514 auto tinfo = detail::get_type_info(Py_TYPE(inst));
515 tinfo->init_holder(inst, nullptr);
516 }
517 return result.ptr();
518 }
519 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200520};
521
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100522/// Wrapper for Python extension modules
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200523class module : public object {
524public:
Wenzel Jakobb1b71402015-10-18 16:48:30 +0200525 PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200526
527 module(const char *name, const char *doc = nullptr) {
Wenzel Jakob57082212015-09-04 23:42:12 +0200528#if PY_MAJOR_VERSION >= 3
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200529 PyModuleDef *def = new PyModuleDef();
530 memset(def, 0, sizeof(PyModuleDef));
531 def->m_name = name;
532 def->m_doc = doc;
533 def->m_size = -1;
534 Py_INCREF(def);
535 m_ptr = PyModule_Create(def);
Wenzel Jakob57082212015-09-04 23:42:12 +0200536#else
537 m_ptr = Py_InitModule3(name, nullptr, doc);
538#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200539 if (m_ptr == nullptr)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100540 pybind11_fail("Internal error in module::module()");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200541 inc_ref();
542 }
543
Wenzel Jakob71867832015-07-29 17:43:52 +0200544 template <typename Func, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100545 module &def(const char *name_, Func &&f, const Extra& ... extra) {
Wenzel Jakob71867832015-07-29 17:43:52 +0200546 cpp_function func(std::forward<Func>(f), name(name_),
Wenzel Jakoba6501792016-02-04 23:02:07 +0100547 sibling((handle) attr(name_)), scope(*this), extra...);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100548 /* PyModule_AddObject steals a reference to 'func' */
549 PyModule_AddObject(ptr(), name_, func.inc_ref().ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200550 return *this;
551 }
552
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200553 module def_submodule(const char *name, const char *doc = nullptr) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200554 std::string full_name = std::string(PyModule_GetName(m_ptr))
555 + std::string(".") + std::string(name);
556 module result(PyImport_AddModule(full_name.c_str()), true);
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200557 if (doc)
Wenzel Jakob8f4eb002015-10-15 18:13:33 +0200558 result.attr("__doc__") = pybind11::str(doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200559 attr(name) = result;
560 return result;
561 }
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200562
563 static module import(const char *name) {
Wenzel Jakobdd57a342015-12-26 14:04:52 +0100564 PyObject *obj = PyImport_ImportModule(name);
565 if (!obj)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100566 pybind11_fail("Module \"" + std::string(name) + "\" not found!");
Wenzel Jakobdd57a342015-12-26 14:04:52 +0100567 return module(obj, false);
Wenzel Jakobdb028d62015-10-13 23:44:25 +0200568 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200569};
570
571NAMESPACE_BEGIN(detail)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100572/// Generic support for creating new Python heap types
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100573class generic_type : public object {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400574 template <typename...> friend class class_;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200575public:
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100576 PYBIND11_OBJECT_DEFAULT(generic_type, object, PyType_Check)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100577protected:
578 void initialize(type_record *rec) {
579 if (rec->base_type) {
580 if (rec->base_handle)
581 pybind11_fail("generic_type: specified base type multiple times!");
582 rec->base_handle = detail::get_type_handle(*(rec->base_type));
583 if (!rec->base_handle) {
584 std::string tname(rec->base_type->name());
585 detail::clean_type_id(tname);
586 pybind11_fail("generic_type: type \"" + std::string(rec->name) +
587 "\" referenced unknown base type \"" + tname + "\"");
588 }
589 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200590
Wenzel Jakob38d8b8c2016-05-31 09:53:28 +0200591 auto &internals = get_internals();
592 auto tindex = std::type_index(*(rec->type));
593
594 if (internals.registered_types_cpp.find(tindex) !=
595 internals.registered_types_cpp.end())
596 pybind11_fail("generic_type: type \"" + std::string(rec->name) +
597 "\" is already registered!");
598
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100599 object name(PYBIND11_FROM_STRING(rec->name), false);
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200600 object scope_module;
601 if (rec->scope) {
602 scope_module = (object) rec->scope.attr("__module__");
603 if (!scope_module)
604 scope_module = (object) rec->scope.attr("__name__");
605 }
606
607#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
608 /* Qualified names for Python >= 3.3 */
609 object scope_qualname;
610 if (rec->scope)
611 scope_qualname = (object) rec->scope.attr("__qualname__");
612 object ht_qualname;
613 if (scope_qualname) {
614 ht_qualname = object(PyUnicode_FromFormat(
615 "%U.%U", scope_qualname.ptr(), name.ptr()), false);
616 } else {
617 ht_qualname = name;
618 }
619#endif
620 std::string full_name = (scope_module ? ((std::string) scope_module.str() + "." + rec->name)
621 : std::string(rec->name));
622
623 char *tp_doc = nullptr;
624 if (rec->doc) {
625 /* Allocate memory for docstring (using PyObject_MALLOC, since
626 Python will free this later on) */
627 size_t size = strlen(rec->doc) + 1;
628 tp_doc = (char *) PyObject_MALLOC(size);
629 memcpy((void *) tp_doc, rec->doc, size);
630 }
631
632 object type_holder(PyType_Type.tp_alloc(&PyType_Type, 0), false);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100633 auto type = (PyHeapTypeObject*) type_holder.ptr();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200634
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100635 if (!type_holder || !name)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100636 pybind11_fail("generic_type: unable to create type object!");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200637
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100638 /* Register supplemental type information in C++ dict */
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100639 detail::type_info *tinfo = new detail::type_info();
640 tinfo->type = (PyTypeObject *) type;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100641 tinfo->type_size = rec->type_size;
642 tinfo->init_holder = rec->init_holder;
Wenzel Jakob38d8b8c2016-05-31 09:53:28 +0200643 internals.registered_types_cpp[tindex] = tinfo;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100644 internals.registered_types_py[type] = tinfo;
645
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100646 /* Basic type attributes */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200647 type->ht_type.tp_name = strdup(full_name.c_str());
Wenzel Jakob0a078052016-05-29 13:40:40 +0200648 type->ht_type.tp_basicsize = (ssize_t) rec->instance_size;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100649 type->ht_type.tp_base = (PyTypeObject *) rec->base_handle.ptr();
650 rec->base_handle.inc_ref();
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100651
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100652 type->ht_name = name.release().ptr();
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100653
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200654#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
655 type->ht_qualname = ht_qualname.release().ptr();
656#endif
657
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100658 /* Supported protocols */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200659 type->ht_type.tp_as_number = &type->as_number;
660 type->ht_type.tp_as_sequence = &type->as_sequence;
661 type->ht_type.tp_as_mapping = &type->as_mapping;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100662
663 /* Supported elementary operations */
664 type->ht_type.tp_init = (initproc) init;
665 type->ht_type.tp_new = (newfunc) new_instance;
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100666 type->ht_type.tp_dealloc = rec->dealloc;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100667
668 /* Support weak references (needed for the keep_alive feature) */
Wenzel Jakob88d1d042016-01-20 01:26:42 +0100669 type->ht_type.tp_weaklistoffset = offsetof(instance_essentials<void>, weakrefs);
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100670
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100671 /* Flags */
672 type->ht_type.tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
673#if PY_MAJOR_VERSION < 3
674 type->ht_type.tp_flags |= Py_TPFLAGS_CHECKTYPES;
675#endif
676 type->ht_type.tp_flags &= ~Py_TPFLAGS_HAVE_GC;
677
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200678 type->ht_type.tp_doc = tp_doc;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200679
680 if (PyType_Ready(&type->ht_type) < 0)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100681 pybind11_fail("generic_type: PyType_Ready failed!");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200682
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100683 m_ptr = type_holder.ptr();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200684
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100685 if (scope_module) // Needed by pydoc
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100686 attr("__module__") = scope_module;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200687
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100688 /* Register type with the parent scope */
Wenzel Jakobb2825952016-04-13 23:33:00 +0200689 if (rec->scope)
690 rec->scope.attr(handle(type->ht_name)) = *this;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100691
692 type_holder.release();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200693 }
694
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100695 /// Allocate a metaclass on demand (for static properties)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200696 handle metaclass() {
697 auto &ht_type = ((PyHeapTypeObject *) m_ptr)->ht_type;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100698 auto &ob_type = PYBIND11_OB_TYPE(ht_type);
Wenzel Jakob57082212015-09-04 23:42:12 +0200699
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200700 if (ob_type == &PyType_Type) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100701 std::string name_ = std::string(ht_type.tp_name) + "__Meta";
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200702#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
703 object ht_qualname(PyUnicode_FromFormat(
704 "%U__Meta", ((object) attr("__qualname__")).ptr()), false);
705#endif
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100706 object name(PYBIND11_FROM_STRING(name_.c_str()), false);
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200707 object type_holder(PyType_Type.tp_alloc(&PyType_Type, 0), false);
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100708 if (!type_holder || !name)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100709 pybind11_fail("generic_type::metaclass(): unable to create type object!");
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100710
711 auto type = (PyHeapTypeObject*) type_holder.ptr();
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100712 type->ht_name = name.release().ptr();
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200713
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100714#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
715 /* Qualified names for Python >= 3.3 */
Wenzel Jakobc47d4982016-07-11 23:40:28 +0200716 type->ht_qualname = ht_qualname.release().ptr();
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100717#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200718 type->ht_type.tp_name = strdup(name_.c_str());
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100719 type->ht_type.tp_base = ob_type;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100720 type->ht_type.tp_flags |= (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE) &
721 ~Py_TPFLAGS_HAVE_GC;
722
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200723 if (PyType_Ready(&type->ht_type) < 0)
Wenzel Jakob678d7872016-01-17 22:36:41 +0100724 pybind11_fail("generic_type::metaclass(): PyType_Ready failed!");
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100725
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100726 ob_type = (PyTypeObject *) type_holder.release().ptr();
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200727 }
728 return handle((PyObject *) ob_type);
729 }
730
731 static int init(void *self, PyObject *, PyObject *) {
732 std::string msg = std::string(Py_TYPE(self)->tp_name) + ": No constructor defined!";
733 PyErr_SetString(PyExc_TypeError, msg.c_str());
734 return -1;
735 }
736
737 static PyObject *new_instance(PyTypeObject *type, PyObject *, PyObject *) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100738 instance<void> *self = (instance<void> *) PyType_GenericAlloc((PyTypeObject *) type, 0);
739 auto tinfo = detail::get_type_info(type);
740 self->value = ::operator new(tinfo->type_size);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200741 self->owned = true;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200742 self->constructed = false;
Jason Rhinelander1b05ce52016-08-09 17:57:59 -0400743 detail::get_internals().registered_instances.emplace(self->value, (PyObject *) self);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200744 return (PyObject *) self;
745 }
746
747 static void dealloc(instance<void> *self) {
748 if (self->value) {
Jason Rhinelander1b05ce52016-08-09 17:57:59 -0400749 auto instance_type = Py_TYPE(self);
750 auto &registered_instances = detail::get_internals().registered_instances;
751 auto range = registered_instances.equal_range(self->value);
752 bool found = false;
753 for (auto it = range.first; it != range.second; ++it) {
754 if (instance_type == Py_TYPE(it->second)) {
755 registered_instances.erase(it);
756 found = true;
757 break;
758 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200759 }
Jason Rhinelander1b05ce52016-08-09 17:57:59 -0400760 if (!found)
761 pybind11_fail("generic_type::dealloc(): Tried to deallocate unregistered instance!");
762
Wenzel Jakob5f218b32016-01-17 22:36:39 +0100763 if (self->weakrefs)
764 PyObject_ClearWeakRefs((PyObject *) self);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200765 }
766 Py_TYPE(self)->tp_free((PyObject*) self);
767 }
768
Wenzel Jakob43398a82015-07-28 16:12:20 +0200769 void install_buffer_funcs(
770 buffer_info *(*get_buffer)(PyObject *, void *),
771 void *get_buffer_data) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200772 PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
773 type->ht_type.tp_as_buffer = &type->as_buffer;
Wenzel Jakob57082212015-09-04 23:42:12 +0200774#if PY_MAJOR_VERSION < 3
775 type->ht_type.tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
776#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200777 type->as_buffer.bf_getbuffer = getbuffer;
778 type->as_buffer.bf_releasebuffer = releasebuffer;
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100779 auto tinfo = detail::get_type_info(&type->ht_type);
780 tinfo->get_buffer = get_buffer;
781 tinfo->get_buffer_data = get_buffer_data;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200782 }
783
784 static int getbuffer(PyObject *obj, Py_buffer *view, int flags) {
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100785 auto tinfo = detail::get_type_info(Py_TYPE(obj));
786 if (view == nullptr || obj == nullptr || !tinfo || !tinfo->get_buffer) {
787 PyErr_SetString(PyExc_BufferError, "generic_type::getbuffer(): Internal error");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200788 return -1;
789 }
790 memset(view, 0, sizeof(Py_buffer));
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100791 buffer_info *info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200792 view->obj = obj;
793 view->ndim = 1;
794 view->internal = info;
795 view->buf = info->ptr;
Wenzel Jakob0a078052016-05-29 13:40:40 +0200796 view->itemsize = (ssize_t) info->itemsize;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200797 view->len = view->itemsize;
798 for (auto s : info->shape)
799 view->len *= s;
800 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
801 view->format = const_cast<char *>(info->format.c_str());
802 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
Wenzel Jakob0a078052016-05-29 13:40:40 +0200803 view->ndim = (int) info->ndim;
Wenzel Jakob27e8e102016-01-17 22:36:37 +0100804 view->strides = (ssize_t *) &info->strides[0];
805 view->shape = (ssize_t *) &info->shape[0];
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200806 }
807 Py_INCREF(view->obj);
808 return 0;
809 }
810
811 static void releasebuffer(PyObject *, Py_buffer *view) { delete (buffer_info *) view->internal; }
812};
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400813
814template <template<typename> class Predicate, typename... BaseTypes> struct class_selector;
815template <template<typename> class Predicate, typename Base, typename... Bases>
816struct class_selector<Predicate, Base, Bases...> {
817 static inline void set_bases(detail::type_record &record) {
818 if (Predicate<Base>::value) record.base_type = &typeid(Base);
819 else class_selector<Predicate, Bases...>::set_bases(record);
820 }
821};
822template <template<typename> class Predicate>
823struct class_selector<Predicate> {
824 static inline void set_bases(detail::type_record &) {}
825};
826
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200827NAMESPACE_END(detail)
828
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400829template <typename type_, typename... options>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100830class class_ : public detail::generic_type {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400831 template <typename T> using is_holder = detail::is_holder_type<type_, T>;
832 template <typename T> using is_subtype = detail::bool_constant<std::is_base_of<type_, T>::value && !std::is_same<T, type_>::value>;
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400833 template <typename T> using is_base_class = detail::bool_constant<std::is_base_of<T, type_>::value && !std::is_same<T, type_>::value>;
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400834 template <typename T> using is_valid_class_option =
835 detail::bool_constant<
836 is_holder<T>::value ||
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400837 is_subtype<T>::value ||
838 is_base_class<T>::value
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400839 >;
840
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200841public:
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400842 using type = type_;
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400843 using type_alias = detail::first_of_t<is_subtype, void, options...>;
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400844 constexpr static bool has_alias = !std::is_void<type_alias>::value;
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400845 using holder_type = detail::first_of_t<is_holder, std::unique_ptr<type>, options...>;
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400846 using instance_type = detail::instance<type, holder_type>;
847
848 static_assert(detail::all_of_t<is_valid_class_option, options...>::value,
849 "Unknown/invalid class_ template parameters provided");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200850
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400851 static_assert(detail::count_t<is_base_class, options...>::value <= 1,
852 "Invalid class_ base types: multiple inheritance is not supported");
853
Wenzel Jakobd561cb02016-01-17 22:36:41 +0100854 PYBIND11_OBJECT(class_, detail::generic_type, PyType_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200855
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100856 template <typename... Extra>
857 class_(handle scope, const char *name, const Extra &... extra) {
858 detail::type_record record;
859 record.scope = scope;
860 record.name = name;
861 record.type = &typeid(type);
Jason Rhinelander9c6859e2016-09-08 11:03:08 -0400862 record.type_size = sizeof(detail::conditional_t<has_alias, type_alias, type>);
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100863 record.instance_size = sizeof(instance_type);
864 record.init_holder = init_holder;
865 record.dealloc = dealloc;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200866
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400867 detail::class_selector<is_base_class, options...>::set_bases(record);
868
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100869 /* Process optional arguments, if any */
870 detail::process_attributes<Extra...>::init(extra..., &record);
871
872 detail::generic_type::initialize(&record);
Wenzel Jakob86d825f2016-05-26 13:19:27 +0200873
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400874 if (has_alias) {
Wenzel Jakob86d825f2016-05-26 13:19:27 +0200875 auto &instances = pybind11::detail::get_internals().registered_types_cpp;
876 instances[std::type_index(typeid(type_alias))] = instances[std::type_index(typeid(type))];
877 }
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100878 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200879
Wenzel Jakob71867832015-07-29 17:43:52 +0200880 template <typename Func, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100881 class_ &def(const char *name_, Func&& f, const Extra&... extra) {
Wenzel Jakob57082212015-09-04 23:42:12 +0200882 cpp_function cf(std::forward<Func>(f), name(name_),
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100883 sibling(attr(name_)), is_method(*this),
884 extra...);
Wenzel Jakob57082212015-09-04 23:42:12 +0200885 attr(cf.name()) = cf;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200886 return *this;
887 }
888
Wenzel Jakob71867832015-07-29 17:43:52 +0200889 template <typename Func, typename... Extra> class_ &
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100890 def_static(const char *name_, Func f, const Extra&... extra) {
Wenzel Jakob57082212015-09-04 23:42:12 +0200891 cpp_function cf(std::forward<Func>(f), name(name_),
Wenzel Jakoba6501792016-02-04 23:02:07 +0100892 sibling(attr(name_)), scope(*this), extra...);
Wenzel Jakob57082212015-09-04 23:42:12 +0200893 attr(cf.name()) = cf;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200894 return *this;
895 }
896
Wenzel Jakob71867832015-07-29 17:43:52 +0200897 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100898 class_ &def(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400899 op.execute(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200900 return *this;
901 }
902
Wenzel Jakob71867832015-07-29 17:43:52 +0200903 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100904 class_ & def_cast(const detail::op_<id, ot, L, R> &op, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400905 op.execute_cast(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200906 return *this;
907 }
908
Wenzel Jakob71867832015-07-29 17:43:52 +0200909 template <typename... Args, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100910 class_ &def(const detail::init<Args...> &init, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400911 init.execute(*this, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200912 return *this;
913 }
914
Wenzel Jakob86d825f2016-05-26 13:19:27 +0200915 template <typename... Args, typename... Extra>
916 class_ &def(const detail::init_alias<Args...> &init, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -0400917 init.execute(*this, extra...);
Wenzel Jakob86d825f2016-05-26 13:19:27 +0200918 return *this;
919 }
920
Wenzel Jakob71867832015-07-29 17:43:52 +0200921 template <typename Func> class_& def_buffer(Func &&func) {
Wenzel Jakob43398a82015-07-28 16:12:20 +0200922 struct capture { Func func; };
923 capture *ptr = new capture { std::forward<Func>(func) };
924 install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200925 detail::type_caster<type> caster;
926 if (!caster.load(obj, false))
927 return nullptr;
Wenzel Jakob43398a82015-07-28 16:12:20 +0200928 return new buffer_info(((capture *) ptr)->func(caster));
929 }, ptr);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200930 return *this;
931 }
932
Wenzel Jakob71867832015-07-29 17:43:52 +0200933 template <typename C, typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100934 class_ &def_readwrite(const char *name, D C::*pm, const Extra&... extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +0100935 cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; }, is_method(*this)),
936 fset([pm](C &c, const D &value) { c.*pm = value; }, is_method(*this));
937 def_property(name, fget, fset, return_value_policy::reference_internal, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200938 return *this;
939 }
940
Wenzel Jakob71867832015-07-29 17:43:52 +0200941 template <typename C, typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100942 class_ &def_readonly(const char *name, const D C::*pm, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +0100943 cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; }, is_method(*this));
944 def_property_readonly(name, fget, return_value_policy::reference_internal, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200945 return *this;
946 }
947
Wenzel Jakob71867832015-07-29 17:43:52 +0200948 template <typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100949 class_ &def_readwrite_static(const char *name, D *pm, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +0100950 cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this)),
951 fset([pm](object, const D &value) { *pm = value; }, scope(*this));
952 def_property_static(name, fget, fset, return_value_policy::reference, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200953 return *this;
954 }
955
Wenzel Jakob71867832015-07-29 17:43:52 +0200956 template <typename D, typename... Extra>
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100957 class_ &def_readonly_static(const char *name, const D *pm, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +0100958 cpp_function fget([pm](object) -> const D &{ return *pm; }, scope(*this));
959 def_property_readonly_static(name, fget, return_value_policy::reference, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200960 return *this;
961 }
962
Wenzel Jakob84ec78f2016-03-21 17:54:24 +0100963 template <typename... Extra>
964 class_ &def_property_readonly(const char *name, const cpp_function &fget, const Extra& ...extra) {
965 def_property(name, fget, cpp_function(), extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200966 return *this;
967 }
968
Wenzel Jakob84ec78f2016-03-21 17:54:24 +0100969 template <typename... Extra>
970 class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const Extra& ...extra) {
971 def_property_static(name, fget, cpp_function(), extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200972 return *this;
973 }
974
Wenzel Jakob84ec78f2016-03-21 17:54:24 +0100975 template <typename... Extra>
976 class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
Wenzel Jakob0b489582016-03-25 16:13:10 +0100977 return def_property_static(name, fget, fset, is_method(*this), extra...);
Wenzel Jakob84ec78f2016-03-21 17:54:24 +0100978 }
979
980 template <typename... Extra>
981 class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const Extra& ...extra) {
982 auto rec_fget = get_function_record(fget), rec_fset = get_function_record(fset);
Wenzel Jakob7c99ff22016-06-02 20:33:01 +0200983 char *doc_prev = rec_fget->doc; /* 'extra' field may include a property-specific documentation string */
Wenzel Jakob84ec78f2016-03-21 17:54:24 +0100984 detail::process_attributes<Extra...>::init(extra..., rec_fget);
Wenzel Jakob7c99ff22016-06-02 20:33:01 +0200985 if (rec_fget->doc && rec_fget->doc != doc_prev) {
986 free(doc_prev);
987 rec_fget->doc = strdup(rec_fget->doc);
988 }
989 if (rec_fset) {
990 doc_prev = rec_fset->doc;
Wenzel Jakob84ec78f2016-03-21 17:54:24 +0100991 detail::process_attributes<Extra...>::init(extra..., rec_fset);
Wenzel Jakob7c99ff22016-06-02 20:33:01 +0200992 if (rec_fset->doc && rec_fset->doc != doc_prev) {
993 free(doc_prev);
994 rec_fset->doc = strdup(rec_fset->doc);
995 }
996 }
Wenzel Jakob84ec78f2016-03-21 17:54:24 +0100997 pybind11::str doc_obj = pybind11::str(rec_fget->doc ? rec_fget->doc : "");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200998 object property(
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100999 PyObject_CallFunctionObjArgs((PyObject *) &PyProperty_Type, fget.ptr() ? fget.ptr() : Py_None,
1000 fset.ptr() ? fset.ptr() : Py_None, Py_None, doc_obj.ptr(), nullptr), false);
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001001 if (rec_fget->class_)
1002 attr(name) = property;
1003 else
1004 metaclass().attr(name) = property;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001005 return *this;
1006 }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001007
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001008private:
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001009 /// Initialize holder object, variant 1: object derives from enable_shared_from_this
1010 template <typename T>
1011 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 +01001012 try {
hbruintjes70d2e572016-07-01 12:39:55 +02001013 new (&inst->holder) holder_type(std::static_pointer_cast<typename holder_type::element_type>(inst->value->shared_from_this()));
Wenzel Jakob6e213c92015-11-24 23:05:58 +01001014 } catch (const std::bad_weak_ptr &) {
1015 new (&inst->holder) holder_type(inst->value);
1016 }
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001017 }
1018
1019 /// Initialize holder object, variant 2: try to construct from existing holder object, if possible
1020 template <typename T = holder_type,
1021 typename std::enable_if<std::is_copy_constructible<T>::value, int>::type = 0>
1022 static void init_holder_helper(instance_type *inst, const holder_type *holder_ptr, const void * /* dummy */) {
1023 if (holder_ptr)
1024 new (&inst->holder) holder_type(*holder_ptr);
1025 else
1026 new (&inst->holder) holder_type(inst->value);
1027 }
1028
1029 /// Initialize holder object, variant 3: holder is not copy constructible (e.g. unique_ptr), always initialize from raw pointer
1030 template <typename T = holder_type,
1031 typename std::enable_if<!std::is_copy_constructible<T>::value, int>::type = 0>
1032 static void init_holder_helper(instance_type *inst, const holder_type * /* unused */, const void * /* dummy */) {
1033 new (&inst->holder) holder_type(inst->value);
1034 }
1035
1036 /// Initialize holder object of an instance, possibly given a pointer to an existing holder
1037 static void init_holder(PyObject *inst_, const void *holder_ptr) {
1038 auto inst = (instance_type *) inst_;
1039 init_holder_helper(inst, (const holder_type *) holder_ptr, inst->value);
Wenzel Jakob6e213c92015-11-24 23:05:58 +01001040 inst->constructed = true;
1041 }
1042
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001043 static void dealloc(PyObject *inst_) {
1044 instance_type *inst = (instance_type *) inst_;
1045 if (inst->owned) {
1046 if (inst->constructed)
1047 inst->holder.~holder_type();
1048 else
1049 ::operator delete(inst->value);
1050 }
Wenzel Jakobd561cb02016-01-17 22:36:41 +01001051 generic_type::dealloc((detail::instance<void> *) inst);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001052 }
Wenzel Jakob84ec78f2016-03-21 17:54:24 +01001053
1054 static detail::function_record *get_function_record(handle h) {
1055 h = detail::get_function(h);
1056 return h ? (detail::function_record *) capsule(
1057 PyCFunction_GetSelf(h.ptr()), true) : nullptr;
1058 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001059};
1060
1061/// Binds C++ enumerations and enumeration classes to Python
1062template <typename Type> class enum_ : public class_<Type> {
1063public:
Wenzel Jakob8ac97152016-09-05 17:20:50 +09001064 using class_<Type>::def;
Pim Schellarte5b42ef2016-08-02 10:58:32 -04001065 using UnderlyingType = typename std::underlying_type<Type>::type;
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001066 template <typename... Extra>
1067 enum_(const handle &scope, const char *name, const Extra&... extra)
1068 : class_<Type>(scope, name, extra...), m_parent(scope) {
Pim Schellarte5b42ef2016-08-02 10:58:32 -04001069 auto entries = new std::unordered_map<UnderlyingType, const char *>();
Wenzel Jakob8ac97152016-09-05 17:20:50 +09001070 def("__repr__", [name, entries](Type value) -> std::string {
Pim Schellarte5b42ef2016-08-02 10:58:32 -04001071 auto it = entries->find((UnderlyingType) value);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001072 return std::string(name) + "." +
1073 ((it == entries->end()) ? std::string("???")
1074 : std::string(it->second));
1075 });
Wenzel Jakob8ac97152016-09-05 17:20:50 +09001076 def("__init__", [](Type& value, UnderlyingType i) { value = (Type)i; });
1077 def("__init__", [](Type& value, UnderlyingType i) { new (&value) Type((Type) i); });
1078 def("__int__", [](Type value) { return (UnderlyingType) value; });
1079 def("__eq__", [](const Type &value, Type *value2) { return value2 && value == *value2; });
1080 def("__ne__", [](const Type &value, Type *value2) { return !value2 || value != *value2; });
Jason Rhinelanderd41a2732016-08-04 00:21:37 -04001081 if (std::is_convertible<Type, UnderlyingType>::value) {
1082 // Don't provide comparison with the underlying type if the enum isn't convertible,
1083 // i.e. if Type is a scoped enum, mirroring the C++ behaviour. (NB: we explicitly
1084 // convert Type to UnderlyingType below anyway because this needs to compile).
Wenzel Jakob8ac97152016-09-05 17:20:50 +09001085 def("__eq__", [](const Type &value, UnderlyingType value2) { return (UnderlyingType) value == value2; });
1086 def("__ne__", [](const Type &value, UnderlyingType value2) { return (UnderlyingType) value != value2; });
Jason Rhinelanderd41a2732016-08-04 00:21:37 -04001087 }
Wenzel Jakob8ac97152016-09-05 17:20:50 +09001088 def("__hash__", [](const Type &value) { return (UnderlyingType) value; });
Wenzel Jakobfe342412016-09-06 13:02:29 +09001089 // Pickling and unpickling -- needed for use with the 'multiprocessing' module
Wenzel Jakob8ac97152016-09-05 17:20:50 +09001090 def("__getstate__", [](const Type &value) { return pybind11::make_tuple((UnderlyingType) value); });
1091 def("__setstate__", [](Type &p, tuple t) { new (&p) Type((Type) t[0].cast<UnderlyingType>()); });
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001092 m_entries = entries;
1093 }
1094
1095 /// Export enumeration entries into the parent scope
1096 void export_values() {
1097 PyObject *dict = ((PyTypeObject *) this->m_ptr)->tp_dict;
1098 PyObject *key, *value;
Wenzel Jakob27e8e102016-01-17 22:36:37 +01001099 ssize_t pos = 0;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001100 while (PyDict_Next(dict, &pos, &key, &value))
1101 if (PyObject_IsInstance(value, this->m_ptr))
1102 m_parent.attr(key) = value;
1103 }
1104
1105 /// Add an enumeration entry
1106 enum_& value(char const* name, Type value) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02001107 this->attr(name) = pybind11::cast(value, return_value_policy::copy);
Pim Schellarte5b42ef2016-08-02 10:58:32 -04001108 (*m_entries)[(UnderlyingType) value] = name;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001109 return *this;
1110 }
1111private:
Pim Schellarte5b42ef2016-08-02 10:58:32 -04001112 std::unordered_map<UnderlyingType, const char *> *m_entries;
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001113 handle m_parent;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001114};
1115
1116NAMESPACE_BEGIN(detail)
Wenzel Jakob71867832015-07-29 17:43:52 +02001117template <typename... Args> struct init {
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001118 template <typename Class, typename... Extra, enable_if_t<!Class::has_alias, int> = 0>
1119 static void execute(Class &cl, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001120 using Base = typename Class::type;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001121 /// Function which calls a specific C++ in-place constructor
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001122 cl.def("__init__", [](Base *self_, Args... args) { new (self_) Base(args...); }, extra...);
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001123 }
1124
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001125 template <typename Class, typename... Extra,
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001126 enable_if_t<Class::has_alias &&
1127 std::is_constructible<typename Class::type, Args...>::value, int> = 0>
1128 static void execute(Class &cl, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001129 using Base = typename Class::type;
1130 using Alias = typename Class::type_alias;
1131 handle cl_type = cl;
1132 cl.def("__init__", [cl_type](handle self_, Args... args) {
Wenzel Jakob69e1a5c2016-05-26 14:29:31 +02001133 if (self_.get_type() == cl_type)
1134 new (self_.cast<Base *>()) Base(args...);
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001135 else
Wenzel Jakob69e1a5c2016-05-26 14:29:31 +02001136 new (self_.cast<Alias *>()) Alias(args...);
Wenzel Jakob86d825f2016-05-26 13:19:27 +02001137 }, extra...);
1138 }
1139
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001140 template <typename Class, typename... Extra,
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001141 enable_if_t<Class::has_alias &&
1142 !std::is_constructible<typename Class::type, Args...>::value, int> = 0>
1143 static void execute(Class &cl, const Extra&... extra) {
1144 init_alias<Args...>::execute(cl, extra...);
1145 }
1146};
1147template <typename... Args> struct init_alias {
1148 template <typename Class, typename... Extra,
1149 enable_if_t<Class::has_alias && std::is_constructible<typename Class::type_alias, Args...>::value, int> = 0>
1150 static void execute(Class &cl, const Extra&... extra) {
Jason Rhinelander5fffe202016-09-06 12:17:06 -04001151 using Alias = typename Class::type_alias;
1152 cl.def("__init__", [](Alias *self_, Args... args) { new (self_) Alias(args...); }, extra...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001153 }
1154};
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001155
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001156
Jason Rhinelanderf2ecd892016-08-10 12:08:04 -04001157inline void keep_alive_impl(handle nurse, handle patient) {
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001158 /* Clever approach based on weak references taken from Boost.Python */
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001159 if (!nurse || !patient)
Wenzel Jakob678d7872016-01-17 22:36:41 +01001160 pybind11_fail("Could not activate keep_alive!");
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001161
Ivan Smirnov984c7622016-08-29 02:38:47 +01001162 if (patient.is_none() || nurse.is_none())
Glen Walkerf45bb582016-08-16 17:50:43 +12001163 return; /* Nothing to keep alive or nothing to be kept alive by */
Wenzel Jakob9b880ba2016-04-25 03:25:13 +02001164
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001165 cpp_function disable_lifesupport(
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001166 [patient](handle weakref) { patient.dec_ref(); weakref.dec_ref(); });
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001167
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001168 weakref wr(nurse, disable_lifesupport);
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001169
Wenzel Jakobb2c2c792016-01-17 22:36:40 +01001170 patient.inc_ref(); /* reference patient and leak the weak reference */
1171 (void) wr.release();
Wenzel Jakob5f218b32016-01-17 22:36:39 +01001172}
1173
Jason Rhinelanderf2ecd892016-08-10 12:08:04 -04001174PYBIND11_NOINLINE inline void keep_alive_impl(int Nurse, int Patient, handle args, handle ret) {
1175 handle nurse (Nurse > 0 ? PyTuple_GetItem(args.ptr(), Nurse - 1) : ret.ptr());
1176 handle patient(Patient > 0 ? PyTuple_GetItem(args.ptr(), Patient - 1) : ret.ptr());
1177
1178 keep_alive_impl(nurse, patient);
1179}
1180
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001181template <typename Iterator, typename Sentinel, bool KeyIterator, return_value_policy Policy>
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001182struct iterator_state {
1183 Iterator it;
1184 Sentinel end;
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001185 bool first;
1186};
Wenzel Jakobb2825952016-04-13 23:33:00 +02001187
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001188NAMESPACE_END(detail)
1189
Ben Pritchard2de6e1d2016-02-18 13:20:15 -05001190template <typename... Args> detail::init<Args...> init() { return detail::init<Args...>(); }
Jason Rhinelanderec62d972016-09-09 02:42:51 -04001191template <typename... Args> detail::init_alias<Args...> init_alias() { return detail::init_alias<Args...>(); }
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001192
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001193template <return_value_policy Policy = return_value_policy::reference_internal,
1194 typename Iterator,
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001195 typename Sentinel,
Wenzel Jakob5dd33d82016-05-30 11:28:21 +02001196 typename ValueType = decltype(*std::declval<Iterator>()),
1197 typename... Extra>
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001198iterator make_iterator(Iterator first, Sentinel last, Extra &&... extra) {
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001199 typedef detail::iterator_state<Iterator, Sentinel, false, Policy> state;
Wenzel Jakobb2825952016-04-13 23:33:00 +02001200
1201 if (!detail::get_type_info(typeid(state))) {
Wenzel Jakob146397e2016-09-06 13:06:31 +09001202 class_<state>(handle(), "iterator")
Wenzel Jakobb2825952016-04-13 23:33:00 +02001203 .def("__iter__", [](state &s) -> state& { return s; })
Wenzel Jakob5dd33d82016-05-30 11:28:21 +02001204 .def("__next__", [](state &s) -> ValueType {
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001205 if (!s.first)
1206 ++s.it;
1207 else
1208 s.first = false;
Wenzel Jakobb2825952016-04-13 23:33:00 +02001209 if (s.it == s.end)
1210 throw stop_iteration();
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001211 return *s.it;
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001212 }, std::forward<Extra>(extra)..., Policy);
Wenzel Jakobb2825952016-04-13 23:33:00 +02001213 }
1214
Ivan Smirnovdaed1ab2016-06-17 22:29:39 +01001215 return (iterator) cast(state { first, last, true });
Wenzel Jakobb2825952016-04-13 23:33:00 +02001216}
Wenzel Jakob146397e2016-09-06 13:06:31 +09001217
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001218template <return_value_policy Policy = return_value_policy::reference_internal,
1219 typename Iterator,
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001220 typename Sentinel,
Ivan Smirnovc5a1c8a2016-08-24 23:27:19 +01001221 typename KeyType = decltype((*std::declval<Iterator>()).first),
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001222 typename... Extra>
Ivan Smirnov2b308e02016-08-24 23:29:04 +01001223iterator make_key_iterator(Iterator first, Sentinel last, Extra &&... extra) {
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001224 typedef detail::iterator_state<Iterator, Sentinel, true, Policy> state;
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001225
1226 if (!detail::get_type_info(typeid(state))) {
Wenzel Jakob146397e2016-09-06 13:06:31 +09001227 class_<state>(handle(), "iterator")
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001228 .def("__iter__", [](state &s) -> state& { return s; })
1229 .def("__next__", [](state &s) -> KeyType {
1230 if (!s.first)
1231 ++s.it;
1232 else
1233 s.first = false;
1234 if (s.it == s.end)
1235 throw stop_iteration();
Ivan Smirnovc5a1c8a2016-08-24 23:27:19 +01001236 return (*s.it).first;
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001237 }, std::forward<Extra>(extra)..., Policy);
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001238 }
1239
1240 return (iterator) cast(state { first, last, true });
1241}
Wenzel Jakobb2825952016-04-13 23:33:00 +02001242
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001243template <return_value_policy Policy = return_value_policy::reference_internal,
1244 typename Type, typename... Extra> iterator make_iterator(Type &value, Extra&&... extra) {
1245 return make_iterator<Policy>(std::begin(value), std::end(value), extra...);
Wenzel Jakobbf0c7dc2016-04-18 10:52:12 +02001246}
1247
Wenzel Jakobb212f6c2016-09-10 16:00:50 +09001248template <return_value_policy Policy = return_value_policy::reference_internal,
1249 typename Type, typename... Extra> iterator make_key_iterator(Type &value, Extra&&... extra) {
1250 return make_key_iterator<Policy>(std::begin(value), std::end(value), extra...);
Jason Rhinelander5aa85be2016-08-11 21:22:05 -04001251}
1252
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001253template <typename InputType, typename OutputType> void implicitly_convertible() {
Wenzel Jakob2ac50442016-01-17 22:36:35 +01001254 auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject * {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001255 if (!detail::type_caster<InputType>().load(obj, false))
1256 return nullptr;
1257 tuple args(1);
1258 args[0] = obj;
1259 PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
1260 if (result == nullptr)
1261 PyErr_Clear();
1262 return result;
1263 };
Wenzel Jakobb6cf75d2016-01-29 11:39:32 +01001264 auto &registered_types = detail::get_internals().registered_types_cpp;
1265 auto it = registered_types.find(std::type_index(typeid(OutputType)));
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001266 if (it == registered_types.end())
Wenzel Jakob678d7872016-01-17 22:36:41 +01001267 pybind11_fail("implicitly_convertible: Unable to find type " + type_id<OutputType>());
Wenzel Jakobd561cb02016-01-17 22:36:41 +01001268 ((detail::type_info *) it->second)->implicit_conversions.push_back(implicit_caster);
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001269}
1270
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001271template <typename ExceptionTranslator>
1272void register_exception_translator(ExceptionTranslator&& translator) {
1273 detail::get_internals().registered_exception_translators.push_front(
1274 std::forward<ExceptionTranslator>(translator));
1275}
1276
1277/* Wrapper to generate a new Python exception type.
1278 *
1279 * This should only be used with PyErr_SetString for now.
1280 * It is not (yet) possible to use as a py::base.
1281 * Template type argument is reserved for future use.
1282 */
1283template <typename type>
1284class exception : public object {
1285public:
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001286 exception(module &m, const std::string &name, PyObject* base=PyExc_Exception) {
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001287 std::string full_name = std::string(PyModule_GetName(m.ptr()))
1288 + std::string(".") + name;
1289 char* exception_name = const_cast<char*>(full_name.c_str());
1290 m_ptr = PyErr_NewException(exception_name, base, NULL);
1291 inc_ref(); // PyModule_AddObject() steals a reference
1292 PyModule_AddObject(m.ptr(), name.c_str(), m_ptr);
1293 }
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001294
1295 // Sets the current python exception to this exception object with the given message
1296 void operator()(const char *message) {
1297 PyErr_SetString(m_ptr, message);
1298 }
Pim Schellart5a7d17f2016-06-17 17:35:59 -04001299};
1300
Jason Rhinelanderb3794f12016-09-16 02:04:15 -04001301/** Registers a Python exception in `m` of the given `name` and installs an exception translator to
1302 * translate the C++ exception to the created Python exception using the exceptions what() method.
1303 * This is intended for simple exception translations; for more complex translation, register the
1304 * exception object and translator directly.
1305 */
1306template <typename CppException> exception<CppException>& register_exception(module &m, const std::string &name, PyObject* base = PyExc_Exception) {
1307 static exception<CppException> ex(m, name, base);
1308 register_exception_translator([](std::exception_ptr p) {
1309 if (!p) return;
1310 try {
1311 std::rethrow_exception(p);
1312 }
1313 catch (const CppException &e) {
1314 ex(e.what());
1315 }
1316 });
1317 return ex;
1318}
1319
Dean Moldovan67990d92016-08-29 18:03:34 +02001320NAMESPACE_BEGIN(detail)
1321PYBIND11_NOINLINE inline void print(tuple args, dict kwargs) {
1322 auto strings = tuple(args.size());
1323 for (size_t i = 0; i < args.size(); ++i) {
1324 strings[i] = args[i].cast<object>().str();
1325 }
1326 auto sep = kwargs["sep"] ? kwargs["sep"] : cast(" ");
1327 auto line = sep.attr("join").cast<object>()(strings);
1328
1329 auto file = kwargs["file"] ? kwargs["file"].cast<object>()
1330 : module::import("sys").attr("stdout");
1331 auto write = file.attr("write").cast<object>();
1332 write(line);
1333 write(kwargs["end"] ? kwargs["end"] : cast("\n"));
1334
1335 if (kwargs["flush"] && kwargs["flush"].cast<bool>()) {
1336 file.attr("flush").cast<object>()();
1337 }
1338}
1339NAMESPACE_END(detail)
1340
1341template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
1342void print(Args &&...args) {
1343 auto c = detail::collect_arguments<policy>(std::forward<Args>(args)...);
1344 detail::print(c.args(), c.kwargs());
1345}
1346
Felipe Lema2547ca42016-01-25 16:22:44 -03001347#if defined(WITH_THREAD)
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001348
1349/* The functions below essentially reproduce the PyGILState_* API using a RAII
1350 * pattern, but there are a few important differences:
1351 *
1352 * 1. When acquiring the GIL from an non-main thread during the finalization
1353 * phase, the GILState API blindly terminates the calling thread, which
1354 * is often not what is wanted. This API does not do this.
1355 *
1356 * 2. The gil_scoped_release function can optionally cut the relationship
1357 * of a PyThreadState and its associated thread, which allows moving it to
1358 * another thread (this is a fairly rare/advanced use case).
1359 *
1360 * 3. The reference count of an acquired thread state can be controlled. This
1361 * can be handy to prevent cases where callbacks issued from an external
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001362 * thread would otherwise constantly construct and destroy thread state data
1363 * structures.
Wenzel Jakob69e1a5c2016-05-26 14:29:31 +02001364 *
1365 * See the Python bindings of NanoGUI (http://github.com/wjakob/nanogui) for an
1366 * example which uses features 2 and 3 to migrate the Python thread of
1367 * execution to another thread (to run the event loop on the original thread,
1368 * in this case).
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001369 */
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001370
1371class gil_scoped_acquire {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001372public:
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001373 PYBIND11_NOINLINE gil_scoped_acquire() {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001374 auto const &internals = detail::get_internals();
1375 tstate = (PyThreadState *) PyThread_get_key_value(internals.tstate);
1376
1377 if (!tstate) {
1378 tstate = PyThreadState_New(internals.istate);
1379 #if !defined(NDEBUG)
1380 if (!tstate)
1381 pybind11_fail("scoped_acquire: could not create thread state!");
1382 #endif
1383 tstate->gilstate_counter = 0;
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001384 #if PY_MAJOR_VERSION < 3
1385 PyThread_delete_key_value(internals.tstate);
1386 #endif
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001387 PyThread_set_key_value(internals.tstate, tstate);
1388 } else {
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001389 release = detail::get_thread_state_unchecked() != tstate;
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001390 }
1391
1392 if (release) {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001393 /* Work around an annoying assertion in PyThreadState_Swap */
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001394 #if defined(Py_DEBUG)
1395 PyInterpreterState *interp = tstate->interp;
1396 tstate->interp = nullptr;
1397 #endif
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001398 PyEval_AcquireThread(tstate);
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001399 #if defined(Py_DEBUG)
1400 tstate->interp = interp;
1401 #endif
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001402 }
1403
1404 inc_ref();
1405 }
1406
1407 void inc_ref() {
1408 ++tstate->gilstate_counter;
1409 }
1410
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001411 PYBIND11_NOINLINE void dec_ref() {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001412 --tstate->gilstate_counter;
1413 #if !defined(NDEBUG)
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001414 if (detail::get_thread_state_unchecked() != tstate)
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001415 pybind11_fail("scoped_acquire::dec_ref(): thread state must be current!");
1416 if (tstate->gilstate_counter < 0)
1417 pybind11_fail("scoped_acquire::dec_ref(): reference count underflow!");
1418 #endif
1419 if (tstate->gilstate_counter == 0) {
1420 #if !defined(NDEBUG)
1421 if (!release)
1422 pybind11_fail("scoped_acquire::dec_ref(): internal error!");
1423 #endif
1424 PyThreadState_Clear(tstate);
1425 PyThreadState_DeleteCurrent();
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001426 PyThread_delete_key_value(detail::get_internals().tstate);
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001427 release = false;
1428 }
1429 }
1430
Wenzel Jakobfbafdea2016-04-25 15:02:43 +02001431 PYBIND11_NOINLINE ~gil_scoped_acquire() {
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001432 dec_ref();
1433 if (release)
1434 PyEval_SaveThread();
1435 }
1436private:
1437 PyThreadState *tstate = nullptr;
1438 bool release = true;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001439};
1440
1441class gil_scoped_release {
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001442public:
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001443 gil_scoped_release(bool disassoc = false) : disassoc(disassoc) {
1444 tstate = PyEval_SaveThread();
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001445 if (disassoc) {
Boris Schäling20ee9352016-05-28 12:26:18 +02001446 auto key = detail::get_internals().tstate;
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001447 #if PY_MAJOR_VERSION < 3
1448 PyThread_delete_key_value(key);
1449 #else
1450 PyThread_set_key_value(key, nullptr);
1451 #endif
1452 }
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001453 }
1454 ~gil_scoped_release() {
1455 if (!tstate)
1456 return;
1457 PyEval_RestoreThread(tstate);
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001458 if (disassoc) {
Boris Schäling20ee9352016-05-28 12:26:18 +02001459 auto key = detail::get_internals().tstate;
Wenzel Jakob2f6662e2016-04-25 09:16:41 +02001460 #if PY_MAJOR_VERSION < 3
1461 PyThread_delete_key_value(key);
1462 #endif
1463 PyThread_set_key_value(key, tstate);
1464 }
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001465 }
1466private:
1467 PyThreadState *tstate;
1468 bool disassoc;
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001469};
Wenzel Jakob39e97e62016-04-25 03:26:15 +02001470#else
1471class gil_scoped_acquire { };
1472class gil_scoped_release { };
Felipe Lema2547ca42016-01-25 16:22:44 -03001473#endif
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001474
Jason Rhinelander1b05ce52016-08-09 17:57:59 -04001475inline function get_type_overload(const void *this_ptr, const detail::type_info *this_type, const char *name) {
1476 handle py_object = detail::get_object_handle(this_ptr, this_type);
Wenzel Jakobac0fde92015-10-01 18:37:26 +02001477 if (!py_object)
1478 return function();
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001479 handle type = py_object.get_type();
1480 auto key = std::make_pair(type.ptr(), name);
1481
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02001482 /* Cache functions that aren't overloaded in Python to avoid
1483 many costly Python dictionary lookups below */
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001484 auto &cache = detail::get_internals().inactive_overload_cache;
1485 if (cache.find(key) != cache.end())
1486 return function();
1487
1488 function overload = (function) py_object.attr(name);
1489 if (overload.is_cpp_function()) {
1490 cache.insert(key);
1491 return function();
1492 }
Wenzel Jakob27e8e102016-01-17 22:36:37 +01001493
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02001494 /* Don't call dispatch code if invoked from overridden function */
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001495 PyFrameObject *frame = PyThreadState_Get()->frame;
Wenzel Jakobb2b44a92016-04-15 17:50:40 +02001496 if (frame && (std::string) pybind11::handle(frame->f_code->co_name).str() == name &&
Wenzel Jakobf5c154a2016-04-11 18:13:08 +02001497 frame->f_code->co_argcount > 0) {
1498 PyFrame_FastToLocals(frame);
1499 PyObject *self_caller = PyDict_GetItem(
1500 frame->f_locals, PyTuple_GET_ITEM(frame->f_code->co_varnames, 0));
1501 if (self_caller == py_object.ptr())
1502 return function();
1503 }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001504 return overload;
1505}
1506
Jason Rhinelander1b05ce52016-08-09 17:57:59 -04001507template <class T> function get_overload(const T *this_ptr, const char *name) {
1508 auto &cpp_types = detail::get_internals().registered_types_cpp;
1509 auto it = cpp_types.find(typeid(T));
1510 if (it == cpp_types.end())
1511 return function();
1512 return get_type_overload(this_ptr, (const detail::type_info *) it->second, name);
1513}
1514
Jason Rhinelander20978262016-08-29 18:16:46 -04001515#define PYBIND11_OVERLOAD_INT(ret_type, cname, name, ...) { \
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02001516 pybind11::gil_scoped_acquire gil; \
Jason Rhinelander20978262016-08-29 18:16:46 -04001517 pybind11::function overload = pybind11::get_overload(static_cast<const cname *>(this), name); \
Jason Rhinelander7dfb9322016-09-08 14:49:43 -04001518 if (overload) { \
Jason Rhinelander3e4fe6c2016-09-11 12:17:41 -04001519 auto o = overload(__VA_ARGS__); \
Jason Rhinelander7dfb9322016-09-08 14:49:43 -04001520 if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
Jason Rhinelander3e4fe6c2016-09-11 12:17:41 -04001521 static pybind11::detail::overload_caster_t<ret_type> caster; \
1522 return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
Jason Rhinelander7dfb9322016-09-08 14:49:43 -04001523 } \
1524 else return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
1525 } \
1526 }
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001527
Wenzel Jakob1e3be732016-05-24 23:42:05 +02001528#define PYBIND11_OVERLOAD_NAME(ret_type, cname, name, fn, ...) \
Jason Rhinelander20978262016-08-29 18:16:46 -04001529 PYBIND11_OVERLOAD_INT(ret_type, cname, name, __VA_ARGS__) \
Wenzel Jakob1e3be732016-05-24 23:42:05 +02001530 return cname::fn(__VA_ARGS__)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001531
Wenzel Jakob1e3be732016-05-24 23:42:05 +02001532#define PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, name, fn, ...) \
Jason Rhinelander20978262016-08-29 18:16:46 -04001533 PYBIND11_OVERLOAD_INT(ret_type, cname, name, __VA_ARGS__) \
Wenzel Jakob1e3be732016-05-24 23:42:05 +02001534 pybind11::pybind11_fail("Tried to call pure virtual function \"" #cname "::" name "\"");
1535
1536#define PYBIND11_OVERLOAD(ret_type, cname, fn, ...) \
1537 PYBIND11_OVERLOAD_NAME(ret_type, cname, #fn, fn, __VA_ARGS__)
1538
1539#define PYBIND11_OVERLOAD_PURE(ret_type, cname, fn, ...) \
1540 PYBIND11_OVERLOAD_PURE_NAME(ret_type, cname, #fn, fn, __VA_ARGS__)
Wenzel Jakoba2f6fde2015-10-01 16:46:03 +02001541
Wenzel Jakob8f4eb002015-10-15 18:13:33 +02001542NAMESPACE_END(pybind11)
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001543
1544#if defined(_MSC_VER)
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001545# pragma warning(pop)
Wenzel Jakob1ffce742016-08-25 01:43:33 +02001546#elif defined(__INTEL_COMPILER)
1547/* Leave ignored warnings on */
Wenzel Jakob6d252962016-05-01 20:47:49 +02001548#elif defined(__GNUG__) && !defined(__clang__)
Wenzel Jakob48548ea2016-01-17 22:36:44 +01001549# pragma GCC diagnostic pop
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001550#endif