blob: dbf12900b84462380879ebb0b5776dd3ffdd4f76 [file] [log] [blame]
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001/*
2 pybind/pybind.h: Main header file of the C++11 python binding generator library
3
4 Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch>
5
6 All rights reserved. Use of this source code is governed by a
7 BSD-style license that can be found in the LICENSE file.
8*/
9
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020010#pragma once
Wenzel Jakob38bd7112015-07-05 20:05:44 +020011
12#if defined(_MSC_VER)
13#pragma warning(push)
14#pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
15#pragma warning(disable: 4800) // warning C4800: 'int': forcing value to bool 'true' or 'false' (performance warning)
16#pragma warning(disable: 4996) // warning C4996: The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name
17#pragma warning(disable: 4100) // warning C4100: Unreferenced formal parameter
18#pragma warning(disable: 4512) // warning C4512: Assignment operator was implicitly defined as deleted
Wenzel Jakobcd5cda72015-08-03 12:17:54 +020019#elif defined(__GNUG__) and !defined(__clang__)
Wenzel Jakob281aa0e2015-07-30 15:29:00 +020020#pragma GCC diagnostic push
21#pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
22#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
23#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
Wenzel Jakob38bd7112015-07-05 20:05:44 +020024#endif
25
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020026#include <pybind/cast.h>
Wenzel Jakob281aa0e2015-07-30 15:29:00 +020027#include <iostream>
Wenzel Jakob38bd7112015-07-05 20:05:44 +020028
29NAMESPACE_BEGIN(pybind)
30
Wenzel Jakob71867832015-07-29 17:43:52 +020031template <typename T> struct arg_t;
32
33/// Annotation for keyword arguments
34struct arg {
35 arg(const char *name) : name(name) { }
36 template <typename T> inline arg_t<T> operator=(const T &value);
37 const char *name;
38};
39
40/// Annotation for keyword arguments with default values
41template <typename T> struct arg_t : public arg {
42 arg_t(const char *name, const T &value) : arg(name), value(value) { }
43 T value;
44};
45template <typename T> inline arg_t<T> arg::operator=(const T &value) { return arg_t<T>(name, value); }
46
47/// Annotation for methods
48struct is_method { };
49
50/// Annotation for documentation
51struct doc { const char *value; doc(const char *value) : value(value) { } };
52
53/// Annotation for function names
54struct name { const char *value; name(const char *value) : value(value) { } };
55
56/// Annotation for function siblings
57struct sibling { PyObject *value; sibling(handle value) : value(value.ptr()) { } };
58
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020059/// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020060class cpp_function : public function {
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020061private:
62 /// Chained list of function entries for overloading
Wenzel Jakob38bd7112015-07-05 20:05:44 +020063 struct function_entry {
Wenzel Jakob71867832015-07-29 17:43:52 +020064 const char *name = nullptr;
65 PyObject * (*impl) (function_entry *, PyObject *, PyObject *, PyObject *);
Wenzel Jakob281aa0e2015-07-30 15:29:00 +020066 PyMethodDef *def;
67 void *data = nullptr;
Wenzel Jakob71867832015-07-29 17:43:52 +020068 bool is_constructor = false, is_method = false;
69 short keywords = 0;
70 return_value_policy policy = return_value_policy::automatic;
71 std::string signature;
72 PyObject *sibling = nullptr;
73 const char *doc = nullptr;
Wenzel Jakob38bd7112015-07-05 20:05:44 +020074 function_entry *next = nullptr;
75 };
Wenzel Jakob38bd7112015-07-05 20:05:44 +020076
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020077 /// Picks a suitable return value converter from cast.h
78 template <typename T> using return_value_caster =
79 detail::type_caster<typename std::conditional<
80 std::is_void<T>::value, detail::void_type, typename detail::decay<T>::type>::type>;
81
82 /// Picks a suitable argument value converter from cast.h
Wenzel Jakob71867832015-07-29 17:43:52 +020083 template <typename... T> using arg_value_caster =
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020084 detail::type_caster<typename std::tuple<T...>>;
Wenzel Jakob71867832015-07-29 17:43:52 +020085
Wenzel Jakoba576e6a2015-07-29 17:51:54 +020086 template <typename... T> static void process_extras(const std::tuple<T...> &args,
87 function_entry *entry, const char **kw, const char **def) {
88 process_extras(args, entry, kw, def, typename detail::make_index_sequence<sizeof...(T)>::type());
Wenzel Jakob71867832015-07-29 17:43:52 +020089 }
90
Wenzel Jakoba576e6a2015-07-29 17:51:54 +020091 template <typename... T, size_t ... Index> static void process_extras(const std::tuple<T...> &args,
92 function_entry *entry, const char **kw, const char **def, detail::index_sequence<Index...>) {
93 int unused[] = { 0, (process_extra(std::get<Index>(args), entry, kw, def), 0)... };
Wenzel Jakob71867832015-07-29 17:43:52 +020094 (void) unused;
95 }
96
Wenzel Jakoba576e6a2015-07-29 17:51:54 +020097 template <typename... T> static void process_extras(const std::tuple<T...> &args,
98 PyObject *pyArgs, PyObject *kwargs, bool is_method) {
99 process_extras(args, pyArgs, kwargs, is_method, typename detail::make_index_sequence<sizeof...(T)>::type());
100 }
Wenzel Jakob71867832015-07-29 17:43:52 +0200101
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200102 template <typename... T, size_t... Index> static void process_extras(const std::tuple<T...> &args,
103 PyObject *pyArgs, PyObject *kwargs, bool is_method, detail::index_sequence<Index...>) {
104 int index = is_method ? 1 : 0;
105 int unused[] = { 0, (process_extra(std::get<Index>(args), index, pyArgs, kwargs), 0)... };
106 (void) unused;
107 }
108
109 static void process_extra(const char *doc, function_entry *entry, const char **, const char **) { entry->doc = doc; }
110 static void process_extra(const pybind::doc &d, function_entry *entry, const char **, const char **) { entry->doc = d.value; }
111 static void process_extra(const pybind::name &n, function_entry *entry, const char **, const char **) { entry->name = n.value; }
112 static void process_extra(const pybind::arg &a, function_entry *entry, const char **kw, const char **) {
113 if (entry->is_method && entry->keywords == 0)
114 kw[entry->keywords++] = "self";
115 kw[entry->keywords++] = a.name;
116 }
117 template <typename T>
118 static void process_extra(const pybind::arg_t<T> &a, function_entry *entry, const char **kw, const char **def) {
119 if (entry->is_method && entry->keywords == 0)
120 kw[entry->keywords++] = "self";
121 kw[entry->keywords] = a.name;
122 def[entry->keywords++] = strdup(std::to_string(a.value).c_str());
123 }
124
125 static void process_extra(const pybind::is_method &, function_entry *entry, const char **, const char **) { entry->is_method = true; }
126 static void process_extra(const pybind::return_value_policy p, function_entry *entry, const char **, const char **) { entry->policy = p; }
127 static void process_extra(pybind::sibling s, function_entry *entry, const char **, const char **) { entry->sibling = s.value; }
128
129 template <typename T> static void process_extra(T, int &, PyObject *, PyObject *) { }
130 static void process_extra(const pybind::arg &a, int &index, PyObject *args, PyObject *kwargs) {
131 if (kwargs) {
132 if (PyTuple_GET_ITEM(args, index) != nullptr) {
133 index++;
134 return;
135 }
136 PyObject *value = PyDict_GetItemString(kwargs, a.name);
137 if (value) {
138 Py_INCREF(value);
139 PyTuple_SetItem(args, index, value);
140 }
141 }
142 index++;
143 }
144 template <typename T>
145 static void process_extra(const pybind::arg_t<T> &a, int &index, PyObject *args, PyObject *kwargs) {
146 if (PyTuple_GET_ITEM(args, index) != nullptr) {
147 index++;
148 return;
149 }
150 PyObject *value = nullptr;
151 if (kwargs)
152 value = PyDict_GetItemString(kwargs, a.name);
153 if (value) {
154 Py_INCREF(value);
155 } else {
156 value = detail::type_caster<typename detail::decay<T>::type>::cast(
157 a.value, return_value_policy::automatic, nullptr);
158 }
159 PyTuple_SetItem(args, index, value);
160 index++;
161 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200162public:
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200163 cpp_function() { }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200164
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200165 /// Vanilla function pointers
Wenzel Jakob71867832015-07-29 17:43:52 +0200166 template <typename Return, typename... Arg, typename... Extra>
167 cpp_function(Return (*f)(Arg...), Extra&&... extra) {
168 struct capture {
169 Return (*f)(Arg...);
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200170 std::tuple<Extra...> extras;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200171 };
172
Wenzel Jakob71867832015-07-29 17:43:52 +0200173 function_entry *entry = new function_entry();
174 entry->data = new capture { f, std::tuple<Extra...>(std::forward<Extra>(extra)...) };
175
176 typedef arg_value_caster<Arg...> cast_in;
177 typedef return_value_caster<Return> cast_out;
178
179 entry->impl = [](function_entry *entry, PyObject *pyArgs, PyObject *kwargs, PyObject *parent) -> PyObject * {
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200180 capture *data = (capture *) entry->data;
181 process_extras(data->extras, pyArgs, kwargs, entry->is_method);
Wenzel Jakob71867832015-07-29 17:43:52 +0200182 cast_in args;
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200183 if (!args.load(pyArgs, true))
184 return nullptr;
185 return cast_out::cast(args.template call<Return>(data->f), entry->policy, parent);
Wenzel Jakob71867832015-07-29 17:43:52 +0200186 };
187
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200188 const int N = sizeof...(Extra) > sizeof...(Arg) ? sizeof...(Extra) : sizeof...(Arg);
189 std::array<const char *, N> kw{}, def{};
190 process_extras(((capture *) entry->data)->extras, entry, kw.data(), def.data());
191
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200192
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200193 detail::descr d = cast_in::descr(kw.data(), def.data());
194 d += " -> ";
195 d += std::move(cast_out::descr());
196
197 initialize(entry, d, sizeof...(Arg));
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200198 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200199
200 /// Delegating helper constructor to deal with lambda functions
Wenzel Jakob71867832015-07-29 17:43:52 +0200201 template <typename Func, typename... Extra> cpp_function(Func &&f, Extra&&... extra) {
202 initialize(std::forward<Func>(f),
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200203 (typename detail::remove_class<decltype(
Wenzel Jakob71867832015-07-29 17:43:52 +0200204 &std::remove_reference<Func>::type::operator())>::type *) nullptr,
205 std::forward<Extra>(extra)...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200206 }
207
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200208 /// Class methods (non-const)
Wenzel Jakob71867832015-07-29 17:43:52 +0200209 template <typename Return, typename Class, typename... Arg, typename... Extra> cpp_function(
210 Return (Class::*f)(Arg...), Extra&&... extra) {
211 initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
212 (Return (*) (Class *, Arg...)) nullptr, std::forward<Extra>(extra)...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200213 }
214
215 /// Class methods (const)
Wenzel Jakob71867832015-07-29 17:43:52 +0200216 template <typename Return, typename Class, typename... Arg, typename... Extra> cpp_function(
217 Return (Class::*f)(Arg...) const, Extra&&... extra) {
218 initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
219 (Return (*)(const Class *, Arg ...)) nullptr, std::forward<Extra>(extra)...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200220 }
221
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200222private:
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200223 /// Functors, lambda functions, etc.
Wenzel Jakob71867832015-07-29 17:43:52 +0200224 template <typename Func, typename Return, typename... Arg, typename... Extra>
225 void initialize(Func &&f, Return (*)(Arg...), Extra&&... extra) {
226 struct capture {
227 typename std::remove_reference<Func>::type f;
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200228 std::tuple<Extra...> extras;
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200229 };
230
Wenzel Jakob71867832015-07-29 17:43:52 +0200231 function_entry *entry = new function_entry();
232 entry->data = new capture { std::forward<Func>(f), std::tuple<Extra...>(std::forward<Extra>(extra)...) };
233
234 typedef arg_value_caster<Arg...> cast_in;
235 typedef return_value_caster<Return> cast_out;
236
237 entry->impl = [](function_entry *entry, PyObject *pyArgs, PyObject *kwargs, PyObject *parent) -> PyObject *{
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200238 capture *data = (capture *)entry->data;
239 process_extras(data->extras, pyArgs, kwargs, entry->is_method);
Wenzel Jakob71867832015-07-29 17:43:52 +0200240 cast_in args;
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200241 if (!args.load(pyArgs, true))
242 return nullptr;
243 return cast_out::cast(args.template call<Return>(data->f), entry->policy, parent);
Wenzel Jakob71867832015-07-29 17:43:52 +0200244 };
245
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200246 const int N = sizeof...(Extra) > sizeof...(Arg) ? sizeof...(Extra) : sizeof...(Arg);
247 std::array<const char *, N> kw{}, def{};
248 process_extras(((capture *) entry->data)->extras, entry, kw.data(), def.data());
249
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200250 detail::descr d = cast_in::descr(kw.data(), def.data());
251 d += " -> ";
252 d += std::move(cast_out::descr());
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200253
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200254 initialize(entry, d, sizeof...(Arg));
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200255 }
256
Wenzel Jakob71867832015-07-29 17:43:52 +0200257 static PyObject *dispatcher(PyObject *self, PyObject *args, PyObject *kwargs ) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200258 function_entry *overloads = (function_entry *) PyCapsule_GetPointer(self, nullptr);
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200259 int nargs = (int) PyTuple_Size(args);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200260 PyObject *result = nullptr;
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200261 PyObject *parent = nargs > 0 ? PyTuple_GetItem(args, 0) : nullptr;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200262 try {
263 for (function_entry *it = overloads; it != nullptr; it = it->next) {
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200264 PyObject *args_ = args;
265
266 if (it->keywords != 0 && it->keywords != nargs) {
267 args_ = PyTuple_New(it->keywords);
268 for (int i=0; i<nargs; ++i) {
269 PyObject *item = PyTuple_GET_ITEM(args, i);
270 Py_INCREF(item);
271 PyTuple_SET_ITEM(args_, i, item);
272 }
273 }
274
275 result = it->impl(it, args_, kwargs, parent);
276
277 if (args_ != args) {
278 Py_DECREF(args_);
279 }
280
281 if (result != nullptr)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200282 break;
283 }
284 } catch (const error_already_set &) { return nullptr;
285 } catch (const index_error &e) { PyErr_SetString(PyExc_IndexError, e.what()); return nullptr;
286 } catch (const stop_iteration &e) { PyErr_SetString(PyExc_StopIteration, e.what()); return nullptr;
287 } catch (const std::exception &e) { PyErr_SetString(PyExc_RuntimeError, e.what()); return nullptr;
288 } catch (...) {
289 PyErr_SetString(PyExc_RuntimeError, "Caught an unknown exception!");
290 return nullptr;
291 }
292 if (result) {
293 if (overloads->is_constructor) {
294 PyObject *inst = PyTuple_GetItem(args, 0);
295 const detail::type_info *type_info =
296 capsule(PyObject_GetAttrString((PyObject *) Py_TYPE(inst),
297 const_cast<char *>("__pybind__")), false);
298 type_info->init_holder(inst);
299 }
300 return result;
301 } else {
302 std::string signatures = "Incompatible function arguments. The "
303 "following argument types are supported:\n";
304 int ctr = 0;
305 for (function_entry *it = overloads; it != nullptr; it = it->next) {
306 signatures += " "+ std::to_string(++ctr) + ". ";
307 signatures += it->signature;
308 signatures += "\n";
309 }
310 PyErr_SetString(PyExc_TypeError, signatures.c_str());
311 return nullptr;
312 }
313 }
314
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200315 static void destruct(function_entry *entry) {
316 while (entry) {
317 delete entry->def;
318 operator delete(entry->data);
319 Py_XDECREF(entry->sibling);
320 function_entry *next = entry->next;
321 delete entry;
322 entry = next;
323 }
324 }
325
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200326 void initialize(function_entry *entry, const detail::descr &descr, int args) {
Wenzel Jakob71867832015-07-29 17:43:52 +0200327 if (entry->name == nullptr)
328 entry->name = "";
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200329
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200330 if (entry->keywords != 0 && entry->keywords != args)
331 throw std::runtime_error(
332 "cpp_function(): function \"" + std::string(entry->name) + "\" takes " +
333 std::to_string(args) + " arguments, but " + std::to_string(entry->keywords) +
334 " pybind::arg entries were specified!");
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200335
Wenzel Jakob71867832015-07-29 17:43:52 +0200336 entry->is_constructor = !strcmp(entry->name, "__init__");
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200337 entry->signature = descr.str();
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200338
Wenzel Jakob71867832015-07-29 17:43:52 +0200339 if (!entry->sibling || !PyCFunction_Check(entry->sibling)) {
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200340 entry->def = new PyMethodDef();
341 memset(entry->def, 0, sizeof(PyMethodDef));
342 entry->def->ml_name = entry->name;
343 entry->def->ml_meth = reinterpret_cast<PyCFunction>(*dispatcher);
344 entry->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
345 capsule entry_capsule(entry, [](PyObject *o) { destruct((function_entry *) PyCapsule_GetPointer(o, nullptr)); });
346 m_ptr = PyCFunction_New(entry->def, entry_capsule.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200347 if (!m_ptr)
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200348 throw std::runtime_error("cpp_function::cpp_function(): Could not allocate function object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200349 } else {
Wenzel Jakob71867832015-07-29 17:43:52 +0200350 m_ptr = entry->sibling;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200351 inc_ref();
352 capsule entry_capsule(PyCFunction_GetSelf(m_ptr), true);
353 function_entry *parent = (function_entry *) entry_capsule, *backup = parent;
354 while (parent->next)
355 parent = parent->next;
356 parent->next = entry;
357 entry = backup;
358 }
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200359
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200360 std::string signatures;
Wenzel Jakob71867832015-07-29 17:43:52 +0200361 int index = 0;
362 function_entry *it = entry;
363 while (it) { /* Create pydoc it */
364 if (it->sibling)
365 signatures += std::to_string(++index) + ". ";
366 signatures += "Signature : " + std::string(it->signature) + "\n";
367 if (it->doc && strlen(it->doc) > 0)
368 signatures += "\n" + std::string(it->doc) + "\n";
369 if (it->next)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200370 signatures += "\n";
Wenzel Jakob71867832015-07-29 17:43:52 +0200371 it = it->next;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200372 }
373 PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
374 if (func->m_ml->ml_doc)
375 std::free((char *) func->m_ml->ml_doc);
376 func->m_ml->ml_doc = strdup(signatures.c_str());
Wenzel Jakob71867832015-07-29 17:43:52 +0200377 if (entry->is_method) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200378 m_ptr = PyInstanceMethod_New(m_ptr);
379 if (!m_ptr)
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200380 throw std::runtime_error("cpp_function::cpp_function(): Could not allocate instance method object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200381 Py_DECREF(func);
382 }
383 }
384};
385
386class module : public object {
387public:
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200388 PYBIND_OBJECT_DEFAULT(module, object, PyModule_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200389
390 module(const char *name, const char *doc = nullptr) {
391 PyModuleDef *def = new PyModuleDef();
392 memset(def, 0, sizeof(PyModuleDef));
393 def->m_name = name;
394 def->m_doc = doc;
395 def->m_size = -1;
396 Py_INCREF(def);
397 m_ptr = PyModule_Create(def);
398 if (m_ptr == nullptr)
399 throw std::runtime_error("Internal error in module::module()");
400 inc_ref();
401 }
402
Wenzel Jakob71867832015-07-29 17:43:52 +0200403 template <typename Func, typename... Extra>
404 module &def(const char *name_, Func &&f, Extra&& ... extra) {
405 cpp_function func(std::forward<Func>(f), name(name_),
406 sibling((handle) attr(name_)), std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200407 func.inc_ref(); /* The following line steals a reference to 'func' */
Wenzel Jakob71867832015-07-29 17:43:52 +0200408 PyModule_AddObject(ptr(), name_, func.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200409 return *this;
410 }
411
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200412 module def_submodule(const char *name, const char *doc = nullptr) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200413 std::string full_name = std::string(PyModule_GetName(m_ptr))
414 + std::string(".") + std::string(name);
415 module result(PyImport_AddModule(full_name.c_str()), true);
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200416 if (doc)
417 result.attr("__doc__") = pybind::str(doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200418 attr(name) = result;
419 return result;
420 }
421};
422
423NAMESPACE_BEGIN(detail)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200424/// Basic support for creating new Python heap types
425class custom_type : public object {
426public:
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200427 PYBIND_OBJECT_DEFAULT(custom_type, object, PyType_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200428
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200429 custom_type(object &scope, const char *name_, const std::type_info *tinfo,
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200430 size_t type_size, size_t instance_size,
431 void (*init_holder)(PyObject *), const destructor &dealloc,
432 PyObject *parent, const char *doc) {
433 PyHeapTypeObject *type = (PyHeapTypeObject*) PyType_Type.tp_alloc(&PyType_Type, 0);
434 PyObject *name = PyUnicode_FromString(name_);
435 if (type == nullptr || name == nullptr)
436 throw std::runtime_error("Internal error in custom_type::custom_type()");
437 Py_INCREF(name);
438 std::string full_name(name_);
439
440 pybind::str scope_name = (object) scope.attr("__name__"),
441 module_name = (object) scope.attr("__module__");
442
443 if (scope_name.check())
444 full_name = std::string(scope_name) + "." + full_name;
445 if (module_name.check())
446 full_name = std::string(module_name) + "." + full_name;
447
448 type->ht_name = type->ht_qualname = name;
449 type->ht_type.tp_name = strdup(full_name.c_str());
450 type->ht_type.tp_basicsize = instance_size;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200451 type->ht_type.tp_init = (initproc) init;
452 type->ht_type.tp_new = (newfunc) new_instance;
453 type->ht_type.tp_dealloc = dealloc;
454 type->ht_type.tp_flags |=
455 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
456 type->ht_type.tp_flags &= ~Py_TPFLAGS_HAVE_GC;
457 type->ht_type.tp_as_number = &type->as_number;
458 type->ht_type.tp_as_sequence = &type->as_sequence;
459 type->ht_type.tp_as_mapping = &type->as_mapping;
460 type->ht_type.tp_base = (PyTypeObject *) parent;
461 Py_XINCREF(parent);
462
463 if (PyType_Ready(&type->ht_type) < 0)
464 throw std::runtime_error("Internal error in custom_type::custom_type()");
465 m_ptr = (PyObject *) type;
466
467 /* Needed by pydoc */
468 if (((module &) scope).check())
469 attr("__module__") = scope_name;
470
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200471 auto &type_info = detail::get_internals().registered_types[tinfo];
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200472 type_info.type = (PyTypeObject *) m_ptr;
473 type_info.type_size = type_size;
474 type_info.init_holder = init_holder;
475 attr("__pybind__") = capsule(&type_info);
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200476 if (doc)
477 attr("__doc__") = pybind::str(doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200478
479 scope.attr(name) = *this;
480 }
481
482protected:
483 /* Allocate a metaclass on demand (for static properties) */
484 handle metaclass() {
485 auto &ht_type = ((PyHeapTypeObject *) m_ptr)->ht_type;
486 auto &ob_type = ht_type.ob_base.ob_base.ob_type;
487 if (ob_type == &PyType_Type) {
488 std::string name_ = std::string(ht_type.tp_name) + "_meta";
489 PyHeapTypeObject *type = (PyHeapTypeObject*) PyType_Type.tp_alloc(&PyType_Type, 0);
490 PyObject *name = PyUnicode_FromString(name_.c_str());
491 if (type == nullptr || name == nullptr)
492 throw std::runtime_error("Internal error in custom_type::metaclass()");
493 Py_INCREF(name);
494 type->ht_name = type->ht_qualname = name;
495 type->ht_type.tp_name = strdup(name_.c_str());
496 type->ht_type.tp_base = &PyType_Type;
497 type->ht_type.tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
498 type->ht_type.tp_flags &= ~Py_TPFLAGS_HAVE_GC;
499 if (PyType_Ready(&type->ht_type) < 0)
500 throw std::runtime_error("Internal error in custom_type::metaclass()");
501 ob_type = (PyTypeObject *) type;
502 Py_INCREF(type);
503 }
504 return handle((PyObject *) ob_type);
505 }
506
507 static int init(void *self, PyObject *, PyObject *) {
508 std::string msg = std::string(Py_TYPE(self)->tp_name) + ": No constructor defined!";
509 PyErr_SetString(PyExc_TypeError, msg.c_str());
510 return -1;
511 }
512
513 static PyObject *new_instance(PyTypeObject *type, PyObject *, PyObject *) {
514 const detail::type_info *type_info = capsule(
515 PyObject_GetAttrString((PyObject *) type, const_cast<char*>("__pybind__")), false);
516 instance<void> *self = (instance<void> *) PyType_GenericAlloc(type, 0);
517 self->value = ::operator new(type_info->type_size);
518 self->owned = true;
519 self->parent = nullptr;
520 self->constructed = false;
521 detail::get_internals().registered_instances[self->value] = (PyObject *) self;
522 return (PyObject *) self;
523 }
524
525 static void dealloc(instance<void> *self) {
526 if (self->value) {
527 bool dont_cache = self->parent && ((instance<void> *) self->parent)->value == self->value;
528 if (!dont_cache) { // avoid an issue with internal references matching their parent's address
529 auto &registered_instances = detail::get_internals().registered_instances;
530 auto it = registered_instances.find(self->value);
531 if (it == registered_instances.end())
532 throw std::runtime_error("Deallocating unregistered instance!");
533 registered_instances.erase(it);
534 }
535 Py_XDECREF(self->parent);
536 }
537 Py_TYPE(self)->tp_free((PyObject*) self);
538 }
539
Wenzel Jakob43398a82015-07-28 16:12:20 +0200540 void install_buffer_funcs(
541 buffer_info *(*get_buffer)(PyObject *, void *),
542 void *get_buffer_data) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200543 PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
544 type->ht_type.tp_as_buffer = &type->as_buffer;
545 type->as_buffer.bf_getbuffer = getbuffer;
546 type->as_buffer.bf_releasebuffer = releasebuffer;
Wenzel Jakob43398a82015-07-28 16:12:20 +0200547 auto info = ((detail::type_info *) capsule(attr("__pybind__")));
548 info->get_buffer = get_buffer;
549 info->get_buffer_data = get_buffer_data;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200550 }
551
552 static int getbuffer(PyObject *obj, Py_buffer *view, int flags) {
Wenzel Jakob43398a82015-07-28 16:12:20 +0200553 auto const &typeinfo = ((detail::type_info *) capsule(handle(obj).attr("__pybind__")));
554
555 if (view == nullptr || obj == nullptr || !typeinfo || !typeinfo->get_buffer) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200556 PyErr_SetString(PyExc_BufferError, "Internal error");
557 return -1;
558 }
559 memset(view, 0, sizeof(Py_buffer));
Wenzel Jakob43398a82015-07-28 16:12:20 +0200560 buffer_info *info = typeinfo->get_buffer(obj, typeinfo->get_buffer_data);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200561 view->obj = obj;
562 view->ndim = 1;
563 view->internal = info;
564 view->buf = info->ptr;
565 view->itemsize = info->itemsize;
566 view->len = view->itemsize;
567 for (auto s : info->shape)
568 view->len *= s;
569 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
570 view->format = const_cast<char *>(info->format.c_str());
571 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
572 view->ndim = info->ndim;
573 view->strides = (Py_ssize_t *)&info->strides[0];
574 view->shape = (Py_ssize_t *) &info->shape[0];
575 }
576 Py_INCREF(view->obj);
577 return 0;
578 }
579
580 static void releasebuffer(PyObject *, Py_buffer *view) { delete (buffer_info *) view->internal; }
581};
Wenzel Jakob71867832015-07-29 17:43:52 +0200582
583/* Forward declarations */
584enum op_id : int;
585enum op_type : int;
586struct undefined_t;
587template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t> struct op_;
588template <typename... Args> struct init;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200589NAMESPACE_END(detail)
590
591template <typename type, typename holder_type = std::unique_ptr<type>> class class_ : public detail::custom_type {
592public:
593 typedef detail::instance<type, holder_type> instance_type;
594
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200595 PYBIND_OBJECT(class_, detail::custom_type, PyType_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200596
597 class_(object &scope, const char *name, const char *doc = nullptr)
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200598 : detail::custom_type(scope, name, &typeid(type), sizeof(type),
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200599 sizeof(instance_type), init_holder, dealloc,
600 nullptr, doc) { }
601
602 class_(object &scope, const char *name, object &parent,
603 const char *doc = nullptr)
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200604 : detail::custom_type(scope, name, &typeid(type), sizeof(type),
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200605 sizeof(instance_type), init_holder, dealloc,
606 parent.ptr(), doc) { }
607
Wenzel Jakob71867832015-07-29 17:43:52 +0200608 template <typename Func, typename... Extra>
609 class_ &def(const char *name_, Func&& f, Extra&&... extra) {
610 attr(name_) = cpp_function(std::forward<Func>(f), name(name_),
611 sibling(attr(name_)), is_method(),
612 std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200613 return *this;
614 }
615
Wenzel Jakob71867832015-07-29 17:43:52 +0200616 template <typename Func, typename... Extra> class_ &
617 def_static(const char *name_, Func f, Extra&&... extra) {
618 attr(name_) = cpp_function(std::forward<Func>(f), name(name_),
619 sibling(attr(name_)),
620 std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200621 return *this;
622 }
623
Wenzel Jakob71867832015-07-29 17:43:52 +0200624 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
625 class_ &def(const detail::op_<id, ot, L, R> &op, Extra&&... extra) {
626 op.template execute<type>(*this, std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200627 return *this;
628 }
629
Wenzel Jakob71867832015-07-29 17:43:52 +0200630 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
631 class_ & def_cast(const detail::op_<id, ot, L, R> &op, Extra&&... extra) {
632 op.template execute_cast<type>(*this, std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200633 return *this;
634 }
635
Wenzel Jakob71867832015-07-29 17:43:52 +0200636 template <typename... Args, typename... Extra>
637 class_ &def(const detail::init<Args...> &init, Extra&&... extra) {
638 init.template execute<type>(*this, std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200639 return *this;
640 }
641
Wenzel Jakob71867832015-07-29 17:43:52 +0200642 template <typename Func> class_& def_buffer(Func &&func) {
Wenzel Jakob43398a82015-07-28 16:12:20 +0200643 struct capture { Func func; };
644 capture *ptr = new capture { std::forward<Func>(func) };
645 install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200646 detail::type_caster<type> caster;
647 if (!caster.load(obj, false))
648 return nullptr;
Wenzel Jakob43398a82015-07-28 16:12:20 +0200649 return new buffer_info(((capture *) ptr)->func(caster));
650 }, ptr);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200651 return *this;
652 }
653
Wenzel Jakob71867832015-07-29 17:43:52 +0200654 template <typename C, typename D, typename... Extra>
655 class_ &def_readwrite(const char *name, D C::*pm, Extra&&... extra) {
656 cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; },
657 return_value_policy::reference_internal,
658 is_method(), extra...),
659 fset([pm](C &c, const D &value) { c.*pm = value; },
660 is_method(), extra...);
661 def_property(name, fget, fset);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200662 return *this;
663 }
664
Wenzel Jakob71867832015-07-29 17:43:52 +0200665 template <typename C, typename D, typename... Extra>
666 class_ &def_readonly(const char *name, const D C::*pm, Extra&& ...extra) {
667 cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; },
668 return_value_policy::reference_internal,
669 is_method(), std::forward<Extra>(extra)...);
670 def_property_readonly(name, fget);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200671 return *this;
672 }
673
Wenzel Jakob71867832015-07-29 17:43:52 +0200674 template <typename D, typename... Extra>
675 class_ &def_readwrite_static(const char *name, D *pm, Extra&& ...extra) {
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200676 cpp_function fget([pm](object) -> const D &{ return *pm; }, nullptr,
Wenzel Jakob71867832015-07-29 17:43:52 +0200677 return_value_policy::reference_internal, extra...),
678 fset([pm](object, const D &value) { *pm = value; }, extra...);
679 def_property_static(name, fget, fset);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200680 return *this;
681 }
682
Wenzel Jakob71867832015-07-29 17:43:52 +0200683 template <typename D, typename... Extra>
684 class_ &def_readonly_static(const char *name, const D *pm, Extra&& ...extra) {
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200685 cpp_function fget([pm](object) -> const D &{ return *pm; }, nullptr,
Wenzel Jakob71867832015-07-29 17:43:52 +0200686 return_value_policy::reference_internal, std::forward<Extra>(extra)...);
687 def_property_readonly_static(name, fget);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200688 return *this;
689 }
690
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200691 class_ &def_property_readonly(const char *name, const cpp_function &fget, const char *doc = nullptr) {
692 def_property(name, fget, cpp_function(), doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200693 return *this;
694 }
695
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200696 class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const char *doc = nullptr) {
697 def_property_static(name, fget, cpp_function(), doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200698 return *this;
699 }
700
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200701 class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const char *doc = nullptr) {
702 object doc_obj = doc ? pybind::str(doc) : (object) const_cast<cpp_function&>(fget).attr("__doc__");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200703 object property(
704 PyObject_CallFunction((PyObject *)&PyProperty_Type,
Wenzel Jakob71867832015-07-29 17:43:52 +0200705 const_cast<char *>("OOOO"), fget.ptr() ? fget.ptr() : Py_None,
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200706 fset.ptr() ? fset.ptr() : Py_None, Py_None, doc_obj.ptr()), false);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200707 attr(name) = property;
708 return *this;
709 }
710
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200711 class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const char *doc = nullptr) {
712 object doc_obj = doc ? pybind::str(doc) : (object) const_cast<cpp_function&>(fget).attr("__doc__");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200713 object property(
714 PyObject_CallFunction((PyObject *)&PyProperty_Type,
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200715 const_cast<char *>("OOOs"), fget.ptr() ? fget.ptr() : Py_None,
716 fset.ptr() ? fset.ptr() : Py_None, Py_None, doc_obj.ptr()), false);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200717 metaclass().attr(name) = property;
718 return *this;
719 }
720private:
721 static void init_holder(PyObject *inst_) {
722 instance_type *inst = (instance_type *) inst_;
723 new (&inst->holder) holder_type(inst->value);
724 inst->constructed = true;
725 }
726 static void dealloc(PyObject *inst_) {
727 instance_type *inst = (instance_type *) inst_;
728 if (inst->owned) {
729 if (inst->constructed)
730 inst->holder.~holder_type();
731 else
732 ::operator delete(inst->value);
733 }
734 custom_type::dealloc((detail::instance<void> *) inst);
735 }
736};
737
738/// Binds C++ enumerations and enumeration classes to Python
739template <typename Type> class enum_ : public class_<Type> {
740public:
741 enum_(object &scope, const char *name, const char *doc = nullptr)
742 : class_<Type>(scope, name, doc), m_parent(scope) {
743 auto entries = new std::unordered_map<int, const char *>();
744 this->def("__str__", [name, entries](Type value) -> std::string {
745 auto it = entries->find(value);
746 return std::string(name) + "." +
747 ((it == entries->end()) ? std::string("???")
748 : std::string(it->second));
749 });
750 m_entries = entries;
751 }
752
753 /// Export enumeration entries into the parent scope
754 void export_values() {
755 PyObject *dict = ((PyTypeObject *) this->m_ptr)->tp_dict;
756 PyObject *key, *value;
757 Py_ssize_t pos = 0;
758 while (PyDict_Next(dict, &pos, &key, &value))
759 if (PyObject_IsInstance(value, this->m_ptr))
760 m_parent.attr(key) = value;
761 }
762
763 /// Add an enumeration entry
764 enum_& value(char const* name, Type value) {
765 this->attr(name) = pybind::cast(value, return_value_policy::copy);
766 (*m_entries)[(int) value] = name;
767 return *this;
768 }
769private:
770 std::unordered_map<int, const char *> *m_entries;
771 object &m_parent;
772};
773
774NAMESPACE_BEGIN(detail)
Wenzel Jakob71867832015-07-29 17:43:52 +0200775template <typename... Args> struct init {
776 template <typename Base, typename Holder, typename... Extra> void execute(pybind::class_<Base, Holder> &class_, Extra&&... extra) const {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200777 /// Function which calls a specific C++ in-place constructor
Wenzel Jakob71867832015-07-29 17:43:52 +0200778 class_.def("__init__", [](Base *instance, Args... args) { new (instance) Base(args...); }, std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200779 }
780};
781NAMESPACE_END(detail)
782
783template <typename... Args> detail::init<Args...> init() { return detail::init<Args...>(); };
784
785template <typename InputType, typename OutputType> void implicitly_convertible() {
786 auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject *{
787 if (!detail::type_caster<InputType>().load(obj, false))
788 return nullptr;
789 tuple args(1);
790 args[0] = obj;
791 PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
792 if (result == nullptr)
793 PyErr_Clear();
794 return result;
795 };
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200796 auto & registered_types = detail::get_internals().registered_types;
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200797 auto it = registered_types.find(&typeid(OutputType));
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200798 if (it == registered_types.end())
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200799 throw std::runtime_error("implicitly_convertible: Unable to find type " + type_id<OutputType>());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200800 it->second.implicit_conversions.push_back(implicit_caster);
801}
802
803inline void init_threading() { PyEval_InitThreads(); }
804
805class gil_scoped_acquire {
806 PyGILState_STATE state;
807public:
808 inline gil_scoped_acquire() { state = PyGILState_Ensure(); }
809 inline ~gil_scoped_acquire() { PyGILState_Release(state); }
810};
811
812class gil_scoped_release {
813 PyThreadState *state;
814public:
815 inline gil_scoped_release() { state = PyEval_SaveThread(); }
816 inline ~gil_scoped_release() { PyEval_RestoreThread(state); }
817};
818
819NAMESPACE_END(pybind)
820
821#if defined(_MSC_VER)
822#pragma warning(pop)
Wenzel Jakobcd5cda72015-08-03 12:17:54 +0200823#elif defined(__GNUG__) and !defined(__clang__)
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200824#pragma GCC diagnostic pop
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200825#endif
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200826