blob: 4cfaab382cef0b27d314cfab624d00765b268616 [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 Jakob71867832015-07-29 17:43:52 +020025template <typename T> struct arg_t;
26
27/// Annotation for keyword arguments
28struct arg {
29 arg(const char *name) : name(name) { }
30 template <typename T> inline arg_t<T> operator=(const T &value);
31 const char *name;
32};
33
34/// Annotation for keyword arguments with default values
35template <typename T> struct arg_t : public arg {
36 arg_t(const char *name, const T &value) : arg(name), value(value) { }
37 T value;
38};
39template <typename T> inline arg_t<T> arg::operator=(const T &value) { return arg_t<T>(name, value); }
40
41/// Annotation for methods
42struct is_method { };
43
44/// Annotation for documentation
45struct doc { const char *value; doc(const char *value) : value(value) { } };
46
47/// Annotation for function names
48struct name { const char *value; name(const char *value) : value(value) { } };
49
50/// Annotation for function siblings
51struct sibling { PyObject *value; sibling(handle value) : value(value.ptr()) { } };
52
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020053/// Wraps an arbitrary C++ function/method/lambda function/.. into a callable Python object
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020054class cpp_function : public function {
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020055private:
56 /// Chained list of function entries for overloading
Wenzel Jakob38bd7112015-07-05 20:05:44 +020057 struct function_entry {
Wenzel Jakob71867832015-07-29 17:43:52 +020058 const char *name = nullptr;
59 PyObject * (*impl) (function_entry *, PyObject *, PyObject *, PyObject *);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020060 void *data;
Wenzel Jakob71867832015-07-29 17:43:52 +020061 bool is_constructor = false, is_method = false;
62 short keywords = 0;
63 return_value_policy policy = return_value_policy::automatic;
64 std::string signature;
65 PyObject *sibling = nullptr;
66 const char *doc = nullptr;
Wenzel Jakob38bd7112015-07-05 20:05:44 +020067 function_entry *next = nullptr;
68 };
Wenzel Jakob38bd7112015-07-05 20:05:44 +020069
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020070 /// Picks a suitable return value converter from cast.h
71 template <typename T> using return_value_caster =
72 detail::type_caster<typename std::conditional<
73 std::is_void<T>::value, detail::void_type, typename detail::decay<T>::type>::type>;
74
75 /// Picks a suitable argument value converter from cast.h
Wenzel Jakob71867832015-07-29 17:43:52 +020076 template <typename... T> using arg_value_caster =
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020077 detail::type_caster<typename std::tuple<T...>>;
Wenzel Jakob71867832015-07-29 17:43:52 +020078
79
80 template <typename... T> void process_args(const std::tuple<T...> &args, function_entry *entry) {
81 process_args(args, entry, typename detail::make_index_sequence<sizeof...(T)>::type());
82 }
83
84 template <typename... T, size_t ... Index> void process_args(const
85 std::tuple<T...> &args, function_entry *entry,
86 detail::index_sequence<Index...>) {
87 int unused[] = { 0, (process_arg(std::get<Index>(args), entry), 0)... };
88 (void) unused;
89 }
90
91 void process_arg(const char *doc, function_entry *entry) { entry->doc = doc; }
92 void process_arg(const pybind::doc &d, function_entry *entry) { entry->doc = d.value; }
93 void process_arg(const pybind::name &n, function_entry *entry) { entry->name = n.value; }
94 void process_arg(const pybind::arg &, function_entry *entry) { entry->keywords++; }
95 void process_arg(const pybind::is_method &, function_entry *entry) { entry->is_method = true; }
96 void process_arg(const pybind::return_value_policy p, function_entry *entry) { entry->policy = p; }
97 void process_arg(pybind::sibling s, function_entry *entry) { entry->sibling = s.value; }
98
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020099public:
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200100 cpp_function() { }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200101
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200102 /// Vanilla function pointers
Wenzel Jakob71867832015-07-29 17:43:52 +0200103 template <typename Return, typename... Arg, typename... Extra>
104 cpp_function(Return (*f)(Arg...), Extra&&... extra) {
105 struct capture {
106 Return (*f)(Arg...);
107 std::tuple<Extra...> extra;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200108 };
109
Wenzel Jakob71867832015-07-29 17:43:52 +0200110 function_entry *entry = new function_entry();
111 entry->data = new capture { f, std::tuple<Extra...>(std::forward<Extra>(extra)...) };
112
113 typedef arg_value_caster<Arg...> cast_in;
114 typedef return_value_caster<Return> cast_out;
115
116 entry->impl = [](function_entry *entry, PyObject *pyArgs, PyObject *kwargs, PyObject *parent) -> PyObject * {
117 cast_in args;
118 if (!args.load(pyArgs, true)) return nullptr;
119 auto f = ((capture *) entry->data)->f;
120 (void)kwargs;
121 return cast_out::cast(args.template call<Return>(f), entry->policy, parent);
122 };
123
124 entry->signature = cast_in::name();
125 entry->signature += " -> ";
126 entry->signature += cast_out::name();
127 process_args(((capture *) entry->data)->extra, entry);
128 initialize(entry);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200129 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200130
131 /// Delegating helper constructor to deal with lambda functions
Wenzel Jakob71867832015-07-29 17:43:52 +0200132 template <typename Func, typename... Extra> cpp_function(Func &&f, Extra&&... extra) {
133 initialize(std::forward<Func>(f),
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200134 (typename detail::remove_class<decltype(
Wenzel Jakob71867832015-07-29 17:43:52 +0200135 &std::remove_reference<Func>::type::operator())>::type *) nullptr,
136 std::forward<Extra>(extra)...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200137 }
138
139
140 /// Class methods (non-const)
Wenzel Jakob71867832015-07-29 17:43:52 +0200141 template <typename Return, typename Class, typename... Arg, typename... Extra> cpp_function(
142 Return (Class::*f)(Arg...), Extra&&... extra) {
143 initialize([f](Class *c, Arg... args) -> Return { return (c->*f)(args...); },
144 (Return (*) (Class *, Arg...)) nullptr, std::forward<Extra>(extra)...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200145 }
146
147 /// Class methods (const)
Wenzel Jakob71867832015-07-29 17:43:52 +0200148 template <typename Return, typename Class, typename... Arg, typename... Extra> cpp_function(
149 Return (Class::*f)(Arg...) const, Extra&&... extra) {
150 initialize([f](const Class *c, Arg... args) -> Return { return (c->*f)(args...); },
151 (Return (*)(const Class *, Arg ...)) nullptr, std::forward<Extra>(extra)...);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200152 }
153
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200154private:
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200155 /// Functors, lambda functions, etc.
Wenzel Jakob71867832015-07-29 17:43:52 +0200156 template <typename Func, typename Return, typename... Arg, typename... Extra>
157 void initialize(Func &&f, Return (*)(Arg...), Extra&&... extra) {
158 struct capture {
159 typename std::remove_reference<Func>::type f;
160 std::tuple<Extra...> extra;
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200161 };
162
Wenzel Jakob71867832015-07-29 17:43:52 +0200163 function_entry *entry = new function_entry();
164 entry->data = new capture { std::forward<Func>(f), std::tuple<Extra...>(std::forward<Extra>(extra)...) };
165
166 typedef arg_value_caster<Arg...> cast_in;
167 typedef return_value_caster<Return> cast_out;
168
169 entry->impl = [](function_entry *entry, PyObject *pyArgs, PyObject *kwargs, PyObject *parent) -> PyObject *{
170 cast_in args;
171 if (!args.load(pyArgs, true)) return nullptr;
172 Func &f = ((capture *) entry->data)->f;
173 (void)kwargs;
174 return cast_out::cast(args.template call<Return>(f), entry->policy, parent);
175 };
176
177 entry->signature = cast_in::name();
178 entry->signature += " -> ";
179 entry->signature += cast_out::name();
180 process_args(((capture *) entry->data)->extra, entry);
181 initialize(entry);
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200182 }
183
Wenzel Jakob71867832015-07-29 17:43:52 +0200184 static PyObject *dispatcher(PyObject *self, PyObject *args, PyObject *kwargs ) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200185 function_entry *overloads = (function_entry *) PyCapsule_GetPointer(self, nullptr);
186 PyObject *result = nullptr;
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200187 PyObject *parent = PyTuple_Size(args) > 0 ? PyTuple_GetItem(args, 0) : nullptr;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200188 try {
189 for (function_entry *it = overloads; it != nullptr; it = it->next) {
Wenzel Jakob71867832015-07-29 17:43:52 +0200190 if ((result = it->impl(it, args, kwargs, parent)) != nullptr)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200191 break;
192 }
193 } catch (const error_already_set &) { return nullptr;
194 } catch (const index_error &e) { PyErr_SetString(PyExc_IndexError, e.what()); return nullptr;
195 } catch (const stop_iteration &e) { PyErr_SetString(PyExc_StopIteration, e.what()); return nullptr;
196 } catch (const std::exception &e) { PyErr_SetString(PyExc_RuntimeError, e.what()); return nullptr;
197 } catch (...) {
198 PyErr_SetString(PyExc_RuntimeError, "Caught an unknown exception!");
199 return nullptr;
200 }
201 if (result) {
202 if (overloads->is_constructor) {
203 PyObject *inst = PyTuple_GetItem(args, 0);
204 const detail::type_info *type_info =
205 capsule(PyObject_GetAttrString((PyObject *) Py_TYPE(inst),
206 const_cast<char *>("__pybind__")), false);
207 type_info->init_holder(inst);
208 }
209 return result;
210 } else {
211 std::string signatures = "Incompatible function arguments. The "
212 "following argument types are supported:\n";
213 int ctr = 0;
214 for (function_entry *it = overloads; it != nullptr; it = it->next) {
215 signatures += " "+ std::to_string(++ctr) + ". ";
216 signatures += it->signature;
217 signatures += "\n";
218 }
219 PyErr_SetString(PyExc_TypeError, signatures.c_str());
220 return nullptr;
221 }
222 }
223
Wenzel Jakob71867832015-07-29 17:43:52 +0200224 void initialize(function_entry *entry) {
225 if (entry->name == nullptr)
226 entry->name = "";
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200227
Wenzel Jakob71867832015-07-29 17:43:52 +0200228 entry->is_constructor = !strcmp(entry->name, "__init__");
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200229
Wenzel Jakob71867832015-07-29 17:43:52 +0200230 if (!entry->sibling || !PyCFunction_Check(entry->sibling)) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200231 PyMethodDef *def = new PyMethodDef();
232 memset(def, 0, sizeof(PyMethodDef));
Wenzel Jakob71867832015-07-29 17:43:52 +0200233 def->ml_name = entry->name;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200234 def->ml_meth = reinterpret_cast<PyCFunction>(*dispatcher);
235 def->ml_flags = METH_VARARGS | METH_KEYWORDS;
236 capsule entry_capsule(entry);
237 m_ptr = PyCFunction_New(def, entry_capsule.ptr());
238 if (!m_ptr)
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200239 throw std::runtime_error("cpp_function::cpp_function(): Could not allocate function object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200240 } else {
Wenzel Jakob71867832015-07-29 17:43:52 +0200241 m_ptr = entry->sibling;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200242 inc_ref();
243 capsule entry_capsule(PyCFunction_GetSelf(m_ptr), true);
244 function_entry *parent = (function_entry *) entry_capsule, *backup = parent;
245 while (parent->next)
246 parent = parent->next;
247 parent->next = entry;
248 entry = backup;
249 }
250 std::string signatures;
Wenzel Jakob71867832015-07-29 17:43:52 +0200251 int index = 0;
252 function_entry *it = entry;
253 while (it) { /* Create pydoc it */
254 if (it->sibling)
255 signatures += std::to_string(++index) + ". ";
256 signatures += "Signature : " + std::string(it->signature) + "\n";
257 if (it->doc && strlen(it->doc) > 0)
258 signatures += "\n" + std::string(it->doc) + "\n";
259 if (it->next)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200260 signatures += "\n";
Wenzel Jakob71867832015-07-29 17:43:52 +0200261 it = it->next;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200262 }
263 PyCFunctionObject *func = (PyCFunctionObject *) m_ptr;
264 if (func->m_ml->ml_doc)
265 std::free((char *) func->m_ml->ml_doc);
266 func->m_ml->ml_doc = strdup(signatures.c_str());
Wenzel Jakob71867832015-07-29 17:43:52 +0200267 if (entry->is_method) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200268 m_ptr = PyInstanceMethod_New(m_ptr);
269 if (!m_ptr)
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200270 throw std::runtime_error("cpp_function::cpp_function(): Could not allocate instance method object");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200271 Py_DECREF(func);
272 }
273 }
274};
275
276class module : public object {
277public:
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200278 PYBIND_OBJECT_DEFAULT(module, object, PyModule_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200279
280 module(const char *name, const char *doc = nullptr) {
281 PyModuleDef *def = new PyModuleDef();
282 memset(def, 0, sizeof(PyModuleDef));
283 def->m_name = name;
284 def->m_doc = doc;
285 def->m_size = -1;
286 Py_INCREF(def);
287 m_ptr = PyModule_Create(def);
288 if (m_ptr == nullptr)
289 throw std::runtime_error("Internal error in module::module()");
290 inc_ref();
291 }
292
Wenzel Jakob71867832015-07-29 17:43:52 +0200293 template <typename Func, typename... Extra>
294 module &def(const char *name_, Func &&f, Extra&& ... extra) {
295 cpp_function func(std::forward<Func>(f), name(name_),
296 sibling((handle) attr(name_)), std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200297 func.inc_ref(); /* The following line steals a reference to 'func' */
Wenzel Jakob71867832015-07-29 17:43:52 +0200298 PyModule_AddObject(ptr(), name_, func.ptr());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200299 return *this;
300 }
301
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200302 module def_submodule(const char *name, const char *doc = nullptr) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200303 std::string full_name = std::string(PyModule_GetName(m_ptr))
304 + std::string(".") + std::string(name);
305 module result(PyImport_AddModule(full_name.c_str()), true);
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200306 if (doc)
307 result.attr("__doc__") = pybind::str(doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200308 attr(name) = result;
309 return result;
310 }
311};
312
313NAMESPACE_BEGIN(detail)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200314/// Basic support for creating new Python heap types
315class custom_type : public object {
316public:
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200317 PYBIND_OBJECT_DEFAULT(custom_type, object, PyType_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200318
319 custom_type(object &scope, const char *name_, const std::string &type_name,
320 size_t type_size, size_t instance_size,
321 void (*init_holder)(PyObject *), const destructor &dealloc,
322 PyObject *parent, const char *doc) {
323 PyHeapTypeObject *type = (PyHeapTypeObject*) PyType_Type.tp_alloc(&PyType_Type, 0);
324 PyObject *name = PyUnicode_FromString(name_);
325 if (type == nullptr || name == nullptr)
326 throw std::runtime_error("Internal error in custom_type::custom_type()");
327 Py_INCREF(name);
328 std::string full_name(name_);
329
330 pybind::str scope_name = (object) scope.attr("__name__"),
331 module_name = (object) scope.attr("__module__");
332
333 if (scope_name.check())
334 full_name = std::string(scope_name) + "." + full_name;
335 if (module_name.check())
336 full_name = std::string(module_name) + "." + full_name;
337
338 type->ht_name = type->ht_qualname = name;
339 type->ht_type.tp_name = strdup(full_name.c_str());
340 type->ht_type.tp_basicsize = instance_size;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200341 type->ht_type.tp_init = (initproc) init;
342 type->ht_type.tp_new = (newfunc) new_instance;
343 type->ht_type.tp_dealloc = dealloc;
344 type->ht_type.tp_flags |=
345 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
346 type->ht_type.tp_flags &= ~Py_TPFLAGS_HAVE_GC;
347 type->ht_type.tp_as_number = &type->as_number;
348 type->ht_type.tp_as_sequence = &type->as_sequence;
349 type->ht_type.tp_as_mapping = &type->as_mapping;
350 type->ht_type.tp_base = (PyTypeObject *) parent;
351 Py_XINCREF(parent);
352
353 if (PyType_Ready(&type->ht_type) < 0)
354 throw std::runtime_error("Internal error in custom_type::custom_type()");
355 m_ptr = (PyObject *) type;
356
357 /* Needed by pydoc */
358 if (((module &) scope).check())
359 attr("__module__") = scope_name;
360
361 auto &type_info = detail::get_internals().registered_types[type_name];
362 type_info.type = (PyTypeObject *) m_ptr;
363 type_info.type_size = type_size;
364 type_info.init_holder = init_holder;
365 attr("__pybind__") = capsule(&type_info);
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200366 if (doc)
367 attr("__doc__") = pybind::str(doc);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200368
369 scope.attr(name) = *this;
370 }
371
372protected:
373 /* Allocate a metaclass on demand (for static properties) */
374 handle metaclass() {
375 auto &ht_type = ((PyHeapTypeObject *) m_ptr)->ht_type;
376 auto &ob_type = ht_type.ob_base.ob_base.ob_type;
377 if (ob_type == &PyType_Type) {
378 std::string name_ = std::string(ht_type.tp_name) + "_meta";
379 PyHeapTypeObject *type = (PyHeapTypeObject*) PyType_Type.tp_alloc(&PyType_Type, 0);
380 PyObject *name = PyUnicode_FromString(name_.c_str());
381 if (type == nullptr || name == nullptr)
382 throw std::runtime_error("Internal error in custom_type::metaclass()");
383 Py_INCREF(name);
384 type->ht_name = type->ht_qualname = name;
385 type->ht_type.tp_name = strdup(name_.c_str());
386 type->ht_type.tp_base = &PyType_Type;
387 type->ht_type.tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
388 type->ht_type.tp_flags &= ~Py_TPFLAGS_HAVE_GC;
389 if (PyType_Ready(&type->ht_type) < 0)
390 throw std::runtime_error("Internal error in custom_type::metaclass()");
391 ob_type = (PyTypeObject *) type;
392 Py_INCREF(type);
393 }
394 return handle((PyObject *) ob_type);
395 }
396
397 static int init(void *self, PyObject *, PyObject *) {
398 std::string msg = std::string(Py_TYPE(self)->tp_name) + ": No constructor defined!";
399 PyErr_SetString(PyExc_TypeError, msg.c_str());
400 return -1;
401 }
402
403 static PyObject *new_instance(PyTypeObject *type, PyObject *, PyObject *) {
404 const detail::type_info *type_info = capsule(
405 PyObject_GetAttrString((PyObject *) type, const_cast<char*>("__pybind__")), false);
406 instance<void> *self = (instance<void> *) PyType_GenericAlloc(type, 0);
407 self->value = ::operator new(type_info->type_size);
408 self->owned = true;
409 self->parent = nullptr;
410 self->constructed = false;
411 detail::get_internals().registered_instances[self->value] = (PyObject *) self;
412 return (PyObject *) self;
413 }
414
415 static void dealloc(instance<void> *self) {
416 if (self->value) {
417 bool dont_cache = self->parent && ((instance<void> *) self->parent)->value == self->value;
418 if (!dont_cache) { // avoid an issue with internal references matching their parent's address
419 auto &registered_instances = detail::get_internals().registered_instances;
420 auto it = registered_instances.find(self->value);
421 if (it == registered_instances.end())
422 throw std::runtime_error("Deallocating unregistered instance!");
423 registered_instances.erase(it);
424 }
425 Py_XDECREF(self->parent);
426 }
427 Py_TYPE(self)->tp_free((PyObject*) self);
428 }
429
Wenzel Jakob43398a82015-07-28 16:12:20 +0200430 void install_buffer_funcs(
431 buffer_info *(*get_buffer)(PyObject *, void *),
432 void *get_buffer_data) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200433 PyHeapTypeObject *type = (PyHeapTypeObject*) m_ptr;
434 type->ht_type.tp_as_buffer = &type->as_buffer;
435 type->as_buffer.bf_getbuffer = getbuffer;
436 type->as_buffer.bf_releasebuffer = releasebuffer;
Wenzel Jakob43398a82015-07-28 16:12:20 +0200437 auto info = ((detail::type_info *) capsule(attr("__pybind__")));
438 info->get_buffer = get_buffer;
439 info->get_buffer_data = get_buffer_data;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200440 }
441
442 static int getbuffer(PyObject *obj, Py_buffer *view, int flags) {
Wenzel Jakob43398a82015-07-28 16:12:20 +0200443 auto const &typeinfo = ((detail::type_info *) capsule(handle(obj).attr("__pybind__")));
444
445 if (view == nullptr || obj == nullptr || !typeinfo || !typeinfo->get_buffer) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200446 PyErr_SetString(PyExc_BufferError, "Internal error");
447 return -1;
448 }
449 memset(view, 0, sizeof(Py_buffer));
Wenzel Jakob43398a82015-07-28 16:12:20 +0200450 buffer_info *info = typeinfo->get_buffer(obj, typeinfo->get_buffer_data);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200451 view->obj = obj;
452 view->ndim = 1;
453 view->internal = info;
454 view->buf = info->ptr;
455 view->itemsize = info->itemsize;
456 view->len = view->itemsize;
457 for (auto s : info->shape)
458 view->len *= s;
459 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
460 view->format = const_cast<char *>(info->format.c_str());
461 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
462 view->ndim = info->ndim;
463 view->strides = (Py_ssize_t *)&info->strides[0];
464 view->shape = (Py_ssize_t *) &info->shape[0];
465 }
466 Py_INCREF(view->obj);
467 return 0;
468 }
469
470 static void releasebuffer(PyObject *, Py_buffer *view) { delete (buffer_info *) view->internal; }
471};
Wenzel Jakob71867832015-07-29 17:43:52 +0200472
473/* Forward declarations */
474enum op_id : int;
475enum op_type : int;
476struct undefined_t;
477template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t> struct op_;
478template <typename... Args> struct init;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200479NAMESPACE_END(detail)
480
481template <typename type, typename holder_type = std::unique_ptr<type>> class class_ : public detail::custom_type {
482public:
483 typedef detail::instance<type, holder_type> instance_type;
484
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200485 PYBIND_OBJECT(class_, detail::custom_type, PyType_Check)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200486
487 class_(object &scope, const char *name, const char *doc = nullptr)
488 : detail::custom_type(scope, name, type_id<type>(), sizeof(type),
489 sizeof(instance_type), init_holder, dealloc,
490 nullptr, doc) { }
491
492 class_(object &scope, const char *name, object &parent,
493 const char *doc = nullptr)
494 : detail::custom_type(scope, name, type_id<type>(), sizeof(type),
495 sizeof(instance_type), init_holder, dealloc,
496 parent.ptr(), doc) { }
497
Wenzel Jakob71867832015-07-29 17:43:52 +0200498 template <typename Func, typename... Extra>
499 class_ &def(const char *name_, Func&& f, Extra&&... extra) {
500 attr(name_) = cpp_function(std::forward<Func>(f), name(name_),
501 sibling(attr(name_)), is_method(),
502 std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200503 return *this;
504 }
505
Wenzel Jakob71867832015-07-29 17:43:52 +0200506 template <typename Func, typename... Extra> class_ &
507 def_static(const char *name_, Func f, Extra&&... extra) {
508 attr(name_) = cpp_function(std::forward<Func>(f), name(name_),
509 sibling(attr(name_)),
510 std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200511 return *this;
512 }
513
Wenzel Jakob71867832015-07-29 17:43:52 +0200514 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
515 class_ &def(const detail::op_<id, ot, L, R> &op, Extra&&... extra) {
516 op.template execute<type>(*this, std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200517 return *this;
518 }
519
Wenzel Jakob71867832015-07-29 17:43:52 +0200520 template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra>
521 class_ & def_cast(const detail::op_<id, ot, L, R> &op, Extra&&... extra) {
522 op.template execute_cast<type>(*this, std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200523 return *this;
524 }
525
Wenzel Jakob71867832015-07-29 17:43:52 +0200526 template <typename... Args, typename... Extra>
527 class_ &def(const detail::init<Args...> &init, Extra&&... extra) {
528 init.template execute<type>(*this, std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200529 return *this;
530 }
531
Wenzel Jakob71867832015-07-29 17:43:52 +0200532 template <typename Func> class_& def_buffer(Func &&func) {
Wenzel Jakob43398a82015-07-28 16:12:20 +0200533 struct capture { Func func; };
534 capture *ptr = new capture { std::forward<Func>(func) };
535 install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200536 detail::type_caster<type> caster;
537 if (!caster.load(obj, false))
538 return nullptr;
Wenzel Jakob43398a82015-07-28 16:12:20 +0200539 return new buffer_info(((capture *) ptr)->func(caster));
540 }, ptr);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200541 return *this;
542 }
543
Wenzel Jakob71867832015-07-29 17:43:52 +0200544 template <typename C, typename D, typename... Extra>
545 class_ &def_readwrite(const char *name, D C::*pm, Extra&&... extra) {
546 cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; },
547 return_value_policy::reference_internal,
548 is_method(), extra...),
549 fset([pm](C &c, const D &value) { c.*pm = value; },
550 is_method(), extra...);
551 def_property(name, fget, fset);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200552 return *this;
553 }
554
Wenzel Jakob71867832015-07-29 17:43:52 +0200555 template <typename C, typename D, typename... Extra>
556 class_ &def_readonly(const char *name, const D C::*pm, Extra&& ...extra) {
557 cpp_function fget([pm](const C &c) -> const D &{ return c.*pm; },
558 return_value_policy::reference_internal,
559 is_method(), std::forward<Extra>(extra)...);
560 def_property_readonly(name, fget);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200561 return *this;
562 }
563
Wenzel Jakob71867832015-07-29 17:43:52 +0200564 template <typename D, typename... Extra>
565 class_ &def_readwrite_static(const char *name, D *pm, Extra&& ...extra) {
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200566 cpp_function fget([pm](object) -> const D &{ return *pm; }, nullptr,
Wenzel Jakob71867832015-07-29 17:43:52 +0200567 return_value_policy::reference_internal, extra...),
568 fset([pm](object, const D &value) { *pm = value; }, extra...);
569 def_property_static(name, fget, fset);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200570 return *this;
571 }
572
Wenzel Jakob71867832015-07-29 17:43:52 +0200573 template <typename D, typename... Extra>
574 class_ &def_readonly_static(const char *name, const D *pm, Extra&& ...extra) {
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200575 cpp_function fget([pm](object) -> const D &{ return *pm; }, nullptr,
Wenzel Jakob71867832015-07-29 17:43:52 +0200576 return_value_policy::reference_internal, std::forward<Extra>(extra)...);
577 def_property_readonly_static(name, fget);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200578 return *this;
579 }
580
Wenzel Jakob71867832015-07-29 17:43:52 +0200581 class_ &def_property_readonly(const char *name, const cpp_function &fget) {
582 def_property(name, fget, cpp_function());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200583 return *this;
584 }
585
Wenzel Jakob71867832015-07-29 17:43:52 +0200586 class_ &def_property_readonly_static(const char *name, const cpp_function &fget) {
587 def_property_static(name, fget, cpp_function());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200588 return *this;
589 }
590
Wenzel Jakob71867832015-07-29 17:43:52 +0200591 class_ &def_property(const char *name, const cpp_function &fget, const cpp_function &fset) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200592 object property(
593 PyObject_CallFunction((PyObject *)&PyProperty_Type,
Wenzel Jakob71867832015-07-29 17:43:52 +0200594 const_cast<char *>("OOOO"), fget.ptr() ? fget.ptr() : Py_None,
595 fset.ptr() ? fset.ptr() : Py_None, Py_None,
596 ((object) const_cast<cpp_function&>(fget).attr("__doc__")).ptr()), false);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200597 attr(name) = property;
598 return *this;
599 }
600
Wenzel Jakob71867832015-07-29 17:43:52 +0200601 class_ &def_property_static(const char *name, const cpp_function &fget, const cpp_function &fset) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200602 object property(
603 PyObject_CallFunction((PyObject *)&PyProperty_Type,
Wenzel Jakob71867832015-07-29 17:43:52 +0200604 const_cast<char *>("OOOO"), fget.ptr() ? fget.ptr() : Py_None,
605 fset.ptr() ? fset.ptr() : Py_None, Py_None,
606 ((object) const_cast<cpp_function&>(fget).attr("__doc__")).ptr()), false);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200607 metaclass().attr(name) = property;
608 return *this;
609 }
610private:
611 static void init_holder(PyObject *inst_) {
612 instance_type *inst = (instance_type *) inst_;
613 new (&inst->holder) holder_type(inst->value);
614 inst->constructed = true;
615 }
616 static void dealloc(PyObject *inst_) {
617 instance_type *inst = (instance_type *) inst_;
618 if (inst->owned) {
619 if (inst->constructed)
620 inst->holder.~holder_type();
621 else
622 ::operator delete(inst->value);
623 }
624 custom_type::dealloc((detail::instance<void> *) inst);
625 }
626};
627
628/// Binds C++ enumerations and enumeration classes to Python
629template <typename Type> class enum_ : public class_<Type> {
630public:
631 enum_(object &scope, const char *name, const char *doc = nullptr)
632 : class_<Type>(scope, name, doc), m_parent(scope) {
633 auto entries = new std::unordered_map<int, const char *>();
634 this->def("__str__", [name, entries](Type value) -> std::string {
635 auto it = entries->find(value);
636 return std::string(name) + "." +
637 ((it == entries->end()) ? std::string("???")
638 : std::string(it->second));
639 });
640 m_entries = entries;
641 }
642
643 /// Export enumeration entries into the parent scope
644 void export_values() {
645 PyObject *dict = ((PyTypeObject *) this->m_ptr)->tp_dict;
646 PyObject *key, *value;
647 Py_ssize_t pos = 0;
648 while (PyDict_Next(dict, &pos, &key, &value))
649 if (PyObject_IsInstance(value, this->m_ptr))
650 m_parent.attr(key) = value;
651 }
652
653 /// Add an enumeration entry
654 enum_& value(char const* name, Type value) {
655 this->attr(name) = pybind::cast(value, return_value_policy::copy);
656 (*m_entries)[(int) value] = name;
657 return *this;
658 }
659private:
660 std::unordered_map<int, const char *> *m_entries;
661 object &m_parent;
662};
663
664NAMESPACE_BEGIN(detail)
Wenzel Jakob71867832015-07-29 17:43:52 +0200665template <typename... Args> struct init {
666 template <typename Base, typename Holder, typename... Extra> void execute(pybind::class_<Base, Holder> &class_, Extra&&... extra) const {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200667 /// Function which calls a specific C++ in-place constructor
Wenzel Jakob71867832015-07-29 17:43:52 +0200668 class_.def("__init__", [](Base *instance, Args... args) { new (instance) Base(args...); }, std::forward<Extra>(extra)...);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200669 }
670};
671NAMESPACE_END(detail)
672
673template <typename... Args> detail::init<Args...> init() { return detail::init<Args...>(); };
674
675template <typename InputType, typename OutputType> void implicitly_convertible() {
676 auto implicit_caster = [](PyObject *obj, PyTypeObject *type) -> PyObject *{
677 if (!detail::type_caster<InputType>().load(obj, false))
678 return nullptr;
679 tuple args(1);
680 args[0] = obj;
681 PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
682 if (result == nullptr)
683 PyErr_Clear();
684 return result;
685 };
686 std::string output_type_name = type_id<OutputType>();
687 auto & registered_types = detail::get_internals().registered_types;
688 auto it = registered_types.find(output_type_name);
689 if (it == registered_types.end())
690 throw std::runtime_error("implicitly_convertible: Unable to find type " + output_type_name);
691 it->second.implicit_conversions.push_back(implicit_caster);
692}
693
694inline void init_threading() { PyEval_InitThreads(); }
695
696class gil_scoped_acquire {
697 PyGILState_STATE state;
698public:
699 inline gil_scoped_acquire() { state = PyGILState_Ensure(); }
700 inline ~gil_scoped_acquire() { PyGILState_Release(state); }
701};
702
703class gil_scoped_release {
704 PyThreadState *state;
705public:
706 inline gil_scoped_release() { state = PyEval_SaveThread(); }
707 inline ~gil_scoped_release() { PyEval_RestoreThread(state); }
708};
709
710NAMESPACE_END(pybind)
711
712#if defined(_MSC_VER)
713#pragma warning(pop)
714#endif