blob: 301304764a66e48eedaa6fe1711a1fd9e7ef8c4b [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 <map>
16#include <array>
17
18NAMESPACE_BEGIN(pybind)
19NAMESPACE_BEGIN(detail)
20
21/// Generic type caster for objects stored on the heap
22template <typename type> class type_caster {
23public:
24 typedef instance<type> instance_type;
25
26 static std::string name() { return type_id<type>(); }
27
28 type_caster() {
29 auto const& registered_types = get_internals().registered_types;
30 auto it = registered_types.find(type_id<type>());
31 if (it != registered_types.end())
32 typeinfo = &it->second;
33 }
34
35 bool load(PyObject *src, bool convert) {
36 if (src == nullptr || typeinfo == nullptr)
37 return false;
38 if (PyType_IsSubtype(Py_TYPE(src), typeinfo->type)) {
39 value = ((instance_type *) src)->value;
40 return true;
41 }
42 if (convert) {
43 for (auto &converter : typeinfo->implicit_conversions) {
44 temp = object(converter(src, typeinfo->type), false);
45 if (load(temp.ptr(), false))
46 return true;
47 }
48 }
49 return false;
50 }
51
52 static PyObject *cast(const type &src, return_value_policy policy, PyObject *parent) {
53 if (policy == return_value_policy::automatic)
54 policy = return_value_policy::copy;
55 return cast(&src, policy, parent);
56 }
57
58 static PyObject *cast(const type *_src, return_value_policy policy, PyObject *parent) {
59 type *src = const_cast<type *>(_src);
60 if (src == nullptr) {
61 Py_INCREF(Py_None);
62 return Py_None;
63 }
64 // avoid an issue with internal references matching their parent's address
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020065 bool dont_cache = policy == return_value_policy::reference_internal &&
66 parent && ((instance<void> *) parent)->value == (void *) src;
Wenzel Jakob38bd7112015-07-05 20:05:44 +020067 auto& internals = get_internals();
68 auto it_instance = internals.registered_instances.find(src);
69 if (it_instance != internals.registered_instances.end() && !dont_cache) {
70 PyObject *inst = it_instance->second;
71 Py_INCREF(inst);
72 return inst;
73 }
74 auto it = internals.registered_types.find(type_id<type>());
75 if (it == internals.registered_types.end()) {
76 std::string msg = std::string("Unregistered type : ") + type_id<type>();
77 PyErr_SetString(PyExc_TypeError, msg.c_str());
78 return nullptr;
79 }
80 auto &type_info = it->second;
81 instance_type *inst = (instance_type *) PyType_GenericAlloc(type_info.type, 0);
82 inst->value = src;
83 inst->owned = true;
84 inst->parent = nullptr;
85 if (policy == return_value_policy::automatic)
86 policy = return_value_policy::take_ownership;
87 handle_return_value_policy<type>(inst, policy, parent);
88 PyObject *inst_pyobj = (PyObject *) inst;
89 type_info.init_holder(inst_pyobj);
90 if (!dont_cache)
91 internals.registered_instances[inst->value] = inst_pyobj;
92 return inst_pyobj;
93 }
94
95 template <class T, typename std::enable_if<std::is_copy_constructible<T>::value, int>::type = 0>
96 static void handle_return_value_policy(instance<T> *inst, return_value_policy policy, PyObject *parent) {
97 if (policy == return_value_policy::copy) {
98 inst->value = new T(*(inst->value));
99 } else if (policy == return_value_policy::reference) {
100 inst->owned = false;
101 } else if (policy == return_value_policy::reference_internal) {
102 inst->owned = false;
103 inst->parent = parent;
104 Py_XINCREF(parent);
105 }
106 }
107
108 template <class T, typename std::enable_if<!std::is_copy_constructible<T>::value, int>::type = 0>
109 static void handle_return_value_policy(instance<T> *inst, return_value_policy policy, PyObject *parent) {
110 if (policy == return_value_policy::copy) {
111 throw cast_error("return_value_policy = copy, but the object is non-copyable!");
112 } else if (policy == return_value_policy::reference) {
113 inst->owned = false;
114 } else if (policy == return_value_policy::reference_internal) {
115 inst->owned = false;
116 inst->parent = parent;
117 Py_XINCREF(parent);
118 }
119 }
120
121 operator type*() { return value; }
122 operator type&() { return *value; }
123protected:
124 type *value = nullptr;
125 const type_info *typeinfo = nullptr;
126 object temp;
127};
128
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200129#define PYBIND_TYPE_CASTER(type, py_name) \
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200130 protected: \
131 type value; \
132 public: \
133 static std::string name() { return py_name; } \
134 static PyObject *cast(const type *src, return_value_policy policy, PyObject *parent) { \
135 return cast(*src, policy, parent); \
136 } \
137 operator type*() { return &value; } \
138 operator type&() { return value; } \
139
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200140#define PYBIND_TYPE_CASTER_NUMBER(type, py_type, from_type, to_pytype) \
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200141 template <> class type_caster<type> { \
142 public: \
143 bool load(PyObject *src, bool) { \
144 value = (type) from_type(src); \
145 if (value == (type) -1 && PyErr_Occurred()) { \
146 PyErr_Clear(); \
147 return false; \
148 } \
149 return true; \
150 } \
151 static PyObject *cast(type src, return_value_policy /* policy */, PyObject * /* parent */) { \
152 return to_pytype((py_type) src); \
153 } \
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200154 PYBIND_TYPE_CASTER(type, #type); \
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200155 };
156
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200157PYBIND_TYPE_CASTER_NUMBER(int32_t, long, PyLong_AsLong, PyLong_FromLong)
158PYBIND_TYPE_CASTER_NUMBER(uint32_t, unsigned long, PyLong_AsUnsignedLong, PyLong_FromUnsignedLong)
159PYBIND_TYPE_CASTER_NUMBER(int64_t, PY_LONG_LONG, PyLong_AsLongLong, PyLong_FromLongLong)
160PYBIND_TYPE_CASTER_NUMBER(uint64_t, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong, PyLong_FromUnsignedLongLong)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200161
162#if defined(__APPLE__) // size_t/ssize_t are separate types on Mac OS X
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200163PYBIND_TYPE_CASTER_NUMBER(ssize_t, Py_ssize_t, PyLong_AsSsize_t, PyLong_FromSsize_t)
164PYBIND_TYPE_CASTER_NUMBER(size_t, size_t, PyLong_AsSize_t, PyLong_FromSize_t)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200165#endif
166
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200167PYBIND_TYPE_CASTER_NUMBER(float, float, PyFloat_AsDouble, PyFloat_FromDouble)
168PYBIND_TYPE_CASTER_NUMBER(double, double, PyFloat_AsDouble, PyFloat_FromDouble)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200169
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200170template <> class type_caster<detail::void_type> {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200171public:
172 bool load(PyObject *, bool) { return true; }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200173 static PyObject *cast(detail::void_type, return_value_policy /* policy */, PyObject * /* parent */) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200174 Py_INCREF(Py_None);
175 return Py_None;
176 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200177 PYBIND_TYPE_CASTER(detail::void_type, "None");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200178};
179
180template <> class type_caster<bool> {
181public:
182 bool load(PyObject *src, bool) {
183 if (src == Py_True) { value = true; return true; }
184 else if (src == Py_False) { value = false; return true; }
185 else return false;
186 }
187 static PyObject *cast(bool src, return_value_policy /* policy */, PyObject * /* parent */) {
188 PyObject *result = src ? Py_True : Py_False;
189 Py_INCREF(result);
190 return result;
191 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200192 PYBIND_TYPE_CASTER(bool, "bool");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200193};
194
Wenzel Jakob43398a82015-07-28 16:12:20 +0200195template <typename T> class type_caster<std::complex<T>> {
196public:
197 bool load(PyObject *src, bool) {
198 Py_complex result = PyComplex_AsCComplex(src);
199 if (result.real == -1.0 && PyErr_Occurred()) {
200 PyErr_Clear();
201 return false;
202 }
203 value = std::complex<T>((T) result.real, (T) result.imag);
204 return true;
205 }
206 static PyObject *cast(const std::complex<T> &src, return_value_policy /* policy */, PyObject * /* parent */) {
207 return PyComplex_FromDoubles((double) src.real(), (double) src.imag());
208 }
209 PYBIND_TYPE_CASTER(std::complex<T>, "complex");
210};
211
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200212template <> class type_caster<std::string> {
213public:
214 bool load(PyObject *src, bool) {
215 const char *ptr = PyUnicode_AsUTF8(src);
216 if (!ptr) { PyErr_Clear(); return false; }
217 value = std::string(ptr);
218 return true;
219 }
220 static PyObject *cast(const std::string &src, return_value_policy /* policy */, PyObject * /* parent */) {
221 return PyUnicode_FromString(src.c_str());
222 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200223 PYBIND_TYPE_CASTER(std::string, "str");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200224};
225
Wenzel Jakob2ac80e72015-07-22 00:59:01 +0200226#ifdef HAVE_WCHAR_H
227template <> class type_caster<std::wstring> {
228public:
229 bool load(PyObject *src, bool) {
230 const wchar_t *ptr = PyUnicode_AsWideCharString(src, nullptr);
231 if (!ptr) { PyErr_Clear(); return false; }
232 value = std::wstring(ptr);
233 return true;
234 }
235 static PyObject *cast(const std::wstring &src, return_value_policy /* policy */, PyObject * /* parent */) {
236 return PyUnicode_FromWideChar(src.c_str(), src.length());
237 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200238 PYBIND_TYPE_CASTER(std::wstring, "wstr");
Wenzel Jakob2ac80e72015-07-22 00:59:01 +0200239};
240#endif
241
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200242template <> class type_caster<char> {
243public:
244 bool load(PyObject *src, bool) {
245 char *ptr = PyUnicode_AsUTF8(src);
246 if (!ptr) { PyErr_Clear(); return false; }
247 value = ptr;
248 return true;
249 }
250
251 static PyObject *cast(const char *src, return_value_policy /* policy */, PyObject * /* parent */) {
252 return PyUnicode_FromString(src);
253 }
254
255 static PyObject *cast(char src, return_value_policy /* policy */, PyObject * /* parent */) {
256 char str[2] = { src, '\0' };
257 return PyUnicode_DecodeLatin1(str, 1, nullptr);
258 }
259
260 static std::string name() { return "str"; }
261
262 operator char*() { return value; }
263 operator char() { return *value; }
264protected:
265 char *value;
266};
267
268template <typename Value> struct type_caster<std::vector<Value>> {
269 typedef std::vector<Value> type;
270 typedef type_caster<Value> value_conv;
271public:
272 bool load(PyObject *src, bool convert) {
273 if (!PyList_Check(src))
274 return false;
275 size_t size = (size_t) PyList_GET_SIZE(src);
276 value.reserve(size);
277 value.clear();
278 for (size_t i=0; i<size; ++i) {
279 value_conv conv;
280 if (!conv.load(PyList_GetItem(src, (ssize_t) i), convert))
281 return false;
282 value.push_back((Value) conv);
283 }
284 return true;
285 }
286
287 static PyObject *cast(const type &src, return_value_policy policy, PyObject *parent) {
288 PyObject *list = PyList_New(src.size());
289 size_t index = 0;
290 for (auto const &value: src) {
291 PyObject *value_ = value_conv::cast(value, policy, parent);
292 if (!value_) {
293 Py_DECREF(list);
294 return nullptr;
295 }
296 PyList_SetItem(list, index++, value_);
297 }
298 return list;
299 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200300 PYBIND_TYPE_CASTER(type, "list<" + value_conv::name() + ">");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200301};
302
303template <typename Key, typename Value> struct type_caster<std::map<Key, Value>> {
304public:
305 typedef std::map<Key, Value> type;
306 typedef type_caster<Key> key_conv;
307 typedef type_caster<Value> value_conv;
308
309 bool load(PyObject *src, bool convert) {
310 if (!PyDict_Check(src))
311 return false;
312
313 value.clear();
314 PyObject *key_, *value_;
315 ssize_t pos = 0;
316 key_conv kconv;
317 value_conv vconv;
318 while (PyDict_Next(src, &pos, &key_, &value_)) {
319 if (!kconv.load(key_, convert) || !vconv.load(value_, convert))
320 return false;
321 value[kconv] = vconv;
322 }
323 return true;
324 }
325
326 static PyObject *cast(const type &src, return_value_policy policy, PyObject *parent) {
327 PyObject *dict = PyDict_New();
328 for (auto const &kv: src) {
329 PyObject *key = key_conv::cast(kv.first, policy, parent);
330 PyObject *value = value_conv::cast(kv.second, policy, parent);
331 if (!key || !value || PyDict_SetItem(dict, key, value) < 0) {
332 Py_XDECREF(key);
333 Py_XDECREF(value);
334 Py_DECREF(dict);
335 return nullptr;
336 }
337 Py_DECREF(key);
338 Py_DECREF(value);
339 }
340 return dict;
341 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200342 PYBIND_TYPE_CASTER(type, "dict<" + key_conv::name() + ", " + value_conv::name() + ">");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200343};
344
345template <typename T1, typename T2> class type_caster<std::pair<T1, T2>> {
346 typedef std::pair<T1, T2> type;
347public:
348 bool load(PyObject *src, bool convert) {
349 if (!PyTuple_Check(src) || PyTuple_Size(src) != 2)
350 return false;
351 if (!first.load(PyTuple_GetItem(src, 0), convert))
352 return false;
353 return second.load(PyTuple_GetItem(src, 1), convert);
354 }
355
356 static PyObject *cast(const type &src, return_value_policy policy, PyObject *parent) {
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200357 PyObject *o1 = type_caster<typename detail::decay<T1>::type>::cast(src.first, policy, parent);
358 PyObject *o2 = type_caster<typename detail::decay<T2>::type>::cast(src.second, policy, parent);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200359 if (!o1 || !o2) {
360 Py_XDECREF(o1);
361 Py_XDECREF(o2);
362 return nullptr;
363 }
364 PyObject *tuple = PyTuple_New(2);
365 PyTuple_SetItem(tuple, 0, o1);
366 PyTuple_SetItem(tuple, 1, o2);
367 return tuple;
368 }
369
370 static std::string name() {
371 return "(" + type_caster<T1>::name() + ", " + type_caster<T2>::name() + ")";
372 }
373
374 operator type() {
375 return type(first, second);
376 }
377protected:
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200378 type_caster<typename detail::decay<T1>::type> first;
379 type_caster<typename detail::decay<T2>::type> second;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200380};
381
382template <typename ... Tuple> class type_caster<std::tuple<Tuple...>> {
383 typedef std::tuple<Tuple...> type;
384public:
385 enum { size = sizeof...(Tuple) };
386
387 bool load(PyObject *src, bool convert) {
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200388 return load(src, convert, typename make_index_sequence<sizeof...(Tuple)>::type());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200389 }
390
391 static PyObject *cast(const type &src, return_value_policy policy, PyObject *parent) {
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200392 return cast(src, policy, parent, typename make_index_sequence<size>::type());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200393 }
394
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200395 static std::string name(const char **keywords = nullptr, const char **values = nullptr) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200396 std::array<std::string, size> names {{
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200397 type_caster<typename detail::decay<Tuple>::type>::name()...
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200398 }};
399 std::string result("(");
400 int counter = 0;
401 for (auto const &name : names) {
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200402 if (keywords && keywords[counter]) {
403 result += keywords[counter];
404 result += " : ";
405 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200406 result += name;
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200407 if (values && values[counter]) {
408 result += " = ";
409 result += values[counter];
410 }
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200411 if (++counter < size)
412 result += ", ";
413 }
414 result += ")";
415 return result;
416 }
417
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200418 template <typename ReturnValue, typename Func> typename std::enable_if<!std::is_void<ReturnValue>::value, ReturnValue>::type call(Func &&f) {
419 return call<ReturnValue>(std::forward<Func>(f), typename make_index_sequence<sizeof...(Tuple)>::type());
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200420 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200421
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200422 template <typename ReturnValue, typename Func> typename std::enable_if<std::is_void<ReturnValue>::value, detail::void_type>::type call(Func &&f) {
423 call<ReturnValue>(std::forward<Func>(f), typename make_index_sequence<sizeof...(Tuple)>::type());
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200424 return detail::void_type();
425 }
426
427 operator type() {
428 return cast(typename make_index_sequence<sizeof...(Tuple)>::type());
429 }
430
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200431protected:
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200432 template <typename ReturnValue, typename Func, size_t ... Index> ReturnValue call(Func &&f, index_sequence<Index...>) {
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200433 return f((Tuple) std::get<Index>(value)...);
434 }
435
436 template <size_t ... Index> type cast(index_sequence<Index...>) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200437 return type((Tuple) std::get<Index>(value)...);
438 }
439
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200440 template <size_t ... Indices> bool load(PyObject *src, bool convert, index_sequence<Indices...>) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200441 if (!PyTuple_Check(src))
442 return false;
443 if (PyTuple_Size(src) != size)
444 return false;
445 std::array<bool, size> results {{
446 std::get<Indices>(value).load(PyTuple_GetItem(src, Indices), convert)...
447 }};
448 for (bool r : results)
449 if (!r)
450 return false;
451 return true;
452 }
453
454 /* Implementation: Convert a C++ tuple into a Python tuple */
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200455 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 +0200456 std::array<PyObject *, size> results {{
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200457 type_caster<typename detail::decay<Tuple>::type>::cast(std::get<Indices>(src), policy, parent)...
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200458 }};
459 bool success = true;
460 for (auto result : results)
461 if (result == nullptr)
462 success = false;
463 if (success) {
464 PyObject *tuple = PyTuple_New(size);
465 int counter = 0;
466 for (auto result : results)
467 PyTuple_SetItem(tuple, counter++, result);
468 return tuple;
469 } else {
470 for (auto result : results) {
471 Py_XDECREF(result);
472 }
473 return nullptr;
474 }
475 }
476
477protected:
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200478 std::tuple<type_caster<typename detail::decay<Tuple>::type>...> value;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200479};
480
481/// Type caster for holder types like std::shared_ptr, etc.
482template <typename type, typename holder_type> class type_caster_holder : public type_caster<type> {
483public:
484 typedef type_caster<type> parent;
485 bool load(PyObject *src, bool convert) {
486 if (!parent::load(src, convert))
487 return false;
488 holder = holder_type(parent::value);
489 return true;
490 }
491 explicit operator type*() { return this->value; }
492 explicit operator type&() { return *(this->value); }
493 explicit operator holder_type&() { return holder; }
494 explicit operator holder_type*() { return &holder; }
495protected:
496 holder_type holder;
497};
498
499template <> class type_caster<handle> {
500public:
501 bool load(PyObject *src) {
502 value = handle(src);
503 return true;
504 }
505 static PyObject *cast(const handle &src, return_value_policy /* policy */, PyObject * /* parent */) {
506 src.inc_ref();
507 return (PyObject *) src.ptr();
508 }
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200509 PYBIND_TYPE_CASTER(handle, "handle");
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200510};
511
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200512#define PYBIND_TYPE_CASTER_PYTYPE(name) \
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200513 template <> class type_caster<name> { \
514 public: \
515 bool load(PyObject *src, bool) { value = name(src, true); return true; } \
516 static PyObject *cast(const name &src, return_value_policy /* policy */, PyObject * /* parent */) { \
517 src.inc_ref(); return (PyObject *) src.ptr(); \
518 } \
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200519 PYBIND_TYPE_CASTER(name, #name); \
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200520 };
521
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200522PYBIND_TYPE_CASTER_PYTYPE(object) PYBIND_TYPE_CASTER_PYTYPE(buffer)
523PYBIND_TYPE_CASTER_PYTYPE(capsule) PYBIND_TYPE_CASTER_PYTYPE(dict)
524PYBIND_TYPE_CASTER_PYTYPE(float_) PYBIND_TYPE_CASTER_PYTYPE(int_)
525PYBIND_TYPE_CASTER_PYTYPE(list) PYBIND_TYPE_CASTER_PYTYPE(slice)
526PYBIND_TYPE_CASTER_PYTYPE(tuple) PYBIND_TYPE_CASTER_PYTYPE(function)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200527
528NAMESPACE_END(detail)
529
530template <typename T> inline T cast(PyObject *object) {
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200531 detail::type_caster<typename detail::decay<T>::type> conv;
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200532 if (!conv.load(object, true))
533 throw cast_error("Unable to cast Python object to C++ type");
534 return conv;
535}
536
537template <typename T> inline object cast(const T &value, return_value_policy policy = return_value_policy::automatic, PyObject *parent = nullptr) {
538 if (policy == return_value_policy::automatic)
539 policy = std::is_pointer<T>::value ? return_value_policy::take_ownership : return_value_policy::copy;
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200540 return object(detail::type_caster<typename detail::decay<T>::type>::cast(value, policy, parent), false);
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200541}
542
543template <typename T> inline T handle::cast() { return pybind::cast<T>(m_ptr); }
544
545template <typename ... Args> inline object handle::call(Args&&... args_) {
546 const size_t size = sizeof...(Args);
547 std::array<PyObject *, size> args{
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200548 { detail::type_caster<typename detail::decay<Args>::type>::cast(
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200549 std::forward<Args>(args_), return_value_policy::automatic, nullptr)... }
550 };
551 bool fail = false;
552 for (auto result : args)
553 if (result == nullptr)
554 fail = true;
555 if (fail) {
556 for (auto result : args) {
557 Py_XDECREF(result);
558 }
559 throw cast_error("handle::call(): unable to convert input arguments to Python objects");
560 }
561 PyObject *tuple = PyTuple_New(size);
562 int counter = 0;
563 for (auto result : args)
564 PyTuple_SetItem(tuple, counter++, result);
565 PyObject *result = PyObject_CallObject(m_ptr, tuple);
566 Py_DECREF(tuple);
567 return object(result, false);
568}
569
570NAMESPACE_END(pybind)