blob: 63ed19c94e77f0fc551546c67084b8b1140e363e [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>
14#include <pybind/mpl.h>
15#include <pybind/typeid.h>
Wenzel Jakob38bd7112015-07-05 20:05:44 +020016#include <map>
17#include <array>
18
19NAMESPACE_BEGIN(pybind)
20NAMESPACE_BEGIN(detail)
21
22/// Generic type caster for objects stored on the heap
23template <typename type> class type_caster {
24public:
25 typedef instance<type> instance_type;
26
27 static std::string name() { return type_id<type>(); }
28
29 type_caster() {
30 auto const& registered_types = get_internals().registered_types;
31 auto it = registered_types.find(type_id<type>());
32 if (it != registered_types.end())
33 typeinfo = &it->second;
34 }
35
36 bool load(PyObject *src, bool convert) {
37 if (src == nullptr || typeinfo == nullptr)
38 return false;
39 if (PyType_IsSubtype(Py_TYPE(src), typeinfo->type)) {
40 value = ((instance_type *) src)->value;
41 return true;
42 }
43 if (convert) {
44 for (auto &converter : typeinfo->implicit_conversions) {
45 temp = object(converter(src, typeinfo->type), false);
46 if (load(temp.ptr(), false))
47 return true;
48 }
49 }
50 return false;
51 }
52
53 static PyObject *cast(const type &src, return_value_policy policy, PyObject *parent) {
54 if (policy == return_value_policy::automatic)
55 policy = return_value_policy::copy;
56 return cast(&src, policy, parent);
57 }
58
59 static PyObject *cast(const type *_src, return_value_policy policy, PyObject *parent) {
60 type *src = const_cast<type *>(_src);
61 if (src == nullptr) {
62 Py_INCREF(Py_None);
63 return Py_None;
64 }
65 // avoid an issue with internal references matching their parent's address
66 bool dont_cache = parent && ((instance<void> *) parent)->value == (void *) src;
67 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
129#define TYPE_CASTER(type, py_name) \
130 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
140#define TYPE_CASTER_NUMBER(type, py_type, from_type, to_pytype) \
141 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 } \
154 TYPE_CASTER(type, #type); \
155 };
156
157TYPE_CASTER_NUMBER(int32_t, long, PyLong_AsLong, PyLong_FromLong)
158TYPE_CASTER_NUMBER(uint32_t, unsigned long, PyLong_AsUnsignedLong, PyLong_FromUnsignedLong)
159TYPE_CASTER_NUMBER(int64_t, PY_LONG_LONG, PyLong_AsLongLong, PyLong_FromLongLong)
160TYPE_CASTER_NUMBER(uint64_t, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong, PyLong_FromUnsignedLongLong)
161
162#if defined(__APPLE__) // size_t/ssize_t are separate types on Mac OS X
163TYPE_CASTER_NUMBER(ssize_t, Py_ssize_t, PyLong_AsSsize_t, PyLong_FromSsize_t)
164TYPE_CASTER_NUMBER(size_t, size_t, PyLong_AsSize_t, PyLong_FromSize_t)
165#endif
166
167TYPE_CASTER_NUMBER(float, float, PyFloat_AsDouble, PyFloat_FromDouble)
168TYPE_CASTER_NUMBER(double, double, PyFloat_AsDouble, PyFloat_FromDouble)
169
170template <> class type_caster<mpl::detail::void_type> {
171public:
172 bool load(PyObject *, bool) { return true; }
173 static PyObject *cast(mpl::detail::void_type, return_value_policy /* policy */, PyObject * /* parent */) {
174 Py_INCREF(Py_None);
175 return Py_None;
176 }
177 TYPE_CASTER(mpl::detail::void_type, "None");
178};
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 }
192 TYPE_CASTER(bool, "bool");
193};
194
195template <> class type_caster<std::string> {
196public:
197 bool load(PyObject *src, bool) {
198 const char *ptr = PyUnicode_AsUTF8(src);
199 if (!ptr) { PyErr_Clear(); return false; }
200 value = std::string(ptr);
201 return true;
202 }
203 static PyObject *cast(const std::string &src, return_value_policy /* policy */, PyObject * /* parent */) {
204 return PyUnicode_FromString(src.c_str());
205 }
206 TYPE_CASTER(std::string, "str");
207};
208
209template <> class type_caster<char> {
210public:
211 bool load(PyObject *src, bool) {
212 char *ptr = PyUnicode_AsUTF8(src);
213 if (!ptr) { PyErr_Clear(); return false; }
214 value = ptr;
215 return true;
216 }
217
218 static PyObject *cast(const char *src, return_value_policy /* policy */, PyObject * /* parent */) {
219 return PyUnicode_FromString(src);
220 }
221
222 static PyObject *cast(char src, return_value_policy /* policy */, PyObject * /* parent */) {
223 char str[2] = { src, '\0' };
224 return PyUnicode_DecodeLatin1(str, 1, nullptr);
225 }
226
227 static std::string name() { return "str"; }
228
229 operator char*() { return value; }
230 operator char() { return *value; }
231protected:
232 char *value;
233};
234
235template <typename Value> struct type_caster<std::vector<Value>> {
236 typedef std::vector<Value> type;
237 typedef type_caster<Value> value_conv;
238public:
239 bool load(PyObject *src, bool convert) {
240 if (!PyList_Check(src))
241 return false;
242 size_t size = (size_t) PyList_GET_SIZE(src);
243 value.reserve(size);
244 value.clear();
245 for (size_t i=0; i<size; ++i) {
246 value_conv conv;
247 if (!conv.load(PyList_GetItem(src, (ssize_t) i), convert))
248 return false;
249 value.push_back((Value) conv);
250 }
251 return true;
252 }
253
254 static PyObject *cast(const type &src, return_value_policy policy, PyObject *parent) {
255 PyObject *list = PyList_New(src.size());
256 size_t index = 0;
257 for (auto const &value: src) {
258 PyObject *value_ = value_conv::cast(value, policy, parent);
259 if (!value_) {
260 Py_DECREF(list);
261 return nullptr;
262 }
263 PyList_SetItem(list, index++, value_);
264 }
265 return list;
266 }
267 TYPE_CASTER(type, "list<" + value_conv::name() + ">");
268};
269
270template <typename Key, typename Value> struct type_caster<std::map<Key, Value>> {
271public:
272 typedef std::map<Key, Value> type;
273 typedef type_caster<Key> key_conv;
274 typedef type_caster<Value> value_conv;
275
276 bool load(PyObject *src, bool convert) {
277 if (!PyDict_Check(src))
278 return false;
279
280 value.clear();
281 PyObject *key_, *value_;
282 ssize_t pos = 0;
283 key_conv kconv;
284 value_conv vconv;
285 while (PyDict_Next(src, &pos, &key_, &value_)) {
286 if (!kconv.load(key_, convert) || !vconv.load(value_, convert))
287 return false;
288 value[kconv] = vconv;
289 }
290 return true;
291 }
292
293 static PyObject *cast(const type &src, return_value_policy policy, PyObject *parent) {
294 PyObject *dict = PyDict_New();
295 for (auto const &kv: src) {
296 PyObject *key = key_conv::cast(kv.first, policy, parent);
297 PyObject *value = value_conv::cast(kv.second, policy, parent);
298 if (!key || !value || PyDict_SetItem(dict, key, value) < 0) {
299 Py_XDECREF(key);
300 Py_XDECREF(value);
301 Py_DECREF(dict);
302 return nullptr;
303 }
304 Py_DECREF(key);
305 Py_DECREF(value);
306 }
307 return dict;
308 }
309 TYPE_CASTER(type, "dict<" + key_conv::name() + ", " + value_conv::name() + ">");
310};
311
312template <typename T1, typename T2> class type_caster<std::pair<T1, T2>> {
313 typedef std::pair<T1, T2> type;
314public:
315 bool load(PyObject *src, bool convert) {
316 if (!PyTuple_Check(src) || PyTuple_Size(src) != 2)
317 return false;
318 if (!first.load(PyTuple_GetItem(src, 0), convert))
319 return false;
320 return second.load(PyTuple_GetItem(src, 1), convert);
321 }
322
323 static PyObject *cast(const type &src, return_value_policy policy, PyObject *parent) {
324 PyObject *o1 = type_caster<typename mpl::normalize_type<T1>::type>::cast(src.first, policy, parent);
325 PyObject *o2 = type_caster<typename mpl::normalize_type<T2>::type>::cast(src.second, policy, parent);
326 if (!o1 || !o2) {
327 Py_XDECREF(o1);
328 Py_XDECREF(o2);
329 return nullptr;
330 }
331 PyObject *tuple = PyTuple_New(2);
332 PyTuple_SetItem(tuple, 0, o1);
333 PyTuple_SetItem(tuple, 1, o2);
334 return tuple;
335 }
336
337 static std::string name() {
338 return "(" + type_caster<T1>::name() + ", " + type_caster<T2>::name() + ")";
339 }
340
341 operator type() {
342 return type(first, second);
343 }
344protected:
345 type_caster<typename mpl::normalize_type<T1>::type> first;
346 type_caster<typename mpl::normalize_type<T2>::type> second;
347};
348
349template <typename ... Tuple> class type_caster<std::tuple<Tuple...>> {
350 typedef std::tuple<Tuple...> type;
351public:
352 enum { size = sizeof...(Tuple) };
353
354 bool load(PyObject *src, bool convert) {
355 return load(src, convert, typename mpl::make_index_sequence<sizeof...(Tuple)>::type());
356 }
357
358 static PyObject *cast(const type &src, return_value_policy policy, PyObject *parent) {
359 return cast(src, policy, parent, typename mpl::make_index_sequence<size>::type());
360 }
361
362 static std::string name() {
363 std::array<std::string, size> names {{
364 type_caster<typename mpl::normalize_type<Tuple>::type>::name()...
365 }};
366 std::string result("(");
367 int counter = 0;
368 for (auto const &name : names) {
369 result += name;
370 if (++counter < size)
371 result += ", ";
372 }
373 result += ")";
374 return result;
375 }
376
377 operator type() {
378 return cast(typename mpl::make_index_sequence<sizeof...(Tuple)>::type());
379 }
380protected:
381 template <size_t ... Index> type cast(mpl::index_sequence<Index...>) {
382 return type((Tuple) std::get<Index>(value)...);
383 }
384
385 template <size_t ... Indices> bool load(PyObject *src, bool convert, mpl::index_sequence<Indices...>) {
386 if (!PyTuple_Check(src))
387 return false;
388 if (PyTuple_Size(src) != size)
389 return false;
390 std::array<bool, size> results {{
391 std::get<Indices>(value).load(PyTuple_GetItem(src, Indices), convert)...
392 }};
393 for (bool r : results)
394 if (!r)
395 return false;
396 return true;
397 }
398
399 /* Implementation: Convert a C++ tuple into a Python tuple */
400 template <size_t ... Indices> static PyObject *cast(const type &src, return_value_policy policy, PyObject *parent, mpl::index_sequence<Indices...>) {
401 std::array<PyObject *, size> results {{
402 type_caster<typename mpl::normalize_type<Tuple>::type>::cast(std::get<Indices>(src), policy, parent)...
403 }};
404 bool success = true;
405 for (auto result : results)
406 if (result == nullptr)
407 success = false;
408 if (success) {
409 PyObject *tuple = PyTuple_New(size);
410 int counter = 0;
411 for (auto result : results)
412 PyTuple_SetItem(tuple, counter++, result);
413 return tuple;
414 } else {
415 for (auto result : results) {
416 Py_XDECREF(result);
417 }
418 return nullptr;
419 }
420 }
421
422protected:
423 std::tuple<type_caster<typename mpl::normalize_type<Tuple>::type>...> value;
424};
425
426/// Type caster for holder types like std::shared_ptr, etc.
427template <typename type, typename holder_type> class type_caster_holder : public type_caster<type> {
428public:
429 typedef type_caster<type> parent;
430 bool load(PyObject *src, bool convert) {
431 if (!parent::load(src, convert))
432 return false;
433 holder = holder_type(parent::value);
434 return true;
435 }
436 explicit operator type*() { return this->value; }
437 explicit operator type&() { return *(this->value); }
438 explicit operator holder_type&() { return holder; }
439 explicit operator holder_type*() { return &holder; }
440protected:
441 holder_type holder;
442};
443
444template <> class type_caster<handle> {
445public:
446 bool load(PyObject *src) {
447 value = handle(src);
448 return true;
449 }
450 static PyObject *cast(const handle &src, return_value_policy /* policy */, PyObject * /* parent */) {
451 src.inc_ref();
452 return (PyObject *) src.ptr();
453 }
454 TYPE_CASTER(handle, "handle");
455};
456
457#define TYPE_CASTER_PYTYPE(name) \
458 template <> class type_caster<name> { \
459 public: \
460 bool load(PyObject *src, bool) { value = name(src, true); return true; } \
461 static PyObject *cast(const name &src, return_value_policy /* policy */, PyObject * /* parent */) { \
462 src.inc_ref(); return (PyObject *) src.ptr(); \
463 } \
464 TYPE_CASTER(name, #name); \
465 };
466
467TYPE_CASTER_PYTYPE(object)
468TYPE_CASTER_PYTYPE(buffer)
469TYPE_CASTER_PYTYPE(capsule)
470TYPE_CASTER_PYTYPE(dict)
471TYPE_CASTER_PYTYPE(float_)
472TYPE_CASTER_PYTYPE(int_)
473TYPE_CASTER_PYTYPE(list)
474TYPE_CASTER_PYTYPE(slice)
475TYPE_CASTER_PYTYPE(tuple)
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200476TYPE_CASTER_PYTYPE(function)
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200477
478#undef TYPE_CASTER
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200479#undef TYPE_CASTER_PYTYPE
Wenzel Jakobbd4a5292015-07-11 17:41:48 +0200480#undef TYPE_CASTER_NUMBER
Wenzel Jakob38bd7112015-07-05 20:05:44 +0200481
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)