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