blob: ecf06dbd77bffb60043b9c1d43599440370422b7 [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 Jakobd85215c2015-08-04 19:03:53 +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
192 entry->signature = cast_in::name(kw.data(), def.data());
Wenzel Jakob71867832015-07-29 17:43:52 +0200193 entry->signature += " -> ";
194 entry->signature += cast_out::name();
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200195
196 initialize(entry, sizeof...(Arg));
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200197 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200198
199 /// Delegating helper constructor to deal with lambda functions
Wenzel Jakob71867832015-07-29 17:43:52 +0200200 template <typename Func, typename... Extra> cpp_function(Func &&f, Extra&&... extra) {
201 initialize(std::forward<Func>(f),
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200202 (typename detail::remove_class<decltype(
Wenzel Jakob71867832015-07-29 17:43:52 +0200203 &std::remove_reference<Func>::type::operator())>::type *) nullptr,
204 std::forward<Extra>(extra)...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200205 }
206
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200207 /// Class methods (non-const)
Wenzel Jakob71867832015-07-29 17:43:52 +0200208 template <typename Return, typename Class, typename... Arg, typename... Extra> cpp_function(
209 Return (Class::*f)(Arg...), Extra&&... extra) {
210 initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
211 (Return (*) (Class *, Arg...)) nullptr, std::forward<Extra>(extra)...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200212 }
213
214 /// Class methods (const)
Wenzel Jakob71867832015-07-29 17:43:52 +0200215 template <typename Return, typename Class, typename... Arg, typename... Extra> cpp_function(
216 Return (Class::*f)(Arg...) const, Extra&&... extra) {
217 initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
218 (Return (*)(const Class *, Arg ...)) nullptr, std::forward<Extra>(extra)...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200219 }
220
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200221private:
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200222 /// Functors, lambda functions, etc.
Wenzel Jakob71867832015-07-29 17:43:52 +0200223 template <typename Func, typename Return, typename... Arg, typename... Extra>
224 void initialize(Func &&f, Return (*)(Arg...), Extra&&... extra) {
225 struct capture {
226 typename std::remove_reference<Func>::type f;
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200227 std::tuple<Extra...> extras;
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200228 };
229
Wenzel Jakob71867832015-07-29 17:43:52 +0200230 function_entry *entry = new function_entry();
231 entry->data = new capture { std::forward<Func>(f), std::tuple<Extra...>(std::forward<Extra>(extra)...) };
232
233 typedef arg_value_caster<Arg...> cast_in;
234 typedef return_value_caster<Return> cast_out;
235
236 entry->impl = [](function_entry *entry, PyObject *pyArgs, PyObject *kwargs, PyObject *parent) -> PyObject *{
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200237 capture *data = (capture *)entry->data;
238 process_extras(data->extras, pyArgs, kwargs, entry->is_method);
Wenzel Jakob71867832015-07-29 17:43:52 +0200239 cast_in args;
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200240 if (!args.load(pyArgs, true))
241 return nullptr;
242 return cast_out::cast(args.template call<Return>(data->f), entry->policy, parent);
Wenzel Jakob71867832015-07-29 17:43:52 +0200243 };
244
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200245 const int N = sizeof...(Extra) > sizeof...(Arg) ? sizeof...(Extra) : sizeof...(Arg);
246 std::array<const char *, N> kw{}, def{};
247 process_extras(((capture *) entry->data)->extras, entry, kw.data(), def.data());
248
249 entry->signature = cast_in::name(kw.data(), def.data());
Wenzel Jakob71867832015-07-29 17:43:52 +0200250 entry->signature += " -> ";
251 entry->signature += cast_out::name();
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200252
253 initialize(entry, sizeof...(Arg));
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200254 }
255
Wenzel Jakob71867832015-07-29 17:43:52 +0200256 static PyObject *dispatcher(PyObject *self, PyObject *args, PyObject *kwargs ) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200257 function_entry *overloads = (function_entry *) PyCapsule_GetPointer(self, nullptr);
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200258 int nargs = (int) PyTuple_Size(args);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200259 PyObject *result = nullptr;
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200260 PyObject *parent = nargs > 0 ? PyTuple_GetItem(args, 0) : nullptr;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200261 try {
262 for (function_entry *it = overloads; it != nullptr; it = it->next) {
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200263 PyObject *args_ = args;
264
265 if (it->keywords != 0 && it->keywords != nargs) {
266 args_ = PyTuple_New(it->keywords);
267 for (int i=0; i<nargs; ++i) {
268 PyObject *item = PyTuple_GET_ITEM(args, i);
269 Py_INCREF(item);
270 PyTuple_SET_ITEM(args_, i, item);
271 }
272 }
273
274 result = it->impl(it, args_, kwargs, parent);
275
276 if (args_ != args) {
277 Py_DECREF(args_);
278 }
279
280 if (result != nullptr)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200281 break;
282 }
283 } catch (const error_already_set &) { return nullptr;
284 } catch (const index_error &e) { PyErr_SetString(PyExc_IndexError, e.what()); return nullptr;
285 } catch (const stop_iteration &e) { PyErr_SetString(PyExc_StopIteration, e.what()); return nullptr;
286 } catch (const std::exception &e) { PyErr_SetString(PyExc_RuntimeError, e.what()); return nullptr;
287 } catch (...) {
288 PyErr_SetString(PyExc_RuntimeError, "Caught an unknown exception!");
289 return nullptr;
290 }
291 if (result) {
292 if (overloads->is_constructor) {
293 PyObject *inst = PyTuple_GetItem(args, 0);
294 const detail::type_info *type_info =
295 capsule(PyObject_GetAttrString((PyObject *) Py_TYPE(inst),
296 const_cast<char *>("__pybind__")), false);
297 type_info->init_holder(inst);
298 }
299 return result;
300 } else {
301 std::string signatures = "Incompatible function arguments. The "
302 "following argument types are supported:\n";
303 int ctr = 0;
304 for (function_entry *it = overloads; it != nullptr; it = it->next) {
305 signatures += " "+ std::to_string(++ctr) + ". ";
306 signatures += it->signature;
307 signatures += "\n";
308 }
309 PyErr_SetString(PyExc_TypeError, signatures.c_str());
310 return nullptr;
311 }
312 }
313
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200314 static void destruct(function_entry *entry) {
315 while (entry) {
316 delete entry->def;
317 operator delete(entry->data);
318 Py_XDECREF(entry->sibling);
319 function_entry *next = entry->next;
320 delete entry;
321 entry = next;
322 }
323 }
324
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200325 void initialize(function_entry *entry, int args) {
Wenzel Jakob71867832015-07-29 17:43:52 +0200326 if (entry->name == nullptr)
327 entry->name = "";
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200328 if (entry->keywords != 0 && entry->keywords != args)
329 throw std::runtime_error(
330 "cpp_function(): function \"" + std::string(entry->name) + "\" takes " +
331 std::to_string(args) + " arguments, but " + std::to_string(entry->keywords) +
332 " pybind::arg entries were specified!");
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200333
Wenzel Jakob71867832015-07-29 17:43:52 +0200334 entry->is_constructor = !strcmp(entry->name, "__init__");
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200335
Wenzel Jakob71867832015-07-29 17:43:52 +0200336 if (!entry->sibling || !PyCFunction_Check(entry->sibling)) {
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200337 entry->def = new PyMethodDef();
338 memset(entry->def, 0, sizeof(PyMethodDef));
339 entry->def->ml_name = entry->name;
340 entry->def->ml_meth = reinterpret_cast<PyCFunction>(*dispatcher);
341 entry->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
342 capsule entry_capsule(entry, [](PyObject *o) { destruct((function_entry *) PyCapsule_GetPointer(o, nullptr)); });
343 m_ptr = PyCFunction_New(entry->def, entry_capsule.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200344 if (!m_ptr)
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200345 throw std::runtime_error("cpp_function::cpp_function(): Could not allocate function object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200346 } else {
Wenzel Jakob71867832015-07-29 17:43:52 +0200347 m_ptr = entry->sibling;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200348 inc_ref();
349 capsule entry_capsule(PyCFunction_GetSelf(m_ptr), true);
350 function_entry *parent = (function_entry *) entry_capsule, *backup = parent;
351 while (parent->next)
352 parent = parent->next;
353 parent->next = entry;
354 entry = backup;
355 }
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200356
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200357 std::string signatures;
Wenzel Jakob71867832015-07-29 17:43:52 +0200358 int index = 0;
359 function_entry *it = entry;
360 while (it) { /* Create pydoc it */
361 if (it->sibling)
362 signatures += std::to_string(++index) + ". ";
363 signatures += "Signature : " + std::string(it->signature) + "\n";
364 if (it->doc && strlen(it->doc) > 0)
365 signatures += "\n" + std::string(it->doc) + "\n";
366 if (it->next)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200367 signatures += "\n";
Wenzel Jakob71867832015-07-29 17:43:52 +0200368 it = it->next;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200369 }
370 PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
371 if (func->m_ml->ml_doc)
372 std::free((char *) func->m_ml->ml_doc);
373 func->m_ml->ml_doc = strdup(signatures.c_str());
Wenzel Jakob71867832015-07-29 17:43:52 +0200374 if (entry->is_method) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200375 m_ptr = PyInstanceMethod_New(m_ptr);
376 if (!m_ptr)
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200377 throw std::runtime_error("cpp_function::cpp_function(): Could not allocate instance method object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200378 Py_DECREF(func);
379 }
380 }
381};
382
383class module : public object {
384public:
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200385 PYBIND_OBJECT_DEFAULT(module, object, PyModule_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200386
387 module(const char *name, const char *doc = nullptr) {
388 PyModuleDef *def = new PyModuleDef();
389 memset(def, 0, sizeof(PyModuleDef));
390 def->m_name = name;
391 def->m_doc = doc;
392 def->m_size = -1;
393 Py_INCREF(def);
394 m_ptr = PyModule_Create(def);
395 if (m_ptr == nullptr)
396 throw std::runtime_error("Internal error in module::module()");
397 inc_ref();
398 }
399
Wenzel Jakob71867832015-07-29 17:43:52 +0200400 template <typename Func, typename... Extra>
401 module &def(const char *name_, Func &&f, Extra&& ... extra) {
402 cpp_function func(std::forward<Func>(f), name(name_),
403 sibling((handle) attr(name_)), std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200404 func.inc_ref(); /* The following line steals a reference to 'func' */
Wenzel Jakob71867832015-07-29 17:43:52 +0200405 PyModule_AddObject(ptr(), name_, func.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200406 return *this;
407 }
408
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200409 module def_submodule(const char *name, const char *doc = nullptr) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200410 std::string full_name = std::string(PyModule_GetName(m_ptr))
411 + std::string(".") + std::string(name);
412 module result(PyImport_AddModule(full_name.c_str()), true);
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200413 if (doc)
414 result.attr("__doc__") = pybind::str(doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200415 attr(name) = result;
416 return result;
417 }
418};
419
420NAMESPACE_BEGIN(detail)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200421/// Basic support for creating new Python heap types
422class custom_type : public object {
423public:
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200424 PYBIND_OBJECT_DEFAULT(custom_type, object, PyType_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200425
426 custom_type(object &scope, const char *name_, const std::string &type_name,
427 size_t type_size, size_t instance_size,
428 void (*init_holder)(PyObject *), const destructor &dealloc,
429 PyObject *parent, const char *doc) {
430 PyHeapTypeObject *type = (PyHeapTypeObject*) PyType_Type.tp_alloc(&PyType_Type, 0);
431 PyObject *name = PyUnicode_FromString(name_);
432 if (type == nullptr || name == nullptr)
433 throw std::runtime_error("Internal error in custom_type::custom_type()");
434 Py_INCREF(name);
435 std::string full_name(name_);
436
437 pybind::str scope_name = (object) scope.attr("__name__"),
438 module_name = (object) scope.attr("__module__");
439
440 if (scope_name.check())
441 full_name = std::string(scope_name) + "." + full_name;
442 if (module_name.check())
443 full_name = std::string(module_name) + "." + full_name;
444
445 type->ht_name = type->ht_qualname = name;
446 type->ht_type.tp_name = strdup(full_name.c_str());
447 type->ht_type.tp_basicsize = instance_size;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200448 type->ht_type.tp_init = (initproc) init;
449 type->ht_type.tp_new = (newfunc) new_instance;
450 type->ht_type.tp_dealloc = dealloc;
451 type->ht_type.tp_flags |=
452 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
453 type->ht_type.tp_flags &= ~Py_TPFLAGS_HAVE_GC;
454 type->ht_type.tp_as_number = &type->as_number;
455 type->ht_type.tp_as_sequence = &type->as_sequence;
456 type->ht_type.tp_as_mapping = &type->as_mapping;
457 type->ht_type.tp_base = (PyTypeObject *) parent;
458 Py_XINCREF(parent);
459
460 if (PyType_Ready(&type->ht_type) < 0)
461 throw std::runtime_error("Internal error in custom_type::custom_type()");
462 m_ptr = (PyObject *) type;
463
464 /* Needed by pydoc */
465 if (((module &) scope).check())
466 attr("__module__") = scope_name;
467
468 auto &type_info = detail::get_internals().registered_types[type_name];
469 type_info.type = (PyTypeObject *) m_ptr;
470 type_info.type_size = type_size;
471 type_info.init_holder = init_holder;
472 attr("__pybind__") = capsule(&type_info);
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200473 if (doc)
474 attr("__doc__") = pybind::str(doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200475
476 scope.attr(name) = *this;
477 }
478
479protected:
480 /* Allocate a metaclass on demand (for static properties) */
481 handle metaclass() {
482 auto &ht_type = ((PyHeapTypeObject *) m_ptr)->ht_type;
483 auto &ob_type = ht_type.ob_base.ob_base.ob_type;
484 if (ob_type == &PyType_Type) {
485 std::string name_ = std::string(ht_type.tp_name) + "_meta";
486 PyHeapTypeObject *type = (PyHeapTypeObject*) PyType_Type.tp_alloc(&PyType_Type, 0);
487 PyObject *name = PyUnicode_FromString(name_.c_str());
488 if (type == nullptr || name == nullptr)
489 throw std::runtime_error("Internal error in custom_type::metaclass()");
490 Py_INCREF(name);
491 type->ht_name = type->ht_qualname = name;
492 type->ht_type.tp_name = strdup(name_.c_str());
493 type->ht_type.tp_base = &PyType_Type;
494 type->ht_type.tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
495 type->ht_type.tp_flags &= ~Py_TPFLAGS_HAVE_GC;
496 if (PyType_Ready(&type->ht_type) < 0)
497 throw std::runtime_error("Internal error in custom_type::metaclass()");
498 ob_type = (PyTypeObject *) type;
499 Py_INCREF(type);
500 }
501 return handle((PyObject *) ob_type);
502 }
503
504 static int init(void *self, PyObject *, PyObject *) {
505 std::string msg = std::string(Py_TYPE(self)->tp_name) + ": No constructor defined!";
506 PyErr_SetString(PyExc_TypeError, msg.c_str());
507 return -1;
508 }
509
510 static PyObject *new_instance(PyTypeObject *type, PyObject *, PyObject *) {
511 const detail::type_info *type_info = capsule(
512 PyObject_GetAttrString((PyObject *) type, const_cast<char*>("__pybind__")), false);
513 instance<void> *self = (instance<void> *) PyType_GenericAlloc(type, 0);
514 self->value = ::operator new(type_info->type_size);
515 self->owned = true;
516 self->parent = nullptr;
517 self->constructed = false;
518 detail::get_internals().registered_instances[self->value] = (PyObject *) self;
519 return (PyObject *) self;
520 }
521
522 static void dealloc(instance<void> *self) {
523 if (self->value) {
524 bool dont_cache = self->parent && ((instance<void> *) self->parent)->value == self->value;
525 if (!dont_cache) { // avoid an issue with internal references matching their parent's address
526 auto &registered_instances = detail::get_internals().registered_instances;
527 auto it = registered_instances.find(self->value);
528 if (it == registered_instances.end())
529 throw std::runtime_error("Deallocating unregistered instance!");
530 registered_instances.erase(it);
531 }
532 Py_XDECREF(self->parent);
533 }
534 Py_TYPE(self)->tp_free((PyObject*) self);
535 }
536
Wenzel Jakob43398a82015-07-28 16:12:20 +0200537 void install_buffer_funcs(
538 buffer_info *(*get_buffer)(PyObject *, void *),
539 void *get_buffer_data) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200540 PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
541 type->ht_type.tp_as_buffer = &type->as_buffer;
542 type->as_buffer.bf_getbuffer = getbuffer;
543 type->as_buffer.bf_releasebuffer = releasebuffer;
Wenzel Jakob43398a82015-07-28 16:12:20 +0200544 auto info = ((detail::type_info *) capsule(attr("__pybind__")));
545 info->get_buffer = get_buffer;
546 info->get_buffer_data = get_buffer_data;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200547 }
548
549 static int getbuffer(PyObject *obj, Py_buffer *view, int flags) {
Wenzel Jakob43398a82015-07-28 16:12:20 +0200550 auto const &typeinfo = ((detail::type_info *) capsule(handle(obj).attr("__pybind__")));
551
552 if (view == nullptr || obj == nullptr || !typeinfo || !typeinfo->get_buffer) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200553 PyErr_SetString(PyExc_BufferError, "Internal error");
554 return -1;
555 }
556 memset(view, 0, sizeof(Py_buffer));
Wenzel Jakob43398a82015-07-28 16:12:20 +0200557 buffer_info *info = typeinfo->get_buffer(obj, typeinfo->get_buffer_data);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200558 view->obj = obj;
559 view->ndim = 1;
560 view->internal = info;
561 view->buf = info->ptr;
562 view->itemsize = info->itemsize;
563 view->len = view->itemsize;
564 for (auto s : info->shape)
565 view->len *= s;
566 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
567 view->format = const_cast<char *>(info->format.c_str());
568 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
569 view->ndim = info->ndim;
570 view->strides = (Py_ssize_t *)&info->strides[0];
571 view->shape = (Py_ssize_t *) &info->shape[0];
572 }
573 Py_INCREF(view->obj);
574 return 0;
575 }
576
577 static void releasebuffer(PyObject *, Py_buffer *view) { delete (buffer_info *) view->internal; }
578};
Wenzel Jakob71867832015-07-29 17:43:52 +0200579
580/* Forward declarations */
581enum op_id : int;
582enum op_type : int;
583struct undefined_t;
584template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t> struct op_;
585template <typename... Args> struct init;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200586NAMESPACE_END(detail)
587
588template <typename type, typename holder_type = std::unique_ptr<type>> class class_ : public detail::custom_type {
589public:
590 typedef detail::instance<type, holder_type> instance_type;
591
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200592 PYBIND_OBJECT(class_, detail::custom_type, PyType_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200593
594 class_(object &scope, const char *name, const char *doc = nullptr)
595 : detail::custom_type(scope, name, type_id<type>(), sizeof(type),
596 sizeof(instance_type), init_holder, dealloc,
597 nullptr, doc) { }
598
599 class_(object &scope, const char *name, object &parent,
600 const char *doc = nullptr)
601 : detail::custom_type(scope, name, type_id<type>(), sizeof(type),
602 sizeof(instance_type), init_holder, dealloc,
603 parent.ptr(), doc) { }
604
Wenzel Jakob71867832015-07-29 17:43:52 +0200605 template <typename Func, typename... Extra>
606 class_ &def(const char *name_, Func&& f, Extra&&... extra) {
607 attr(name_) = cpp_function(std::forward<Func>(f), name(name_),
608 sibling(attr(name_)), is_method(),
609 std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200610 return *this;
611 }
612
Wenzel Jakob71867832015-07-29 17:43:52 +0200613 template <typename Func, typename... Extra> class_ &
614 def_static(const char *name_, Func f, Extra&&... extra) {
615 attr(name_) = cpp_function(std::forward<Func>(f), name(name_),
616 sibling(attr(name_)),
617 std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200618 return *this;
619 }
620
Wenzel Jakob71867832015-07-29 17:43:52 +0200621 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
622 class_ &def(const detail::op_<id, ot, L, R> &op, Extra&&... extra) {
623 op.template execute<type>(*this, std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200624 return *this;
625 }
626
Wenzel Jakob71867832015-07-29 17:43:52 +0200627 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
628 class_ & def_cast(const detail::op_<id, ot, L, R> &op, Extra&&... extra) {
629 op.template execute_cast<type>(*this, std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200630 return *this;
631 }
632
Wenzel Jakob71867832015-07-29 17:43:52 +0200633 template <typename... Args, typename... Extra>
634 class_ &def(const detail::init<Args...> &init, Extra&&... extra) {
635 init.template execute<type>(*this, std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200636 return *this;
637 }
638
Wenzel Jakob71867832015-07-29 17:43:52 +0200639 template <typename Func> class_& def_buffer(Func &&func) {
Wenzel Jakob43398a82015-07-28 16:12:20 +0200640 struct capture { Func func; };
641 capture *ptr = new capture { std::forward<Func>(func) };
642 install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200643 detail::type_caster<type> caster;
644 if (!caster.load(obj, false))
645 return nullptr;
Wenzel Jakob43398a82015-07-28 16:12:20 +0200646 return new buffer_info(((capture *) ptr)->func(caster));
647 }, ptr);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200648 return *this;
649 }
650
Wenzel Jakob71867832015-07-29 17:43:52 +0200651 template <typename C, typename D, typename... Extra>
652 class_ &def_readwrite(const char *name, D C::*pm, Extra&&... extra) {
653 cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; },
654 return_value_policy::reference_internal,
655 is_method(), extra...),
656 fset([pm](C &c, const D &value) { c.*pm = value; },
657 is_method(), extra...);
658 def_property(name, fget, fset);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200659 return *this;
660 }
661
Wenzel Jakob71867832015-07-29 17:43:52 +0200662 template <typename C, typename D, typename... Extra>
663 class_ &def_readonly(const char *name, const D C::*pm, Extra&& ...extra) {
664 cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; },
665 return_value_policy::reference_internal,
666 is_method(), std::forward<Extra>(extra)...);
667 def_property_readonly(name, fget);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200668 return *this;
669 }
670
Wenzel Jakob71867832015-07-29 17:43:52 +0200671 template <typename D, typename... Extra>
672 class_ &def_readwrite_static(const char *name, D *pm, Extra&& ...extra) {
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200673 cpp_function fget([pm](object) -> const D &{ return *pm; }, nullptr,
Wenzel Jakob71867832015-07-29 17:43:52 +0200674 return_value_policy::reference_internal, extra...),
675 fset([pm](object, const D &value) { *pm = value; }, extra...);
676 def_property_static(name, fget, fset);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200677 return *this;
678 }
679
Wenzel Jakob71867832015-07-29 17:43:52 +0200680 template <typename D, typename... Extra>
681 class_ &def_readonly_static(const char *name, const D *pm, Extra&& ...extra) {
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200682 cpp_function fget([pm](object) -> const D &{ return *pm; }, nullptr,
Wenzel Jakob71867832015-07-29 17:43:52 +0200683 return_value_policy::reference_internal, std::forward<Extra>(extra)...);
684 def_property_readonly_static(name, fget);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200685 return *this;
686 }
687
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200688 class_ &def_property_readonly(const char *name, const cpp_function &fget, const char *doc = nullptr) {
689 def_property(name, fget, cpp_function(), doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200690 return *this;
691 }
692
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200693 class_ &def_property_readonly_static(const char *name, const cpp_function &fget, const char *doc = nullptr) {
694 def_property_static(name, fget, cpp_function(), doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200695 return *this;
696 }
697
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200698 class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset, const char *doc = nullptr) {
699 object doc_obj = doc ? pybind::str(doc) : (object) const_cast<cpp_function&>(fget).attr("__doc__");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200700 object property(
701 PyObject_CallFunction((PyObject *)&PyProperty_Type,
Wenzel Jakob71867832015-07-29 17:43:52 +0200702 const_cast<char *>("OOOO"), fget.ptr() ? fget.ptr() : Py_None,
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200703 fset.ptr() ? fset.ptr() : Py_None, Py_None, doc_obj.ptr()), false);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200704 attr(name) = property;
705 return *this;
706 }
707
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200708 class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset, const char *doc = nullptr) {
709 object doc_obj = doc ? pybind::str(doc) : (object) const_cast<cpp_function&>(fget).attr("__doc__");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200710 object property(
711 PyObject_CallFunction((PyObject *)&PyProperty_Type,
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200712 const_cast<char *>("OOOs"), fget.ptr() ? fget.ptr() : Py_None,
713 fset.ptr() ? fset.ptr() : Py_None, Py_None, doc_obj.ptr()), false);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200714 metaclass().attr(name) = property;
715 return *this;
716 }
717private:
718 static void init_holder(PyObject *inst_) {
719 instance_type *inst = (instance_type *) inst_;
720 new (&inst->holder) holder_type(inst->value);
721 inst->constructed = true;
722 }
723 static void dealloc(PyObject *inst_) {
724 instance_type *inst = (instance_type *) inst_;
725 if (inst->owned) {
726 if (inst->constructed)
727 inst->holder.~holder_type();
728 else
729 ::operator delete(inst->value);
730 }
731 custom_type::dealloc((detail::instance<void> *) inst);
732 }
733};
734
735/// Binds C++ enumerations and enumeration classes to Python
736template <typename Type> class enum_ : public class_<Type> {
737public:
738 enum_(object &scope, const char *name, const char *doc = nullptr)
739 : class_<Type>(scope, name, doc), m_parent(scope) {
740 auto entries = new std::unordered_map<int, const char *>();
741 this->def("__str__", [name, entries](Type value) -> std::string {
742 auto it = entries->find(value);
743 return std::string(name) + "." +
744 ((it == entries->end()) ? std::string("???")
745 : std::string(it->second));
746 });
747 m_entries = entries;
748 }
749
750 /// Export enumeration entries into the parent scope
751 void export_values() {
752 PyObject *dict = ((PyTypeObject *) this->m_ptr)->tp_dict;
753 PyObject *key, *value;
754 Py_ssize_t pos = 0;
755 while (PyDict_Next(dict, &pos, &key, &value))
756 if (PyObject_IsInstance(value, this->m_ptr))
757 m_parent.attr(key) = value;
758 }
759
760 /// Add an enumeration entry
761 enum_& value(char const* name, Type value) {
762 this->attr(name) = pybind::cast(value, return_value_policy::copy);
763 (*m_entries)[(int) value] = name;
764 return *this;
765 }
766private:
767 std::unordered_map<int, const char *> *m_entries;
768 object &m_parent;
769};
770
771NAMESPACE_BEGIN(detail)
Wenzel Jakob71867832015-07-29 17:43:52 +0200772template <typename... Args> struct init {
773 template <typename Base, typename Holder, typename... Extra> void execute(pybind::class_<Base, Holder> &class_, Extra&&... extra) const {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200774 /// Function which calls a specific C++ in-place constructor
Wenzel Jakob71867832015-07-29 17:43:52 +0200775 class_.def("__init__", [](Base *instance, Args... args) { new (instance) Base(args...); }, std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200776 }
777};
778NAMESPACE_END(detail)
779
780template <typename... Args> detail::init<Args...> init() { return detail::init<Args...>(); };
781
782template <typename InputType, typename OutputType> void implicitly_convertible() {
783 auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject *{
784 if (!detail::type_caster<InputType>().load(obj, false))
785 return nullptr;
786 tuple args(1);
787 args[0] = obj;
788 PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
789 if (result == nullptr)
790 PyErr_Clear();
791 return result;
792 };
793 std::string output_type_name = type_id<OutputType>();
794 auto & registered_types = detail::get_internals().registered_types;
795 auto it = registered_types.find(output_type_name);
796 if (it == registered_types.end())
797 throw std::runtime_error("implicitly_convertible: Unable to find type " + output_type_name);
798 it->second.implicit_conversions.push_back(implicit_caster);
799}
800
801inline void init_threading() { PyEval_InitThreads(); }
802
803class gil_scoped_acquire {
804 PyGILState_STATE state;
805public:
806 inline gil_scoped_acquire() { state = PyGILState_Ensure(); }
807 inline ~gil_scoped_acquire() { PyGILState_Release(state); }
808};
809
810class gil_scoped_release {
811 PyThreadState *state;
812public:
813 inline gil_scoped_release() { state = PyEval_SaveThread(); }
814 inline ~gil_scoped_release() { PyEval_RestoreThread(state); }
815};
816
817NAMESPACE_END(pybind)
818
819#if defined(_MSC_VER)
820#pragma warning(pop)
Wenzel Jakobd85215c2015-08-04 19:03:53 +0200821#elif defined(__GNUG__) and !defined(__clang__)
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200822#pragma GCC diagnostic pop
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200823#endif
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200824