blob: 38b9d7f4650b35ddbe2362d1a6fd15bd18f1449e [file] [log] [blame]
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001/*
2 pybind/cast.h: Partial template specializations to cast between
3 C++ and Python types
4
5 Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch>
6
7 All rights reserved. Use of this source code is governed by a
8 BSD-style license that can be found in the LICENSE file.
9*/
10
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020011#pragma once
Wenzel Jakob38bd7112015-07-05 20:05:44 +020012
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020013#include <pybind/pytypes.h>
Wenzel Jakobbd4a5292015-07-11 17:41:48 +020014#include <pybind/typeid.h>
Wenzel Jakob38bd7112015-07-05 20:05:44 +020015#include <array>
16
17NAMESPACE_BEGIN(pybind)
18NAMESPACE_BEGIN(detail)
19
Wenzel Jakobf5fae922015-08-24 15:31:24 +020020#if defined(_MSC_VER)
21#define NOINLINE __declspec(noinline)
22#else
23#define NOINLINE __attribute__ ((noinline))
24#endif
25
26/** Linked list descriptor type for function signatures (produces smaller binaries
27 * compared to a previous solution using std::string and operator +=) */
28class descr {
29public:
30 struct entry {
31 const std::type_info *type = nullptr;
32 const char *str = nullptr;
33 entry *next = nullptr;
34 entry(const std::type_info *type) : type(type) { }
35 entry(const char *str) : str(str) { }
36 };
37
38 descr() { }
39 descr(descr &&d) : first(d.first), last(d.last) { d.first = d.last = nullptr; }
40 NOINLINE descr(const char *str) { first = last = new entry { str }; }
41 NOINLINE descr(const std::type_info &type) { first = last = new entry { &type }; }
42
43 NOINLINE void operator+(const char *str) {
44 entry *next = new entry { str };
45 last->next = next;
46 last = next;
47 }
48
49 NOINLINE void operator+(const std::type_info *type) {
50 entry *next = new entry { type };
51 last->next = next;
52 last = next;
53 }
54
55 NOINLINE void operator+=(descr &&other) {
56 last->next = other.first;
57 while (last->next)
58 last = last->next;
59 other.first = other.last = nullptr;
60 }
61
62 NOINLINE friend descr operator+(descr &&l, descr &&r) {
63 descr result(std::move(l));
64 result += std::move(r);
65 return result;
66 }
67
68 NOINLINE std::string str() const {
69 std::string result;
70 auto const& registered_types = get_internals().registered_types;
71 for (entry *it = first; it != nullptr; it = it->next) {
72 if (it->type) {
73 auto it2 = registered_types.find(it->type);
74 if (it2 != registered_types.end()) {
75 result += it2->second.type->tp_name;
76 } else {
77 std::string tname(it->type->name());
78 detail::clean_type_id(tname);
79 result += tname;
80 }
81 } else {
82 result += it->str;
83 }
84 }
85 return result;
86 }
87
88 NOINLINE ~descr() {
89 while (first) {
90 entry *tmp = first->next;
91 delete first;
92 first = tmp;
93 }
94 }
95
96 entry *first = nullptr;
97 entry *last = nullptr;
98};
99
100#undef NOINLINE
101
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200102/// Generic type caster for objects stored on the heap
103template <typename type> class type_caster {
104public:
105 typedef instance<type> instance_type;
106
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200107 static descr descr() { return typeid(type); }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200108
109 type_caster() {
110 auto const& registered_types = get_internals().registered_types;
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200111 auto it = registered_types.find(&typeid(type));
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200112 if (it != registered_types.end())
113 typeinfo = &it->second;
114 }
115
116 bool load(PyObject *src, bool convert) {
117 if (src == nullptr || typeinfo == nullptr)
118 return false;
119 if (PyType_IsSubtype(Py_TYPE(src), typeinfo->type)) {
120 value = ((instance_type *) src)->value;
121 return true;
122 }
123 if (convert) {
124 for (auto &converter : typeinfo->implicit_conversions) {
125 temp = object(converter(src, typeinfo->type), false);
126 if (load(temp.ptr(), false))
127 return true;
128 }
129 }
130 return false;
131 }
132
133 static PyObject *cast(const type &src, return_value_policy policy, PyObject *parent) {
134 if (policy == return_value_policy::automatic)
135 policy = return_value_policy::copy;
136 return cast(&src, policy, parent);
137 }
138
139 static PyObject *cast(const type *_src, return_value_policy policy, PyObject *parent) {
140 type *src = const_cast<type *>(_src);
141 if (src == nullptr) {
142 Py_INCREF(Py_None);
143 return Py_None;
144 }
145 // avoid an issue with internal references matching their parent's address
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200146 bool dont_cache = policy == return_value_policy::reference_internal &&
147 parent && ((instance<void> *) parent)->value == (void *) src;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200148 auto& internals = get_internals();
149 auto it_instance = internals.registered_instances.find(src);
150 if (it_instance != internals.registered_instances.end() && !dont_cache) {
151 PyObject *inst = it_instance->second;
152 Py_INCREF(inst);
153 return inst;
154 }
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200155 auto it = internals.registered_types.find(&typeid(type));
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200156 if (it == internals.registered_types.end()) {
157 std::string msg = std::string("Unregistered type : ") + type_id<type>();
158 PyErr_SetString(PyExc_TypeError, msg.c_str());
159 return nullptr;
160 }
161 auto &type_info = it->second;
162 instance_type *inst = (instance_type *) PyType_GenericAlloc(type_info.type, 0);
163 inst->value = src;
164 inst->owned = true;
165 inst->parent = nullptr;
166 if (policy == return_value_policy::automatic)
167 policy = return_value_policy::take_ownership;
168 handle_return_value_policy<type>(inst, policy, parent);
169 PyObject *inst_pyobj = (PyObject *) inst;
170 type_info.init_holder(inst_pyobj);
171 if (!dont_cache)
172 internals.registered_instances[inst->value] = inst_pyobj;
173 return inst_pyobj;
174 }
175
176 template <class T, typename std::enable_if<std::is_copy_constructible<T>::value, int>::type = 0>
177 static void handle_return_value_policy(instance<T> *inst, return_value_policy policy, PyObject *parent) {
178 if (policy == return_value_policy::copy) {
179 inst->value = new T(*(inst->value));
180 } else if (policy == return_value_policy::reference) {
181 inst->owned = false;
182 } else if (policy == return_value_policy::reference_internal) {
183 inst->owned = false;
184 inst->parent = parent;
185 Py_XINCREF(parent);
186 }
187 }
188
189 template <class T, typename std::enable_if<!std::is_copy_constructible<T>::value, int>::type = 0>
190 static void handle_return_value_policy(instance<T> *inst, return_value_policy policy, PyObject *parent) {
191 if (policy == return_value_policy::copy) {
192 throw cast_error("return_value_policy = copy, but the object is non-copyable!");
193 } else if (policy == return_value_policy::reference) {
194 inst->owned = false;
195 } else if (policy == return_value_policy::reference_internal) {
196 inst->owned = false;
197 inst->parent = parent;
198 Py_XINCREF(parent);
199 }
200 }
201
202 operator type*() { return value; }
203 operator type&() { return *value; }
204protected:
205 type *value = nullptr;
206 const type_info *typeinfo = nullptr;
207 object temp;
208};
209
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200210#define PYBIND_TYPE_CASTER(type, py_name) \
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200211 protected: \
212 type value; \
213 public: \
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200214 static descr descr() { return py_name; } \
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200215 static PyObject *cast(const type *src, return_value_policy policy, PyObject *parent) { \
216 return cast(*src, policy, parent); \
217 } \
218 operator type*() { return &value; } \
219 operator type&() { return value; } \
220
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200221#define PYBIND_TYPE_CASTER_NUMBER(type, py_type, from_type, to_pytype) \
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200222 template <> class type_caster<type> { \
223 public: \
224 bool load(PyObject *src, bool) { \
225 value = (type) from_type(src); \
226 if (value == (type) -1 && PyErr_Occurred()) { \
227 PyErr_Clear(); \
228 return false; \
229 } \
230 return true; \
231 } \
232 static PyObject *cast(type src, return_value_policy /* policy */, PyObject * /* parent */) { \
233 return to_pytype((py_type) src); \
234 } \
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200235 PYBIND_TYPE_CASTER(type, #type); \
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200236 };
237
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200238PYBIND_TYPE_CASTER_NUMBER(int32_t, long, PyLong_AsLong, PyLong_FromLong)
239PYBIND_TYPE_CASTER_NUMBER(uint32_t, unsigned long, PyLong_AsUnsignedLong, PyLong_FromUnsignedLong)
240PYBIND_TYPE_CASTER_NUMBER(int64_t, PY_LONG_LONG, PyLong_AsLongLong, PyLong_FromLongLong)
241PYBIND_TYPE_CASTER_NUMBER(uint64_t, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong, PyLong_FromUnsignedLongLong)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200242
243#if defined(__APPLE__) // size_t/ssize_t are separate types on Mac OS X
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200244PYBIND_TYPE_CASTER_NUMBER(ssize_t, Py_ssize_t, PyLong_AsSsize_t, PyLong_FromSsize_t)
245PYBIND_TYPE_CASTER_NUMBER(size_t, size_t, PyLong_AsSize_t, PyLong_FromSize_t)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200246#endif
247
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200248PYBIND_TYPE_CASTER_NUMBER(float, float, PyFloat_AsDouble, PyFloat_FromDouble)
249PYBIND_TYPE_CASTER_NUMBER(double, double, PyFloat_AsDouble, PyFloat_FromDouble)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200250
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200251template <> class type_caster<void_type> {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200252public:
253 bool load(PyObject *, bool) { return true; }
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200254 static PyObject *cast(void_type, return_value_policy /* policy */, PyObject * /* parent */) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200255 Py_INCREF(Py_None);
256 return Py_None;
257 }
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200258 PYBIND_TYPE_CASTER(void_type, "None");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200259};
260
261template <> class type_caster<bool> {
262public:
263 bool load(PyObject *src, bool) {
264 if (src == Py_True) { value = true; return true; }
265 else if (src == Py_False) { value = false; return true; }
266 else return false;
267 }
268 static PyObject *cast(bool src, return_value_policy /* policy */, PyObject * /* parent */) {
269 PyObject *result = src ? Py_True : Py_False;
270 Py_INCREF(result);
271 return result;
272 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200273 PYBIND_TYPE_CASTER(bool, "bool");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200274};
275
276template <> class type_caster<std::string> {
277public:
278 bool load(PyObject *src, bool) {
279 const char *ptr = PyUnicode_AsUTF8(src);
280 if (!ptr) { PyErr_Clear(); return false; }
281 value = std::string(ptr);
282 return true;
283 }
284 static PyObject *cast(const std::string &src, return_value_policy /* policy */, PyObject * /* parent */) {
285 return PyUnicode_FromString(src.c_str());
286 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200287 PYBIND_TYPE_CASTER(std::string, "str");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200288};
289
Wenzel Jakob2ac80e72015-07-22 00:59:01 +0200290#ifdef HAVE_WCHAR_H
291template <> class type_caster<std::wstring> {
292public:
293 bool load(PyObject *src, bool) {
294 const wchar_t *ptr = PyUnicode_AsWideCharString(src, nullptr);
295 if (!ptr) { PyErr_Clear(); return false; }
296 value = std::wstring(ptr);
297 return true;
298 }
299 static PyObject *cast(const std::wstring &src, return_value_policy /* policy */, PyObject * /* parent */) {
300 return PyUnicode_FromWideChar(src.c_str(), src.length());
301 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200302 PYBIND_TYPE_CASTER(std::wstring, "wstr");
Wenzel Jakob2ac80e72015-07-22 00:59:01 +0200303};
304#endif
305
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200306template <> class type_caster<char> {
307public:
308 bool load(PyObject *src, bool) {
309 char *ptr = PyUnicode_AsUTF8(src);
310 if (!ptr) { PyErr_Clear(); return false; }
311 value = ptr;
312 return true;
313 }
314
315 static PyObject *cast(const char *src, return_value_policy /* policy */, PyObject * /* parent */) {
316 return PyUnicode_FromString(src);
317 }
318
319 static PyObject *cast(char src, return_value_policy /* policy */, PyObject * /* parent */) {
320 char str[2] = { src, '\0' };
321 return PyUnicode_DecodeLatin1(str, 1, nullptr);
322 }
323
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200324 static descr descr() { return "str"; }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200325
326 operator char*() { return value; }
327 operator char() { return *value; }
328protected:
329 char *value;
330};
331
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200332template <typename T1, typename T2> class type_caster<std::pair<T1, T2>> {
333 typedef std::pair<T1, T2> type;
334public:
335 bool load(PyObject *src, bool convert) {
336 if (!PyTuple_Check(src) || PyTuple_Size(src) != 2)
337 return false;
338 if (!first.load(PyTuple_GetItem(src, 0), convert))
339 return false;
340 return second.load(PyTuple_GetItem(src, 1), convert);
341 }
342
343 static PyObject *cast(const type &src, return_value_policy policy, PyObject *parent) {
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200344 PyObject *o1 = type_caster<typename decay<T1>::type>::cast(src.first, policy, parent);
345 PyObject *o2 = type_caster<typename decay<T2>::type>::cast(src.second, policy, parent);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200346 if (!o1 || !o2) {
347 Py_XDECREF(o1);
348 Py_XDECREF(o2);
349 return nullptr;
350 }
351 PyObject *tuple = PyTuple_New(2);
352 PyTuple_SetItem(tuple, 0, o1);
353 PyTuple_SetItem(tuple, 1, o2);
354 return tuple;
355 }
356
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200357 static descr descr() {
358 class descr result("(");
359 result += std::move(type_caster<typename decay<T1>::type>::descr());
360 result += ", ";
361 result += std::move(type_caster<typename decay<T2>::type>::descr());
362 result += ")";
363 return result;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200364 }
365
366 operator type() {
367 return type(first, second);
368 }
369protected:
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200370 type_caster<typename decay<T1>::type> first;
371 type_caster<typename decay<T2>::type> second;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200372};
373
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200374template <typename... Tuple> class type_caster<std::tuple<Tuple...>> {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200375 typedef std::tuple<Tuple...> type;
376public:
377 enum { size = sizeof...(Tuple) };
378
379 bool load(PyObject *src, bool convert) {
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200380 return load(src, convert, typename make_index_sequence<sizeof...(Tuple)>::type());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200381 }
382
383 static PyObject *cast(const type &src, return_value_policy policy, PyObject *parent) {
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200384 return cast(src, policy, parent, typename make_index_sequence<size>::type());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200385 }
386
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200387 static descr descr(const char **keywords = nullptr, const char **values = nullptr) {
388 std::array<class descr, size> descrs {{
389 type_caster<typename decay<Tuple>::type>::descr()...
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200390 }};
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200391 class descr result("(");
392 for (int i=0; i<size; ++i) {
393 if (keywords && keywords[i]) {
394 result += keywords[i];
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200395 result += " : ";
396 }
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200397 result += std::move(descrs[i]);
398 if (values && values[i]) {
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200399 result += " = ";
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200400 result += values[i];
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200401 }
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200402 if (i+1 < size)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200403 result += ", ";
404 }
405 result += ")";
406 return result;
407 }
408
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200409 template <typename ReturnValue, typename Func> typename std::enable_if<!std::is_void<ReturnValue>::value, ReturnValue>::type call(Func &&f) {
410 return call<ReturnValue>(std::forward<Func>(f), typename make_index_sequence<sizeof...(Tuple)>::type());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200411 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200412
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200413 template <typename ReturnValue, typename Func> typename std::enable_if<std::is_void<ReturnValue>::value, void_type>::type call(Func &&f) {
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200414 call<ReturnValue>(std::forward<Func>(f), typename make_index_sequence<sizeof...(Tuple)>::type());
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200415 return void_type();
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200416 }
417
418 operator type() {
419 return cast(typename make_index_sequence<sizeof...(Tuple)>::type());
420 }
421
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200422protected:
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200423 template <typename ReturnValue, typename Func, size_t ... Index> ReturnValue call(Func &&f, index_sequence<Index...>) {
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200424 return f((Tuple) std::get<Index>(value)...);
425 }
426
427 template <size_t ... Index> type cast(index_sequence<Index...>) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200428 return type((Tuple) std::get<Index>(value)...);
429 }
430
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200431 template <size_t ... Indices> bool load(PyObject *src, bool convert, index_sequence<Indices...>) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200432 if (!PyTuple_Check(src))
433 return false;
434 if (PyTuple_Size(src) != size)
435 return false;
436 std::array<bool, size> results {{
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200437 (PyTuple_GET_ITEM(src, Indices) != nullptr ? std::get<Indices>(value).load(PyTuple_GET_ITEM(src, Indices), convert) : false)...
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200438 }};
Wenzel Jakobf5fae922015-08-24 15:31:24 +0200439 (void) convert; /* avoid a warning when the tuple is empty */
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200440 for (bool r : results)
441 if (!r)
442 return false;
443 return true;
444 }
445
446 /* Implementation: Convert a C++ tuple into a Python tuple */
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200447 template <size_t ... Indices> static PyObject *cast(const type &src, return_value_policy policy, PyObject *parent, index_sequence<Indices...>) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200448 std::array<PyObject *, size> results {{
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200449 type_caster<typename decay<Tuple>::type>::cast(std::get<Indices>(src), policy, parent)...
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200450 }};
451 bool success = true;
452 for (auto result : results)
453 if (result == nullptr)
454 success = false;
455 if (success) {
456 PyObject *tuple = PyTuple_New(size);
457 int counter = 0;
458 for (auto result : results)
459 PyTuple_SetItem(tuple, counter++, result);
460 return tuple;
461 } else {
462 for (auto result : results) {
463 Py_XDECREF(result);
464 }
465 return nullptr;
466 }
467 }
468
469protected:
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200470 std::tuple<type_caster<typename decay<Tuple>::type>...> value;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200471};
472
473/// Type caster for holder types like std::shared_ptr, etc.
474template <typename type, typename holder_type> class type_caster_holder : public type_caster<type> {
475public:
476 typedef type_caster<type> parent;
477 bool load(PyObject *src, bool convert) {
478 if (!parent::load(src, convert))
479 return false;
480 holder = holder_type(parent::value);
481 return true;
482 }
483 explicit operator type*() { return this->value; }
484 explicit operator type&() { return *(this->value); }
485 explicit operator holder_type&() { return holder; }
486 explicit operator holder_type*() { return &holder; }
487protected:
488 holder_type holder;
489};
490
491template <> class type_caster<handle> {
492public:
493 bool load(PyObject *src) {
494 value = handle(src);
495 return true;
496 }
497 static PyObject *cast(const handle &src, return_value_policy /* policy */, PyObject * /* parent */) {
498 src.inc_ref();
499 return (PyObject *) src.ptr();
500 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200501 PYBIND_TYPE_CASTER(handle, "handle");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200502};
503
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200504#define PYBIND_TYPE_CASTER_PYTYPE(name) \
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200505 template <> class type_caster<name> { \
506 public: \
507 bool load(PyObject *src, bool) { value = name(src, true); return true; } \
508 static PyObject *cast(const name &src, return_value_policy /* policy */, PyObject * /* parent */) { \
509 src.inc_ref(); return (PyObject *) src.ptr(); \
510 } \
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200511 PYBIND_TYPE_CASTER(name, #name); \
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200512 };
513
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200514PYBIND_TYPE_CASTER_PYTYPE(object) PYBIND_TYPE_CASTER_PYTYPE(buffer)
515PYBIND_TYPE_CASTER_PYTYPE(capsule) PYBIND_TYPE_CASTER_PYTYPE(dict)
516PYBIND_TYPE_CASTER_PYTYPE(float_) PYBIND_TYPE_CASTER_PYTYPE(int_)
517PYBIND_TYPE_CASTER_PYTYPE(list) PYBIND_TYPE_CASTER_PYTYPE(slice)
518PYBIND_TYPE_CASTER_PYTYPE(tuple) PYBIND_TYPE_CASTER_PYTYPE(function)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200519
520NAMESPACE_END(detail)
521
522template <typename T> inline T cast(PyObject *object) {
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200523 detail::type_caster<typename detail::decay<T>::type> conv;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200524 if (!conv.load(object, true))
525 throw cast_error("Unable to cast Python object to C++ type");
526 return conv;
527}
528
529template <typename T> inline object cast(const T &value, return_value_policy policy = return_value_policy::automatic, PyObject *parent = nullptr) {
530 if (policy == return_value_policy::automatic)
531 policy = std::is_pointer<T>::value ? return_value_policy::take_ownership : return_value_policy::copy;
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200532 return object(detail::type_caster<typename detail::decay<T>::type>::cast(value, policy, parent), false);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200533}
534
535template <typename T> inline T handle::cast() { return pybind::cast<T>(m_ptr); }
536
Wenzel Jakob281aa0e2015-07-30 15:29:00 +0200537template <typename... Args> inline object handle::call(Args&&... args_) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200538 const size_t size = sizeof...(Args);
539 std::array<PyObject *, size> args{
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200540 { detail::type_caster<typename detail::decay<Args>::type>::cast(
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200541 std::forward<Args>(args_), return_value_policy::automatic, nullptr)... }
542 };
543 bool fail = false;
544 for (auto result : args)
545 if (result == nullptr)
546 fail = true;
547 if (fail) {
548 for (auto result : args) {
549 Py_XDECREF(result);
550 }
551 throw cast_error("handle::call(): unable to convert input arguments to Python objects");
552 }
553 PyObject *tuple = PyTuple_New(size);
554 int counter = 0;
555 for (auto result : args)
556 PyTuple_SetItem(tuple, counter++, result);
557 PyObject *result = PyObject_CallObject(m_ptr, tuple);
558 Py_DECREF(tuple);
559 return object(result, false);
560}
561
562NAMESPACE_END(pybind)