blob: 6b3b96e3a50fd1403326f3ce6f308e23ceb19a11 [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
11#if !defined(__PYBIND_CAST)
12#define __PYBIND_CAST
13
14#include "pytypes.h"
15#include "mpl.h"
16#include "typeid.h"
17#include <map>
18#include <array>
19
20NAMESPACE_BEGIN(pybind)
21NAMESPACE_BEGIN(detail)
22
23/// Generic type caster for objects stored on the heap
24template <typename type> class type_caster {
25public:
26 typedef instance<type> instance_type;
27
28 static std::string name() { return type_id<type>(); }
29
30 type_caster() {
31 auto const& registered_types = get_internals().registered_types;
32 auto it = registered_types.find(type_id<type>());
33 if (it != registered_types.end())
34 typeinfo = &it->second;
35 }
36
37 bool load(PyObject *src, bool convert) {
38 if (src == nullptr || typeinfo == nullptr)
39 return false;
40 if (PyType_IsSubtype(Py_TYPE(src), typeinfo->type)) {
41 value = ((instance_type *) src)->value;
42 return true;
43 }
44 if (convert) {
45 for (auto &converter : typeinfo->implicit_conversions) {
46 temp = object(converter(src, typeinfo->type), false);
47 if (load(temp.ptr(), false))
48 return true;
49 }
50 }
51 return false;
52 }
53
54 static PyObject *cast(const type &src, return_value_policy policy, PyObject *parent) {
55 if (policy == return_value_policy::automatic)
56 policy = return_value_policy::copy;
57 return cast(&src, policy, parent);
58 }
59
60 static PyObject *cast(const type *_src, return_value_policy policy, PyObject *parent) {
61 type *src = const_cast<type *>(_src);
62 if (src == nullptr) {
63 Py_INCREF(Py_None);
64 return Py_None;
65 }
66 // avoid an issue with internal references matching their parent's address
67 bool dont_cache = parent && ((instance<void> *) parent)->value == (void *) src;
68 auto& internals = get_internals();
69 auto it_instance = internals.registered_instances.find(src);
70 if (it_instance != internals.registered_instances.end() && !dont_cache) {
71 PyObject *inst = it_instance->second;
72 Py_INCREF(inst);
73 return inst;
74 }
75 auto it = internals.registered_types.find(type_id<type>());
76 if (it == internals.registered_types.end()) {
77 std::string msg = std::string("Unregistered type : ") + type_id<type>();
78 PyErr_SetString(PyExc_TypeError, msg.c_str());
79 return nullptr;
80 }
81 auto &type_info = it->second;
82 instance_type *inst = (instance_type *) PyType_GenericAlloc(type_info.type, 0);
83 inst->value = src;
84 inst->owned = true;
85 inst->parent = nullptr;
86 if (policy == return_value_policy::automatic)
87 policy = return_value_policy::take_ownership;
88 handle_return_value_policy<type>(inst, policy, parent);
89 PyObject *inst_pyobj = (PyObject *) inst;
90 type_info.init_holder(inst_pyobj);
91 if (!dont_cache)
92 internals.registered_instances[inst->value] = inst_pyobj;
93 return inst_pyobj;
94 }
95
96 template <class T, typename std::enable_if<std::is_copy_constructible<T>::value, int>::type = 0>
97 static void handle_return_value_policy(instance<T> *inst, return_value_policy policy, PyObject *parent) {
98 if (policy == return_value_policy::copy) {
99 inst->value = new T(*(inst->value));
100 } else if (policy == return_value_policy::reference) {
101 inst->owned = false;
102 } else if (policy == return_value_policy::reference_internal) {
103 inst->owned = false;
104 inst->parent = parent;
105 Py_XINCREF(parent);
106 }
107 }
108
109 template <class T, typename std::enable_if<!std::is_copy_constructible<T>::value, int>::type = 0>
110 static void handle_return_value_policy(instance<T> *inst, return_value_policy policy, PyObject *parent) {
111 if (policy == return_value_policy::copy) {
112 throw cast_error("return_value_policy = copy, but the object is non-copyable!");
113 } else if (policy == return_value_policy::reference) {
114 inst->owned = false;
115 } else if (policy == return_value_policy::reference_internal) {
116 inst->owned = false;
117 inst->parent = parent;
118 Py_XINCREF(parent);
119 }
120 }
121
122 operator type*() { return value; }
123 operator type&() { return *value; }
124protected:
125 type *value = nullptr;
126 const type_info *typeinfo = nullptr;
127 object temp;
128};
129
130#define TYPE_CASTER(type, py_name) \
131 protected: \
132 type value; \
133 public: \
134 static std::string name() { return py_name; } \
135 static PyObject *cast(const type *src, return_value_policy policy, PyObject *parent) { \
136 return cast(*src, policy, parent); \
137 } \
138 operator type*() { return &value; } \
139 operator type&() { return value; } \
140
141#define TYPE_CASTER_NUMBER(type, py_type, from_type, to_pytype) \
142 template <> class type_caster<type> { \
143 public: \
144 bool load(PyObject *src, bool) { \
145 value = (type) from_type(src); \
146 if (value == (type) -1 && PyErr_Occurred()) { \
147 PyErr_Clear(); \
148 return false; \
149 } \
150 return true; \
151 } \
152 static PyObject *cast(type src, return_value_policy /* policy */, PyObject * /* parent */) { \
153 return to_pytype((py_type) src); \
154 } \
155 TYPE_CASTER(type, #type); \
156 };
157
158TYPE_CASTER_NUMBER(int32_t, long, PyLong_AsLong, PyLong_FromLong)
159TYPE_CASTER_NUMBER(uint32_t, unsigned long, PyLong_AsUnsignedLong, PyLong_FromUnsignedLong)
160TYPE_CASTER_NUMBER(int64_t, PY_LONG_LONG, PyLong_AsLongLong, PyLong_FromLongLong)
161TYPE_CASTER_NUMBER(uint64_t, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong, PyLong_FromUnsignedLongLong)
162
163#if defined(__APPLE__) // size_t/ssize_t are separate types on Mac OS X
164TYPE_CASTER_NUMBER(ssize_t, Py_ssize_t, PyLong_AsSsize_t, PyLong_FromSsize_t)
165TYPE_CASTER_NUMBER(size_t, size_t, PyLong_AsSize_t, PyLong_FromSize_t)
166#endif
167
168TYPE_CASTER_NUMBER(float, float, PyFloat_AsDouble, PyFloat_FromDouble)
169TYPE_CASTER_NUMBER(double, double, PyFloat_AsDouble, PyFloat_FromDouble)
170
171template <> class type_caster<mpl::detail::void_type> {
172public:
173 bool load(PyObject *, bool) { return true; }
174 static PyObject *cast(mpl::detail::void_type, return_value_policy /* policy */, PyObject * /* parent */) {
175 Py_INCREF(Py_None);
176 return Py_None;
177 }
178 TYPE_CASTER(mpl::detail::void_type, "None");
179};
180
181template <> class type_caster<bool> {
182public:
183 bool load(PyObject *src, bool) {
184 if (src == Py_True) { value = true; return true; }
185 else if (src == Py_False) { value = false; return true; }
186 else return false;
187 }
188 static PyObject *cast(bool src, return_value_policy /* policy */, PyObject * /* parent */) {
189 PyObject *result = src ? Py_True : Py_False;
190 Py_INCREF(result);
191 return result;
192 }
193 TYPE_CASTER(bool, "bool");
194};
195
196template <> class type_caster<std::string> {
197public:
198 bool load(PyObject *src, bool) {
199 const char *ptr = PyUnicode_AsUTF8(src);
200 if (!ptr) { PyErr_Clear(); return false; }
201 value = std::string(ptr);
202 return true;
203 }
204 static PyObject *cast(const std::string &src, return_value_policy /* policy */, PyObject * /* parent */) {
205 return PyUnicode_FromString(src.c_str());
206 }
207 TYPE_CASTER(std::string, "str");
208};
209
210template <> class type_caster<char> {
211public:
212 bool load(PyObject *src, bool) {
213 char *ptr = PyUnicode_AsUTF8(src);
214 if (!ptr) { PyErr_Clear(); return false; }
215 value = ptr;
216 return true;
217 }
218
219 static PyObject *cast(const char *src, return_value_policy /* policy */, PyObject * /* parent */) {
220 return PyUnicode_FromString(src);
221 }
222
223 static PyObject *cast(char src, return_value_policy /* policy */, PyObject * /* parent */) {
224 char str[2] = { src, '\0' };
225 return PyUnicode_DecodeLatin1(str, 1, nullptr);
226 }
227
228 static std::string name() { return "str"; }
229
230 operator char*() { return value; }
231 operator char() { return *value; }
232protected:
233 char *value;
234};
235
236template <typename Value> struct type_caster<std::vector<Value>> {
237 typedef std::vector<Value> type;
238 typedef type_caster<Value> value_conv;
239public:
240 bool load(PyObject *src, bool convert) {
241 if (!PyList_Check(src))
242 return false;
243 size_t size = (size_t) PyList_GET_SIZE(src);
244 value.reserve(size);
245 value.clear();
246 for (size_t i=0; i<size; ++i) {
247 value_conv conv;
248 if (!conv.load(PyList_GetItem(src, (ssize_t) i), convert))
249 return false;
250 value.push_back((Value) conv);
251 }
252 return true;
253 }
254
255 static PyObject *cast(const type &src, return_value_policy policy, PyObject *parent) {
256 PyObject *list = PyList_New(src.size());
257 size_t index = 0;
258 for (auto const &value: src) {
259 PyObject *value_ = value_conv::cast(value, policy, parent);
260 if (!value_) {
261 Py_DECREF(list);
262 return nullptr;
263 }
264 PyList_SetItem(list, index++, value_);
265 }
266 return list;
267 }
268 TYPE_CASTER(type, "list<" + value_conv::name() + ">");
269};
270
271template <typename Key, typename Value> struct type_caster<std::map<Key, Value>> {
272public:
273 typedef std::map<Key, Value> type;
274 typedef type_caster<Key> key_conv;
275 typedef type_caster<Value> value_conv;
276
277 bool load(PyObject *src, bool convert) {
278 if (!PyDict_Check(src))
279 return false;
280
281 value.clear();
282 PyObject *key_, *value_;
283 ssize_t pos = 0;
284 key_conv kconv;
285 value_conv vconv;
286 while (PyDict_Next(src, &pos, &key_, &value_)) {
287 if (!kconv.load(key_, convert) || !vconv.load(value_, convert))
288 return false;
289 value[kconv] = vconv;
290 }
291 return true;
292 }
293
294 static PyObject *cast(const type &src, return_value_policy policy, PyObject *parent) {
295 PyObject *dict = PyDict_New();
296 for (auto const &kv: src) {
297 PyObject *key = key_conv::cast(kv.first, policy, parent);
298 PyObject *value = value_conv::cast(kv.second, policy, parent);
299 if (!key || !value || PyDict_SetItem(dict, key, value) < 0) {
300 Py_XDECREF(key);
301 Py_XDECREF(value);
302 Py_DECREF(dict);
303 return nullptr;
304 }
305 Py_DECREF(key);
306 Py_DECREF(value);
307 }
308 return dict;
309 }
310 TYPE_CASTER(type, "dict<" + key_conv::name() + ", " + value_conv::name() + ">");
311};
312
313template <typename T1, typename T2> class type_caster<std::pair<T1, T2>> {
314 typedef std::pair<T1, T2> type;
315public:
316 bool load(PyObject *src, bool convert) {
317 if (!PyTuple_Check(src) || PyTuple_Size(src) != 2)
318 return false;
319 if (!first.load(PyTuple_GetItem(src, 0), convert))
320 return false;
321 return second.load(PyTuple_GetItem(src, 1), convert);
322 }
323
324 static PyObject *cast(const type &src, return_value_policy policy, PyObject *parent) {
325 PyObject *o1 = type_caster<typename mpl::normalize_type<T1>::type>::cast(src.first, policy, parent);
326 PyObject *o2 = type_caster<typename mpl::normalize_type<T2>::type>::cast(src.second, policy, parent);
327 if (!o1 || !o2) {
328 Py_XDECREF(o1);
329 Py_XDECREF(o2);
330 return nullptr;
331 }
332 PyObject *tuple = PyTuple_New(2);
333 PyTuple_SetItem(tuple, 0, o1);
334 PyTuple_SetItem(tuple, 1, o2);
335 return tuple;
336 }
337
338 static std::string name() {
339 return "(" + type_caster<T1>::name() + ", " + type_caster<T2>::name() + ")";
340 }
341
342 operator type() {
343 return type(first, second);
344 }
345protected:
346 type_caster<typename mpl::normalize_type<T1>::type> first;
347 type_caster<typename mpl::normalize_type<T2>::type> second;
348};
349
350template <typename ... Tuple> class type_caster<std::tuple<Tuple...>> {
351 typedef std::tuple<Tuple...> type;
352public:
353 enum { size = sizeof...(Tuple) };
354
355 bool load(PyObject *src, bool convert) {
356 return load(src, convert, typename mpl::make_index_sequence<sizeof...(Tuple)>::type());
357 }
358
359 static PyObject *cast(const type &src, return_value_policy policy, PyObject *parent) {
360 return cast(src, policy, parent, typename mpl::make_index_sequence<size>::type());
361 }
362
363 static std::string name() {
364 std::array<std::string, size> names {{
365 type_caster<typename mpl::normalize_type<Tuple>::type>::name()...
366 }};
367 std::string result("(");
368 int counter = 0;
369 for (auto const &name : names) {
370 result += name;
371 if (++counter < size)
372 result += ", ";
373 }
374 result += ")";
375 return result;
376 }
377
378 operator type() {
379 return cast(typename mpl::make_index_sequence<sizeof...(Tuple)>::type());
380 }
381protected:
382 template <size_t ... Index> type cast(mpl::index_sequence<Index...>) {
383 return type((Tuple) std::get<Index>(value)...);
384 }
385
386 template <size_t ... Indices> bool load(PyObject *src, bool convert, mpl::index_sequence<Indices...>) {
387 if (!PyTuple_Check(src))
388 return false;
389 if (PyTuple_Size(src) != size)
390 return false;
391 std::array<bool, size> results {{
392 std::get<Indices>(value).load(PyTuple_GetItem(src, Indices), convert)...
393 }};
394 for (bool r : results)
395 if (!r)
396 return false;
397 return true;
398 }
399
400 /* Implementation: Convert a C++ tuple into a Python tuple */
401 template <size_t ... Indices> static PyObject *cast(const type &src, return_value_policy policy, PyObject *parent, mpl::index_sequence<Indices...>) {
402 std::array<PyObject *, size> results {{
403 type_caster<typename mpl::normalize_type<Tuple>::type>::cast(std::get<Indices>(src), policy, parent)...
404 }};
405 bool success = true;
406 for (auto result : results)
407 if (result == nullptr)
408 success = false;
409 if (success) {
410 PyObject *tuple = PyTuple_New(size);
411 int counter = 0;
412 for (auto result : results)
413 PyTuple_SetItem(tuple, counter++, result);
414 return tuple;
415 } else {
416 for (auto result : results) {
417 Py_XDECREF(result);
418 }
419 return nullptr;
420 }
421 }
422
423protected:
424 std::tuple<type_caster<typename mpl::normalize_type<Tuple>::type>...> value;
425};
426
427/// Type caster for holder types like std::shared_ptr, etc.
428template <typename type, typename holder_type> class type_caster_holder : public type_caster<type> {
429public:
430 typedef type_caster<type> parent;
431 bool load(PyObject *src, bool convert) {
432 if (!parent::load(src, convert))
433 return false;
434 holder = holder_type(parent::value);
435 return true;
436 }
437 explicit operator type*() { return this->value; }
438 explicit operator type&() { return *(this->value); }
439 explicit operator holder_type&() { return holder; }
440 explicit operator holder_type*() { return &holder; }
441protected:
442 holder_type holder;
443};
444
445template <> class type_caster<handle> {
446public:
447 bool load(PyObject *src) {
448 value = handle(src);
449 return true;
450 }
451 static PyObject *cast(const handle &src, return_value_policy /* policy */, PyObject * /* parent */) {
452 src.inc_ref();
453 return (PyObject *) src.ptr();
454 }
455 TYPE_CASTER(handle, "handle");
456};
457
458#define TYPE_CASTER_PYTYPE(name) \
459 template <> class type_caster<name> { \
460 public: \
461 bool load(PyObject *src, bool) { value = name(src, true); return true; } \
462 static PyObject *cast(const name &src, return_value_policy /* policy */, PyObject * /* parent */) { \
463 src.inc_ref(); return (PyObject *) src.ptr(); \
464 } \
465 TYPE_CASTER(name, #name); \
466 };
467
468TYPE_CASTER_PYTYPE(object)
469TYPE_CASTER_PYTYPE(buffer)
470TYPE_CASTER_PYTYPE(capsule)
471TYPE_CASTER_PYTYPE(dict)
472TYPE_CASTER_PYTYPE(float_)
473TYPE_CASTER_PYTYPE(int_)
474TYPE_CASTER_PYTYPE(list)
475TYPE_CASTER_PYTYPE(slice)
476TYPE_CASTER_PYTYPE(tuple)
477
478#undef TYPE_CASTER
479#undef TYPE_CASTER_NUMBER
480#undef TYPE_CASTER_PYTYPE
481
482NAMESPACE_END(detail)
483
484template <typename T> inline T cast(PyObject *object) {
485 detail::type_caster<typename mpl::normalize_type<T>::type> conv;
486 if (!conv.load(object, true))
487 throw cast_error("Unable to cast Python object to C++ type");
488 return conv;
489}
490
491template <typename T> inline object cast(const T &value, return_value_policy policy = return_value_policy::automatic, PyObject *parent = nullptr) {
492 if (policy == return_value_policy::automatic)
493 policy = std::is_pointer<T>::value ? return_value_policy::take_ownership : return_value_policy::copy;
494 return object(detail::type_caster<typename mpl::normalize_type<T>::type>::cast(value, policy, parent), false);
495}
496
497template <typename T> inline T handle::cast() { return pybind::cast<T>(m_ptr); }
498
499template <typename ... Args> inline object handle::call(Args&&... args_) {
500 const size_t size = sizeof...(Args);
501 std::array<PyObject *, size> args{
502 { detail::type_caster<typename mpl::normalize_type<Args>::type>::cast(
503 std::forward<Args>(args_), return_value_policy::automatic, nullptr)... }
504 };
505 bool fail = false;
506 for (auto result : args)
507 if (result == nullptr)
508 fail = true;
509 if (fail) {
510 for (auto result : args) {
511 Py_XDECREF(result);
512 }
513 throw cast_error("handle::call(): unable to convert input arguments to Python objects");
514 }
515 PyObject *tuple = PyTuple_New(size);
516 int counter = 0;
517 for (auto result : args)
518 PyTuple_SetItem(tuple, counter++, result);
519 PyObject *result = PyObject_CallObject(m_ptr, tuple);
520 Py_DECREF(tuple);
521 return object(result, false);
522}
523
524NAMESPACE_END(pybind)
525
526#endif /* __PYBIND_CAST */