blob: ad92a824062ca83d089c0157043f85a409662a33 [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
10#if !defined(__PYBIND_H)
11#define __PYBIND_H
12
13#if defined(_MSC_VER)
14#pragma warning(push)
15#pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
16#pragma warning(disable: 4800) // warning C4800: 'int': forcing value to bool 'true' or 'false' (performance warning)
17#pragma warning(disable: 4996) // warning C4996: The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name
18#pragma warning(disable: 4100) // warning C4100: Unreferenced formal parameter
19#pragma warning(disable: 4512) // warning C4512: Assignment operator was implicitly defined as deleted
20#endif
21
22#include "cast.h"
23
24NAMESPACE_BEGIN(pybind)
25
26class function : public object {
27private:
28 struct function_entry {
29 std::function<PyObject* (PyObject *)> impl;
30 std::string signature, doc;
31 bool is_constructor;
32 function_entry *next = nullptr;
33 };
34public:
35 PYTHON_OBJECT_DEFAULT(function, object, PyFunction_Check)
36
37 template <typename Func>
38 function(const char *name, Func _func, bool is_method,
39 function overload_sibling = function(), const char *doc = nullptr,
40 return_value_policy policy = return_value_policy::automatic) {
41 /* Function traits extracted from the template type 'Func' */
42 typedef mpl::function_traits<Func> f_traits;
43
44 /* Suitable input and output casters */
45 typedef typename detail::type_caster<typename f_traits::args_type> cast_in;
46 typedef typename detail::type_caster<typename mpl::normalize_type<typename f_traits::return_type>::type> cast_out;
47 typename f_traits::f_type func = f_traits::cast(_func);
48
49 auto impl = [func, policy](PyObject *pyArgs) -> PyObject *{
50 cast_in args;
51 if (!args.load(pyArgs, true))
52 return nullptr;
53 PyObject *parent = policy != return_value_policy::reference_internal
54 ? nullptr : PyTuple_GetItem(pyArgs, 0);
55 return cast_out::cast(
56 f_traits::dispatch(func, (typename f_traits::args_type) args),
57 policy, parent);
58 };
59
60 /* Linked list of function call handlers (for overloading) */
61 function_entry *entry = new function_entry();
62 entry->impl = impl;
63 entry->signature = std::string(name) + cast_in::name() + std::string(" -> ") + cast_out::name();
64 entry->is_constructor = !strcmp(name, "__init__");
65 if (doc) entry->doc = doc;
66
67 install_function(name, entry, is_method, overload_sibling);
68 }
69
70private:
71 static PyObject *dispatcher(PyObject *self, PyObject *args, PyObject * /* kwargs */) {
72 function_entry *overloads = (function_entry *) PyCapsule_GetPointer(self, nullptr);
73 PyObject *result = nullptr;
74 try {
75 for (function_entry *it = overloads; it != nullptr; it = it->next) {
76 if ((result = it->impl(args)) != nullptr)
77 break;
78 }
79 } catch (const error_already_set &) { return nullptr;
80 } catch (const index_error &e) { PyErr_SetString(PyExc_IndexError, e.what()); return nullptr;
81 } catch (const stop_iteration &e) { PyErr_SetString(PyExc_StopIteration, e.what()); return nullptr;
82 } catch (const std::exception &e) { PyErr_SetString(PyExc_RuntimeError, e.what()); return nullptr;
83 } catch (...) {
84 PyErr_SetString(PyExc_RuntimeError, "Caught an unknown exception!");
85 return nullptr;
86 }
87 if (result) {
88 if (overloads->is_constructor) {
89 PyObject *inst = PyTuple_GetItem(args, 0);
90 const detail::type_info *type_info =
91 capsule(PyObject_GetAttrString((PyObject *) Py_TYPE(inst),
92 const_cast<char *>("__pybind__")), false);
93 type_info->init_holder(inst);
94 }
95 return result;
96 } else {
97 std::string signatures = "Incompatible function arguments. The "
98 "following argument types are supported:\n";
99 int ctr = 0;
100 for (function_entry *it = overloads; it != nullptr; it = it->next) {
101 signatures += " "+ std::to_string(++ctr) + ". ";
102 signatures += it->signature;
103 signatures += "\n";
104 }
105 PyErr_SetString(PyExc_TypeError, signatures.c_str());
106 return nullptr;
107 }
108 }
109
110 void install_function(const char *name, function_entry *entry, bool is_method, function overload_sibling) {
111 if (!overload_sibling.ptr() || !PyCFunction_Check(overload_sibling.ptr())) {
112 PyMethodDef *def = new PyMethodDef();
113 memset(def, 0, sizeof(PyMethodDef));
114 def->ml_name = strdup(name);
115 def->ml_meth = reinterpret_cast<PyCFunction>(*dispatcher);
116 def->ml_flags = METH_VARARGS | METH_KEYWORDS;
117 capsule entry_capsule(entry);
118 m_ptr = PyCFunction_New(def, entry_capsule.ptr());
119 if (!m_ptr)
120 throw std::runtime_error("function::function(): Could not allocate function object");
121 } else {
122 m_ptr = overload_sibling.ptr();
123 inc_ref();
124 capsule entry_capsule(PyCFunction_GetSelf(m_ptr), true);
125 function_entry *parent = (function_entry *) entry_capsule, *backup = parent;
126 while (parent->next)
127 parent = parent->next;
128 parent->next = entry;
129 entry = backup;
130 }
131 std::string signatures;
132 while (entry) { /* Create pydoc entry */
133 signatures += "Signature : " + std::string(entry->signature) + "\n";
134 if (!entry->doc.empty())
135 signatures += "\n" + std::string(entry->doc) + "\n";
136 if (entry->next)
137 signatures += "\n";
138 entry = entry->next;
139 }
140 PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
141 if (func->m_ml->ml_doc)
142 std::free((char *) func->m_ml->ml_doc);
143 func->m_ml->ml_doc = strdup(signatures.c_str());
144 if (is_method) {
145 m_ptr = PyInstanceMethod_New(m_ptr);
146 if (!m_ptr)
147 throw std::runtime_error("function::function(): Could not allocate instance method object");
148 Py_DECREF(func);
149 }
150 }
151};
152
153class module : public object {
154public:
155 PYTHON_OBJECT_DEFAULT(module, object, PyModule_Check)
156
157 module(const char *name, const char *doc = nullptr) {
158 PyModuleDef *def = new PyModuleDef();
159 memset(def, 0, sizeof(PyModuleDef));
160 def->m_name = name;
161 def->m_doc = doc;
162 def->m_size = -1;
163 Py_INCREF(def);
164 m_ptr = PyModule_Create(def);
165 if (m_ptr == nullptr)
166 throw std::runtime_error("Internal error in module::module()");
167 inc_ref();
168 }
169
170 template <typename Func> module& def(const char *name, Func f, const char *doc = nullptr) {
171 function func(name, f, false, (function) attr(name), doc);
172 func.inc_ref(); /* The following line steals a reference to 'func' */
173 PyModule_AddObject(ptr(), name, func.ptr());
174 return *this;
175 }
176
177 module def_submodule(const char *name) {
178 std::string full_name = std::string(PyModule_GetName(m_ptr))
179 + std::string(".") + std::string(name);
180 module result(PyImport_AddModule(full_name.c_str()), true);
181 attr(name) = result;
182 return result;
183 }
184};
185
186NAMESPACE_BEGIN(detail)
187/* Forward declarations */
188enum op_id : int;
189enum op_type : int;
190struct undefined_t;
191template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t> struct op_;
192template <typename ... Args> struct init;
193
194/// Basic support for creating new Python heap types
195class custom_type : public object {
196public:
197 PYTHON_OBJECT_DEFAULT(custom_type, object, PyType_Check)
198
199 custom_type(object &scope, const char *name_, const std::string &type_name,
200 size_t type_size, size_t instance_size,
201 void (*init_holder)(PyObject *), const destructor &dealloc,
202 PyObject *parent, const char *doc) {
203 PyHeapTypeObject *type = (PyHeapTypeObject*) PyType_Type.tp_alloc(&PyType_Type, 0);
204 PyObject *name = PyUnicode_FromString(name_);
205 if (type == nullptr || name == nullptr)
206 throw std::runtime_error("Internal error in custom_type::custom_type()");
207 Py_INCREF(name);
208 std::string full_name(name_);
209
210 pybind::str scope_name = (object) scope.attr("__name__"),
211 module_name = (object) scope.attr("__module__");
212
213 if (scope_name.check())
214 full_name = std::string(scope_name) + "." + full_name;
215 if (module_name.check())
216 full_name = std::string(module_name) + "." + full_name;
217
218 type->ht_name = type->ht_qualname = name;
219 type->ht_type.tp_name = strdup(full_name.c_str());
220 type->ht_type.tp_basicsize = instance_size;
221 type->ht_type.tp_doc = doc;
222 type->ht_type.tp_init = (initproc) init;
223 type->ht_type.tp_new = (newfunc) new_instance;
224 type->ht_type.tp_dealloc = dealloc;
225 type->ht_type.tp_flags |=
226 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
227 type->ht_type.tp_flags &= ~Py_TPFLAGS_HAVE_GC;
228 type->ht_type.tp_as_number = &type->as_number;
229 type->ht_type.tp_as_sequence = &type->as_sequence;
230 type->ht_type.tp_as_mapping = &type->as_mapping;
231 type->ht_type.tp_base = (PyTypeObject *) parent;
232 Py_XINCREF(parent);
233
234 if (PyType_Ready(&type->ht_type) < 0)
235 throw std::runtime_error("Internal error in custom_type::custom_type()");
236 m_ptr = (PyObject *) type;
237
238 /* Needed by pydoc */
239 if (((module &) scope).check())
240 attr("__module__") = scope_name;
241
242 auto &type_info = detail::get_internals().registered_types[type_name];
243 type_info.type = (PyTypeObject *) m_ptr;
244 type_info.type_size = type_size;
245 type_info.init_holder = init_holder;
246 attr("__pybind__") = capsule(&type_info);
247
248 scope.attr(name) = *this;
249 }
250
251protected:
252 /* Allocate a metaclass on demand (for static properties) */
253 handle metaclass() {
254 auto &ht_type = ((PyHeapTypeObject *) m_ptr)->ht_type;
255 auto &ob_type = ht_type.ob_base.ob_base.ob_type;
256 if (ob_type == &PyType_Type) {
257 std::string name_ = std::string(ht_type.tp_name) + "_meta";
258 PyHeapTypeObject *type = (PyHeapTypeObject*) PyType_Type.tp_alloc(&PyType_Type, 0);
259 PyObject *name = PyUnicode_FromString(name_.c_str());
260 if (type == nullptr || name == nullptr)
261 throw std::runtime_error("Internal error in custom_type::metaclass()");
262 Py_INCREF(name);
263 type->ht_name = type->ht_qualname = name;
264 type->ht_type.tp_name = strdup(name_.c_str());
265 type->ht_type.tp_base = &PyType_Type;
266 type->ht_type.tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
267 type->ht_type.tp_flags &= ~Py_TPFLAGS_HAVE_GC;
268 if (PyType_Ready(&type->ht_type) < 0)
269 throw std::runtime_error("Internal error in custom_type::metaclass()");
270 ob_type = (PyTypeObject *) type;
271 Py_INCREF(type);
272 }
273 return handle((PyObject *) ob_type);
274 }
275
276 static int init(void *self, PyObject *, PyObject *) {
277 std::string msg = std::string(Py_TYPE(self)->tp_name) + ": No constructor defined!";
278 PyErr_SetString(PyExc_TypeError, msg.c_str());
279 return -1;
280 }
281
282 static PyObject *new_instance(PyTypeObject *type, PyObject *, PyObject *) {
283 const detail::type_info *type_info = capsule(
284 PyObject_GetAttrString((PyObject *) type, const_cast<char*>("__pybind__")), false);
285 instance<void> *self = (instance<void> *) PyType_GenericAlloc(type, 0);
286 self->value = ::operator new(type_info->type_size);
287 self->owned = true;
288 self->parent = nullptr;
289 self->constructed = false;
290 detail::get_internals().registered_instances[self->value] = (PyObject *) self;
291 return (PyObject *) self;
292 }
293
294 static void dealloc(instance<void> *self) {
295 if (self->value) {
296 bool dont_cache = self->parent && ((instance<void> *) self->parent)->value == self->value;
297 if (!dont_cache) { // avoid an issue with internal references matching their parent's address
298 auto &registered_instances = detail::get_internals().registered_instances;
299 auto it = registered_instances.find(self->value);
300 if (it == registered_instances.end())
301 throw std::runtime_error("Deallocating unregistered instance!");
302 registered_instances.erase(it);
303 }
304 Py_XDECREF(self->parent);
305 }
306 Py_TYPE(self)->tp_free((PyObject*) self);
307 }
308
309 void install_buffer_funcs(const std::function<buffer_info *(PyObject *)> &func) {
310 PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
311 type->ht_type.tp_as_buffer = &type->as_buffer;
312 type->as_buffer.bf_getbuffer = getbuffer;
313 type->as_buffer.bf_releasebuffer = releasebuffer;
314 ((detail::type_info *) capsule(attr("__pybind__")))->get_buffer = func;
315 }
316
317 static int getbuffer(PyObject *obj, Py_buffer *view, int flags) {
318 auto const &info_func = ((detail::type_info *) capsule(handle(obj).attr("__pybind__")))->get_buffer;
319 if (view == nullptr || obj == nullptr || !info_func) {
320 PyErr_SetString(PyExc_BufferError, "Internal error");
321 return -1;
322 }
323 memset(view, 0, sizeof(Py_buffer));
324 buffer_info *info = info_func(obj);
325 view->obj = obj;
326 view->ndim = 1;
327 view->internal = info;
328 view->buf = info->ptr;
329 view->itemsize = info->itemsize;
330 view->len = view->itemsize;
331 for (auto s : info->shape)
332 view->len *= s;
333 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
334 view->format = const_cast<char *>(info->format.c_str());
335 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
336 view->ndim = info->ndim;
337 view->strides = (Py_ssize_t *)&info->strides[0];
338 view->shape = (Py_ssize_t *) &info->shape[0];
339 }
340 Py_INCREF(view->obj);
341 return 0;
342 }
343
344 static void releasebuffer(PyObject *, Py_buffer *view) { delete (buffer_info *) view->internal; }
345};
346
347NAMESPACE_END(detail)
348
349template <typename type, typename holder_type = std::unique_ptr<type>> class class_ : public detail::custom_type {
350public:
351 typedef detail::instance<type, holder_type> instance_type;
352
353 PYTHON_OBJECT(class_, detail::custom_type, PyType_Check)
354
355 class_(object &scope, const char *name, const char *doc = nullptr)
356 : detail::custom_type(scope, name, type_id<type>(), sizeof(type),
357 sizeof(instance_type), init_holder, dealloc,
358 nullptr, doc) { }
359
360 class_(object &scope, const char *name, object &parent,
361 const char *doc = nullptr)
362 : detail::custom_type(scope, name, type_id<type>(), sizeof(type),
363 sizeof(instance_type), init_holder, dealloc,
364 parent.ptr(), doc) { }
365
366 template <typename Func>
367 class_ &def(const char *name, Func f, const char *doc = nullptr,
368 return_value_policy policy = return_value_policy::automatic) {
369 attr(name) = function(name, f, true, (function) attr(name), doc, policy);
370 return *this;
371 }
372
373 template <typename Func> class_ &
374 def_static(const char *name, Func f, const char *doc = nullptr,
375 return_value_policy policy = return_value_policy::automatic) {
376 attr(name) = function(name, f, false, (function) attr(name), doc, policy);
377 return *this;
378 }
379
380 template <detail::op_id id, detail::op_type ot, typename L, typename R>
381 class_ &def(const detail::op_<id, ot, L, R> &op, const char *doc = nullptr,
382 return_value_policy policy = return_value_policy::automatic) {
383 op.template execute<type>(*this, doc, policy);
384 return *this;
385 }
386
387 template <detail::op_id id, detail::op_type ot, typename L, typename R> class_ &
388 def_cast(const detail::op_<id, ot, L, R> &op, const char *doc = nullptr,
389 return_value_policy policy = return_value_policy::automatic) {
390 op.template execute_cast<type>(*this, doc, policy);
391 return *this;
392 }
393
394 template <typename... Args>
395 class_ &def(const detail::init<Args...> &init, const char *doc = nullptr) {
396 init.template execute<type>(*this, doc);
397 return *this;
398 }
399
400 class_& def_buffer(const std::function<buffer_info(type&)> &func) {
401 install_buffer_funcs([func](PyObject *obj) -> buffer_info* {
402 detail::type_caster<type> caster;
403 if (!caster.load(obj, false))
404 return nullptr;
405 return new buffer_info(func(caster));
406 });
407 return *this;
408 }
409
410 template <typename C, typename D>
411 class_ &def_readwrite(const char *name, D C::*pm,
412 const char *doc = nullptr) {
413 function fget("", [=](C * ptr) -> D & { return ptr->*pm; }, true,
414 function(), doc, return_value_policy::reference_internal),
415 fset("", [=](C *ptr, const D &value) { ptr->*pm = value; }, true, function(), doc);
416 def_property(name, fget, fset, doc);
417 return *this;
418 }
419
420 template <typename C, typename D>
421 class_ &def_readonly(const char *name, const D C::*pm,
422 const char *doc = nullptr) {
423 function fget("", [=](C * ptr) -> const D & { return ptr->*pm; }, true,
424 function(), doc, return_value_policy::reference_internal);
425 def_property(name, fget, doc);
426 return *this;
427 }
428
429 template <typename D>
430 class_ &def_readwrite_static(const char *name, D *pm,
431 const char *doc = nullptr) {
432 function fget("", [=](object) -> D & { return *pm; }, true),
433 fset("", [=](object, const D &value) { *pm = value; }, true);
434 def_property_static(name, fget, fset, doc);
435 return *this;
436 }
437
438 template <typename D>
439 class_ &def_readonly_static(const char *name, const D *pm,
440 const char *doc = nullptr) {
441 function fget("", [=](object) -> const D & { return *pm; }, true);
442 def_property_static(name, fget, doc);
443 return *this;
444 }
445
446 class_ &def_property(const char *name, const function &fget,
447 const char *doc = nullptr) {
448 def_property(name, fget, function(), doc);
449 return *this;
450 }
451
452 class_ &def_property_static(const char *name, const function &fget,
453 const char *doc = nullptr) {
454 def_property_static(name, fget, function(), doc);
455 return *this;
456 }
457
458 class_ &def_property(const char *name, const function &fget,
459 const function &fset, const char *doc = nullptr) {
460 object property(
461 PyObject_CallFunction((PyObject *)&PyProperty_Type,
462 const_cast<char *>("OOOs"), fget.ptr() ? fget.ptr() : Py_None,
463 fset.ptr() ? fset.ptr() : Py_None, Py_None, doc), false);
464 attr(name) = property;
465 return *this;
466 }
467
468 class_ &def_property_static(const char *name, const function &fget,
469 const function &fset,
470 const char *doc = nullptr) {
471 object property(
472 PyObject_CallFunction((PyObject *)&PyProperty_Type,
473 const_cast<char *>("OOOs"), fget.ptr() ? fget.ptr() : Py_None,
474 fset.ptr() ? fset.ptr() : Py_None, Py_None, doc), false);
475 metaclass().attr(name) = property;
476 return *this;
477 }
478private:
479 static void init_holder(PyObject *inst_) {
480 instance_type *inst = (instance_type *) inst_;
481 new (&inst->holder) holder_type(inst->value);
482 inst->constructed = true;
483 }
484 static void dealloc(PyObject *inst_) {
485 instance_type *inst = (instance_type *) inst_;
486 if (inst->owned) {
487 if (inst->constructed)
488 inst->holder.~holder_type();
489 else
490 ::operator delete(inst->value);
491 }
492 custom_type::dealloc((detail::instance<void> *) inst);
493 }
494};
495
496/// Binds C++ enumerations and enumeration classes to Python
497template <typename Type> class enum_ : public class_<Type> {
498public:
499 enum_(object &scope, const char *name, const char *doc = nullptr)
500 : class_<Type>(scope, name, doc), m_parent(scope) {
501 auto entries = new std::unordered_map<int, const char *>();
502 this->def("__str__", [name, entries](Type value) -> std::string {
503 auto it = entries->find(value);
504 return std::string(name) + "." +
505 ((it == entries->end()) ? std::string("???")
506 : std::string(it->second));
507 });
508 m_entries = entries;
509 }
510
511 /// Export enumeration entries into the parent scope
512 void export_values() {
513 PyObject *dict = ((PyTypeObject *) this->m_ptr)->tp_dict;
514 PyObject *key, *value;
515 Py_ssize_t pos = 0;
516 while (PyDict_Next(dict, &pos, &key, &value))
517 if (PyObject_IsInstance(value, this->m_ptr))
518 m_parent.attr(key) = value;
519 }
520
521 /// Add an enumeration entry
522 enum_& value(char const* name, Type value) {
523 this->attr(name) = pybind::cast(value, return_value_policy::copy);
524 (*m_entries)[(int) value] = name;
525 return *this;
526 }
527private:
528 std::unordered_map<int, const char *> *m_entries;
529 object &m_parent;
530};
531
532NAMESPACE_BEGIN(detail)
533template <typename ... Args> struct init {
534 template <typename Base, typename Holder> void execute(pybind::class_<Base, Holder> &class_, const char *doc) const {
535 /// Function which calls a specific C++ in-place constructor
536 class_.def("__init__", [](Base *instance, Args... args) { new (instance) Base(args...); }, doc);
537 }
538};
539NAMESPACE_END(detail)
540
541template <typename... Args> detail::init<Args...> init() { return detail::init<Args...>(); };
542
543template <typename InputType, typename OutputType> void implicitly_convertible() {
544 auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject *{
545 if (!detail::type_caster<InputType>().load(obj, false))
546 return nullptr;
547 tuple args(1);
548 args[0] = obj;
549 PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
550 if (result == nullptr)
551 PyErr_Clear();
552 return result;
553 };
554 std::string output_type_name = type_id<OutputType>();
555 auto & registered_types = detail::get_internals().registered_types;
556 auto it = registered_types.find(output_type_name);
557 if (it == registered_types.end())
558 throw std::runtime_error("implicitly_convertible: Unable to find type " + output_type_name);
559 it->second.implicit_conversions.push_back(implicit_caster);
560}
561
562inline void init_threading() { PyEval_InitThreads(); }
563
564class gil_scoped_acquire {
565 PyGILState_STATE state;
566public:
567 inline gil_scoped_acquire() { state = PyGILState_Ensure(); }
568 inline ~gil_scoped_acquire() { PyGILState_Release(state); }
569};
570
571class gil_scoped_release {
572 PyThreadState *state;
573public:
574 inline gil_scoped_release() { state = PyEval_SaveThread(); }
575 inline ~gil_scoped_release() { PyEval_RestoreThread(state); }
576};
577
578NAMESPACE_END(pybind)
579
580#if defined(_MSC_VER)
581#pragma warning(pop)
582#endif
583
584#undef PYTHON_OBJECT
585#undef PYTHON_OBJECT_DEFAULT
586
587#endif /* __PYBIND_H */