You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1604 lines
64 KiB

8 years ago
  1. /*
  2. pybind11/cast.h: Partial template specializations to cast between
  3. C++ and Python types
  4. Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
  5. All rights reserved. Use of this source code is governed by a
  6. BSD-style license that can be found in the LICENSE file.
  7. */
  8. #pragma once
  9. #include "pytypes.h"
  10. #include "typeid.h"
  11. #include "descr.h"
  12. #include <array>
  13. #include <limits>
  14. NAMESPACE_BEGIN(pybind11)
  15. NAMESPACE_BEGIN(detail)
  16. inline PyTypeObject *make_static_property_type();
  17. inline PyTypeObject *make_default_metaclass();
  18. /// Additional type information which does not fit into the PyTypeObject
  19. struct type_info {
  20. PyTypeObject *type;
  21. size_t type_size;
  22. void *(*operator_new)(size_t);
  23. void (*init_holder)(PyObject *, const void *);
  24. void (*dealloc)(PyObject *);
  25. std::vector<PyObject *(*)(PyObject *, PyTypeObject *)> implicit_conversions;
  26. std::vector<std::pair<const std::type_info *, void *(*)(void *)>> implicit_casts;
  27. std::vector<bool (*)(PyObject *, void *&)> *direct_conversions;
  28. buffer_info *(*get_buffer)(PyObject *, void *) = nullptr;
  29. void *get_buffer_data = nullptr;
  30. /** A simple type never occurs as a (direct or indirect) parent
  31. * of a class that makes use of multiple inheritance */
  32. bool simple_type = true;
  33. /* for base vs derived holder_type checks */
  34. bool default_holder = true;
  35. };
  36. PYBIND11_NOINLINE inline internals &get_internals() {
  37. static internals *internals_ptr = nullptr;
  38. if (internals_ptr)
  39. return *internals_ptr;
  40. handle builtins(PyEval_GetBuiltins());
  41. const char *id = PYBIND11_INTERNALS_ID;
  42. if (builtins.contains(id) && isinstance<capsule>(builtins[id])) {
  43. internals_ptr = capsule(builtins[id]);
  44. } else {
  45. internals_ptr = new internals();
  46. #if defined(WITH_THREAD)
  47. PyEval_InitThreads();
  48. PyThreadState *tstate = PyThreadState_Get();
  49. internals_ptr->tstate = PyThread_create_key();
  50. PyThread_set_key_value(internals_ptr->tstate, tstate);
  51. internals_ptr->istate = tstate->interp;
  52. #endif
  53. builtins[id] = capsule(internals_ptr);
  54. internals_ptr->registered_exception_translators.push_front(
  55. [](std::exception_ptr p) -> void {
  56. try {
  57. if (p) std::rethrow_exception(p);
  58. } catch (error_already_set &e) { e.restore(); return;
  59. } catch (const builtin_exception &e) { e.set_error(); return;
  60. } catch (const std::bad_alloc &e) { PyErr_SetString(PyExc_MemoryError, e.what()); return;
  61. } catch (const std::domain_error &e) { PyErr_SetString(PyExc_ValueError, e.what()); return;
  62. } catch (const std::invalid_argument &e) { PyErr_SetString(PyExc_ValueError, e.what()); return;
  63. } catch (const std::length_error &e) { PyErr_SetString(PyExc_ValueError, e.what()); return;
  64. } catch (const std::out_of_range &e) { PyErr_SetString(PyExc_IndexError, e.what()); return;
  65. } catch (const std::range_error &e) { PyErr_SetString(PyExc_ValueError, e.what()); return;
  66. } catch (const std::exception &e) { PyErr_SetString(PyExc_RuntimeError, e.what()); return;
  67. } catch (...) {
  68. PyErr_SetString(PyExc_RuntimeError, "Caught an unknown exception!");
  69. return;
  70. }
  71. }
  72. );
  73. internals_ptr->static_property_type = make_static_property_type();
  74. internals_ptr->default_metaclass = make_default_metaclass();
  75. }
  76. return *internals_ptr;
  77. }
  78. PYBIND11_NOINLINE inline detail::type_info* get_type_info(PyTypeObject *type) {
  79. auto const &type_dict = get_internals().registered_types_py;
  80. do {
  81. auto it = type_dict.find(type);
  82. if (it != type_dict.end())
  83. return (detail::type_info *) it->second;
  84. type = type->tp_base;
  85. if (!type)
  86. return nullptr;
  87. } while (true);
  88. }
  89. PYBIND11_NOINLINE inline detail::type_info *get_type_info(const std::type_info &tp,
  90. bool throw_if_missing = false) {
  91. auto &types = get_internals().registered_types_cpp;
  92. auto it = types.find(std::type_index(tp));
  93. if (it != types.end())
  94. return (detail::type_info *) it->second;
  95. if (throw_if_missing) {
  96. std::string tname = tp.name();
  97. detail::clean_type_id(tname);
  98. pybind11_fail("pybind11::detail::get_type_info: unable to find type info for \"" + tname + "\"");
  99. }
  100. return nullptr;
  101. }
  102. PYBIND11_NOINLINE inline handle get_type_handle(const std::type_info &tp, bool throw_if_missing) {
  103. detail::type_info *type_info = get_type_info(tp, throw_if_missing);
  104. return handle(type_info ? ((PyObject *) type_info->type) : nullptr);
  105. }
  106. PYBIND11_NOINLINE inline bool isinstance_generic(handle obj, const std::type_info &tp) {
  107. handle type = detail::get_type_handle(tp, false);
  108. if (!type)
  109. return false;
  110. return isinstance(obj, type);
  111. }
  112. PYBIND11_NOINLINE inline std::string error_string() {
  113. if (!PyErr_Occurred()) {
  114. PyErr_SetString(PyExc_RuntimeError, "Unknown internal error occurred");
  115. return "Unknown internal error occurred";
  116. }
  117. error_scope scope; // Preserve error state
  118. std::string errorString;
  119. if (scope.type) {
  120. errorString += handle(scope.type).attr("__name__").cast<std::string>();
  121. errorString += ": ";
  122. }
  123. if (scope.value)
  124. errorString += (std::string) str(scope.value);
  125. PyErr_NormalizeException(&scope.type, &scope.value, &scope.trace);
  126. #if PY_MAJOR_VERSION >= 3
  127. if (scope.trace != nullptr)
  128. PyException_SetTraceback(scope.value, scope.trace);
  129. #endif
  130. #if !defined(PYPY_VERSION)
  131. if (scope.trace) {
  132. PyTracebackObject *trace = (PyTracebackObject *) scope.trace;
  133. /* Get the deepest trace possible */
  134. while (trace->tb_next)
  135. trace = trace->tb_next;
  136. PyFrameObject *frame = trace->tb_frame;
  137. errorString += "\n\nAt:\n";
  138. while (frame) {
  139. int lineno = PyFrame_GetLineNumber(frame);
  140. errorString +=
  141. " " + handle(frame->f_code->co_filename).cast<std::string>() +
  142. "(" + std::to_string(lineno) + "): " +
  143. handle(frame->f_code->co_name).cast<std::string>() + "\n";
  144. frame = frame->f_back;
  145. }
  146. trace = trace->tb_next;
  147. }
  148. #endif
  149. return errorString;
  150. }
  151. PYBIND11_NOINLINE inline handle get_object_handle(const void *ptr, const detail::type_info *type ) {
  152. auto &instances = get_internals().registered_instances;
  153. auto range = instances.equal_range(ptr);
  154. for (auto it = range.first; it != range.second; ++it) {
  155. auto instance_type = detail::get_type_info(Py_TYPE(it->second));
  156. if (instance_type && instance_type == type)
  157. return handle((PyObject *) it->second);
  158. }
  159. return handle();
  160. }
  161. inline PyThreadState *get_thread_state_unchecked() {
  162. #if defined(PYPY_VERSION)
  163. return PyThreadState_GET();
  164. #elif PY_VERSION_HEX < 0x03000000
  165. return _PyThreadState_Current;
  166. #elif PY_VERSION_HEX < 0x03050000
  167. return (PyThreadState*) _Py_atomic_load_relaxed(&_PyThreadState_Current);
  168. #elif PY_VERSION_HEX < 0x03050200
  169. return (PyThreadState*) _PyThreadState_Current.value;
  170. #else
  171. return _PyThreadState_UncheckedGet();
  172. #endif
  173. }
  174. // Forward declaration
  175. inline void keep_alive_impl(handle nurse, handle patient);
  176. class type_caster_generic {
  177. public:
  178. PYBIND11_NOINLINE type_caster_generic(const std::type_info &type_info)
  179. : typeinfo(get_type_info(type_info)) { }
  180. PYBIND11_NOINLINE bool load(handle src, bool convert) {
  181. if (!src)
  182. return false;
  183. return load(src, convert, Py_TYPE(src.ptr()));
  184. }
  185. bool load(handle src, bool convert, PyTypeObject *tobj) {
  186. if (!src || !typeinfo)
  187. return false;
  188. if (src.is_none()) {
  189. value = nullptr;
  190. return true;
  191. }
  192. if (typeinfo->simple_type) { /* Case 1: no multiple inheritance etc. involved */
  193. /* Check if we can safely perform a reinterpret-style cast */
  194. if (PyType_IsSubtype(tobj, typeinfo->type)) {
  195. value = reinterpret_cast<instance<void> *>(src.ptr())->value;
  196. return true;
  197. }
  198. } else { /* Case 2: multiple inheritance */
  199. /* Check if we can safely perform a reinterpret-style cast */
  200. if (tobj == typeinfo->type) {
  201. value = reinterpret_cast<instance<void> *>(src.ptr())->value;
  202. return true;
  203. }
  204. /* If this is a python class, also check the parents recursively */
  205. auto const &type_dict = get_internals().registered_types_py;
  206. bool new_style_class = PyType_Check((PyObject *) tobj);
  207. if (type_dict.find(tobj) == type_dict.end() && new_style_class && tobj->tp_bases) {
  208. auto parents = reinterpret_borrow<tuple>(tobj->tp_bases);
  209. for (handle parent : parents) {
  210. bool result = load(src, convert, (PyTypeObject *) parent.ptr());
  211. if (result)
  212. return true;
  213. }
  214. }
  215. /* Try implicit casts */
  216. for (auto &cast : typeinfo->implicit_casts) {
  217. type_caster_generic sub_caster(*cast.first);
  218. if (sub_caster.load(src, convert)) {
  219. value = cast.second(sub_caster.value);
  220. return true;
  221. }
  222. }
  223. }
  224. /* Perform an implicit conversion */
  225. if (convert) {
  226. for (auto &converter : typeinfo->implicit_conversions) {
  227. temp = reinterpret_steal<object>(converter(src.ptr(), typeinfo->type));
  228. if (load(temp, false))
  229. return true;
  230. }
  231. for (auto &converter : *typeinfo->direct_conversions) {
  232. if (converter(src.ptr(), value))
  233. return true;
  234. }
  235. }
  236. return false;
  237. }
  238. PYBIND11_NOINLINE static handle cast(const void *_src, return_value_policy policy, handle parent,
  239. const std::type_info *type_info,
  240. const std::type_info *type_info_backup,
  241. void *(*copy_constructor)(const void *),
  242. void *(*move_constructor)(const void *),
  243. const void *existing_holder = nullptr) {
  244. void *src = const_cast<void *>(_src);
  245. if (src == nullptr)
  246. return none().inc_ref();
  247. auto &internals = get_internals();
  248. auto it = internals.registered_types_cpp.find(std::type_index(*type_info));
  249. if (it == internals.registered_types_cpp.end()) {
  250. type_info = type_info_backup;
  251. it = internals.registered_types_cpp.find(std::type_index(*type_info));
  252. }
  253. if (it == internals.registered_types_cpp.end()) {
  254. std::string tname = type_info->name();
  255. detail::clean_type_id(tname);
  256. std::string msg = "Unregistered type : " + tname;
  257. PyErr_SetString(PyExc_TypeError, msg.c_str());
  258. return handle();
  259. }
  260. auto tinfo = (const detail::type_info *) it->second;
  261. auto it_instances = internals.registered_instances.equal_range(src);
  262. for (auto it_i = it_instances.first; it_i != it_instances.second; ++it_i) {
  263. auto instance_type = detail::get_type_info(Py_TYPE(it_i->second));
  264. if (instance_type && instance_type == tinfo)
  265. return handle((PyObject *) it_i->second).inc_ref();
  266. }
  267. auto inst = reinterpret_steal<object>(PyType_GenericAlloc(tinfo->type, 0));
  268. auto wrapper = (instance<void> *) inst.ptr();
  269. wrapper->value = nullptr;
  270. wrapper->owned = false;
  271. switch (policy) {
  272. case return_value_policy::automatic:
  273. case return_value_policy::take_ownership:
  274. wrapper->value = src;
  275. wrapper->owned = true;
  276. break;
  277. case return_value_policy::automatic_reference:
  278. case return_value_policy::reference:
  279. wrapper->value = src;
  280. wrapper->owned = false;
  281. break;
  282. case return_value_policy::copy:
  283. if (copy_constructor)
  284. wrapper->value = copy_constructor(src);
  285. else
  286. throw cast_error("return_value_policy = copy, but the "
  287. "object is non-copyable!");
  288. wrapper->owned = true;
  289. break;
  290. case return_value_policy::move:
  291. if (move_constructor)
  292. wrapper->value = move_constructor(src);
  293. else if (copy_constructor)
  294. wrapper->value = copy_constructor(src);
  295. else
  296. throw cast_error("return_value_policy = move, but the "
  297. "object is neither movable nor copyable!");
  298. wrapper->owned = true;
  299. break;
  300. case return_value_policy::reference_internal:
  301. wrapper->value = src;
  302. wrapper->owned = false;
  303. detail::keep_alive_impl(inst, parent);
  304. break;
  305. default:
  306. throw cast_error("unhandled return_value_policy: should not happen!");
  307. }
  308. tinfo->init_holder(inst.ptr(), existing_holder);
  309. internals.registered_instances.emplace(wrapper->value, inst.ptr());
  310. return inst.release();
  311. }
  312. protected:
  313. const type_info *typeinfo = nullptr;
  314. void *value = nullptr;
  315. object temp;
  316. };
  317. /* Determine suitable casting operator */
  318. template <typename T>
  319. using cast_op_type = typename std::conditional<std::is_pointer<typename std::remove_reference<T>::type>::value,
  320. typename std::add_pointer<intrinsic_t<T>>::type,
  321. typename std::add_lvalue_reference<intrinsic_t<T>>::type>::type;
  322. // std::is_copy_constructible isn't quite enough: it lets std::vector<T> (and similar) through when
  323. // T is non-copyable, but code containing such a copy constructor fails to actually compile.
  324. template <typename T, typename SFINAE = void> struct is_copy_constructible : std::is_copy_constructible<T> {};
  325. // Specialization for types that appear to be copy constructible but also look like stl containers
  326. // (we specifically check for: has `value_type` and `reference` with `reference = value_type&`): if
  327. // so, copy constructability depends on whether the value_type is copy constructible.
  328. template <typename Container> struct is_copy_constructible<Container, enable_if_t<
  329. std::is_copy_constructible<Container>::value &&
  330. std::is_same<typename Container::value_type &, typename Container::reference>::value
  331. >> : std::is_copy_constructible<typename Container::value_type> {};
  332. /// Generic type caster for objects stored on the heap
  333. template <typename type> class type_caster_base : public type_caster_generic {
  334. using itype = intrinsic_t<type>;
  335. public:
  336. static PYBIND11_DESCR name() { return type_descr(_<type>()); }
  337. type_caster_base() : type_caster_base(typeid(type)) { }
  338. explicit type_caster_base(const std::type_info &info) : type_caster_generic(info) { }
  339. static handle cast(const itype &src, return_value_policy policy, handle parent) {
  340. if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference)
  341. policy = return_value_policy::copy;
  342. return cast(&src, policy, parent);
  343. }
  344. static handle cast(itype &&src, return_value_policy, handle parent) {
  345. return cast(&src, return_value_policy::move, parent);
  346. }
  347. static handle cast(const itype *src, return_value_policy policy, handle parent) {
  348. return type_caster_generic::cast(
  349. src, policy, parent, src ? &typeid(*src) : nullptr, &typeid(type),
  350. make_copy_constructor(src), make_move_constructor(src));
  351. }
  352. static handle cast_holder(const itype *src, const void *holder) {
  353. return type_caster_generic::cast(
  354. src, return_value_policy::take_ownership, {},
  355. src ? &typeid(*src) : nullptr, &typeid(type),
  356. nullptr, nullptr, holder);
  357. }
  358. template <typename T> using cast_op_type = pybind11::detail::cast_op_type<T>;
  359. operator itype*() { return (type *) value; }
  360. operator itype&() { if (!value) throw reference_cast_error(); return *((itype *) value); }
  361. protected:
  362. typedef void *(*Constructor)(const void *stream);
  363. #if !defined(_MSC_VER)
  364. /* Only enabled when the types are {copy,move}-constructible *and* when the type
  365. does not have a private operator new implementaton. */
  366. template <typename T = type, typename = enable_if_t<is_copy_constructible<T>::value>> static auto make_copy_constructor(const T *value) -> decltype(new T(*value), Constructor(nullptr)) {
  367. return [](const void *arg) -> void * { return new T(*((const T *) arg)); }; }
  368. template <typename T = type> static auto make_move_constructor(const T *value) -> decltype(new T(std::move(*((T *) value))), Constructor(nullptr)) {
  369. return [](const void *arg) -> void * { return (void *) new T(std::move(*const_cast<T *>(reinterpret_cast<const T *>(arg)))); }; }
  370. #else
  371. /* Visual Studio 2015's SFINAE implementation doesn't yet handle the above robustly in all situations.
  372. Use a workaround that only tests for constructibility for now. */
  373. template <typename T = type, typename = enable_if_t<is_copy_constructible<T>::value>>
  374. static Constructor make_copy_constructor(const T *value) {
  375. return [](const void *arg) -> void * { return new T(*((const T *)arg)); }; }
  376. template <typename T = type, typename = enable_if_t<std::is_move_constructible<T>::value>>
  377. static Constructor make_move_constructor(const T *value) {
  378. return [](const void *arg) -> void * { return (void *) new T(std::move(*((T *)arg))); }; }
  379. #endif
  380. static Constructor make_copy_constructor(...) { return nullptr; }
  381. static Constructor make_move_constructor(...) { return nullptr; }
  382. };
  383. template <typename type, typename SFINAE = void> class type_caster : public type_caster_base<type> { };
  384. template <typename type> using make_caster = type_caster<intrinsic_t<type>>;
  385. // Shortcut for calling a caster's `cast_op_type` cast operator for casting a type_caster to a T
  386. template <typename T> typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) {
  387. return caster.operator typename make_caster<T>::template cast_op_type<T>();
  388. }
  389. template <typename T> typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &&caster) {
  390. return cast_op<T>(caster);
  391. }
  392. template <typename type> class type_caster<std::reference_wrapper<type>> : public type_caster_base<type> {
  393. public:
  394. static handle cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) {
  395. return type_caster_base<type>::cast(&src.get(), policy, parent);
  396. }
  397. template <typename T> using cast_op_type = std::reference_wrapper<type>;
  398. operator std::reference_wrapper<type>() { return std::ref(*((type *) this->value)); }
  399. };
  400. #define PYBIND11_TYPE_CASTER(type, py_name) \
  401. protected: \
  402. type value; \
  403. public: \
  404. static PYBIND11_DESCR name() { return type_descr(py_name); } \
  405. static handle cast(const type *src, return_value_policy policy, handle parent) { \
  406. if (!src) return none().release(); \
  407. return cast(*src, policy, parent); \
  408. } \
  409. operator type*() { return &value; } \
  410. operator type&() { return value; } \
  411. template <typename _T> using cast_op_type = pybind11::detail::cast_op_type<_T>
  412. template <typename CharT> using is_std_char_type = any_of<
  413. std::is_same<CharT, char>, /* std::string */
  414. std::is_same<CharT, char16_t>, /* std::u16string */
  415. std::is_same<CharT, char32_t>, /* std::u32string */
  416. std::is_same<CharT, wchar_t> /* std::wstring */
  417. >;
  418. template <typename T>
  419. struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_type<T>::value>> {
  420. using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>;
  421. using _py_type_1 = conditional_t<std::is_signed<T>::value, _py_type_0, typename std::make_unsigned<_py_type_0>::type>;
  422. using py_type = conditional_t<std::is_floating_point<T>::value, double, _py_type_1>;
  423. public:
  424. bool load(handle src, bool convert) {
  425. py_type py_value;
  426. if (!src)
  427. return false;
  428. if (std::is_floating_point<T>::value) {
  429. if (convert || PyFloat_Check(src.ptr()))
  430. py_value = (py_type) PyFloat_AsDouble(src.ptr());
  431. else
  432. return false;
  433. } else if (sizeof(T) <= sizeof(long)) {
  434. if (PyFloat_Check(src.ptr()))
  435. return false;
  436. if (std::is_signed<T>::value)
  437. py_value = (py_type) PyLong_AsLong(src.ptr());
  438. else
  439. py_value = (py_type) PyLong_AsUnsignedLong(src.ptr());
  440. } else {
  441. if (PyFloat_Check(src.ptr()))
  442. return false;
  443. if (std::is_signed<T>::value)
  444. py_value = (py_type) PYBIND11_LONG_AS_LONGLONG(src.ptr());
  445. else
  446. py_value = (py_type) PYBIND11_LONG_AS_UNSIGNED_LONGLONG(src.ptr());
  447. }
  448. if ((py_value == (py_type) -1 && PyErr_Occurred()) ||
  449. (std::is_integral<T>::value && sizeof(py_type) != sizeof(T) &&
  450. (py_value < (py_type) std::numeric_limits<T>::min() ||
  451. py_value > (py_type) std::numeric_limits<T>::max()))) {
  452. #if PY_VERSION_HEX < 0x03000000
  453. bool type_error = PyErr_ExceptionMatches(PyExc_SystemError);
  454. #else
  455. bool type_error = PyErr_ExceptionMatches(PyExc_TypeError);
  456. #endif
  457. PyErr_Clear();
  458. if (type_error && convert && PyNumber_Check(src.ptr())) {
  459. auto tmp = reinterpret_borrow<object>(std::is_floating_point<T>::value
  460. ? PyNumber_Float(src.ptr())
  461. : PyNumber_Long(src.ptr()));
  462. PyErr_Clear();
  463. return load(tmp, false);
  464. }
  465. return false;
  466. }
  467. value = (T) py_value;
  468. return true;
  469. }
  470. static handle cast(T src, return_value_policy /* policy */, handle /* parent */) {
  471. if (std::is_floating_point<T>::value) {
  472. return PyFloat_FromDouble((double) src);
  473. } else if (sizeof(T) <= sizeof(long)) {
  474. if (std::is_signed<T>::value)
  475. return PyLong_FromLong((long) src);
  476. else
  477. return PyLong_FromUnsignedLong((unsigned long) src);
  478. } else {
  479. if (std::is_signed<T>::value)
  480. return PyLong_FromLongLong((long long) src);
  481. else
  482. return PyLong_FromUnsignedLongLong((unsigned long long) src);
  483. }
  484. }
  485. PYBIND11_TYPE_CASTER(T, _<std::is_integral<T>::value>("int", "float"));
  486. };
  487. template<typename T> struct void_caster {
  488. public:
  489. bool load(handle, bool) { return false; }
  490. static handle cast(T, return_value_policy /* policy */, handle /* parent */) {
  491. return none().inc_ref();
  492. }
  493. PYBIND11_TYPE_CASTER(T, _("None"));
  494. };
  495. template <> class type_caster<void_type> : public void_caster<void_type> {};
  496. template <> class type_caster<void> : public type_caster<void_type> {
  497. public:
  498. using type_caster<void_type>::cast;
  499. bool load(handle h, bool) {
  500. if (!h) {
  501. return false;
  502. } else if (h.is_none()) {
  503. value = nullptr;
  504. return true;
  505. }
  506. /* Check if this is a capsule */
  507. if (isinstance<capsule>(h)) {
  508. value = reinterpret_borrow<capsule>(h);
  509. return true;
  510. }
  511. /* Check if this is a C++ type */
  512. if (get_type_info((PyTypeObject *) h.get_type().ptr())) {
  513. value = ((instance<void> *) h.ptr())->value;
  514. return true;
  515. }
  516. /* Fail */
  517. return false;
  518. }
  519. static handle cast(const void *ptr, return_value_policy /* policy */, handle /* parent */) {
  520. if (ptr)
  521. return capsule(ptr).release();
  522. else
  523. return none().inc_ref();
  524. }
  525. template <typename T> using cast_op_type = void*&;
  526. operator void *&() { return value; }
  527. static PYBIND11_DESCR name() { return type_descr(_("capsule")); }
  528. private:
  529. void *value = nullptr;
  530. };
  531. template <> class type_caster<std::nullptr_t> : public type_caster<void_type> { };
  532. template <> class type_caster<bool> {
  533. public:
  534. bool load(handle src, bool) {
  535. if (!src) return false;
  536. else if (src.ptr() == Py_True) { value = true; return true; }
  537. else if (src.ptr() == Py_False) { value = false; return true; }
  538. else return false;
  539. }
  540. static handle cast(bool src, return_value_policy /* policy */, handle /* parent */) {
  541. return handle(src ? Py_True : Py_False).inc_ref();
  542. }
  543. PYBIND11_TYPE_CASTER(bool, _("bool"));
  544. };
  545. // Helper class for UTF-{8,16,32} C++ stl strings:
  546. template <typename CharT, class Traits, class Allocator>
  547. struct type_caster<std::basic_string<CharT, Traits, Allocator>, enable_if_t<is_std_char_type<CharT>::value>> {
  548. // Simplify life by being able to assume standard char sizes (the standard only guarantees
  549. // minimums), but Python requires exact sizes
  550. static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1, "Unsupported char size != 1");
  551. static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2, "Unsupported char16_t size != 2");
  552. static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4, "Unsupported char32_t size != 4");
  553. // wchar_t can be either 16 bits (Windows) or 32 (everywhere else)
  554. static_assert(!std::is_same<CharT, wchar_t>::value || sizeof(CharT) == 2 || sizeof(CharT) == 4,
  555. "Unsupported wchar_t size != 2/4");
  556. static constexpr size_t UTF_N = 8 * sizeof(CharT);
  557. using StringType = std::basic_string<CharT, Traits, Allocator>;
  558. bool load(handle src, bool) {
  559. #if PY_MAJOR_VERSION < 3
  560. object temp;
  561. #endif
  562. handle load_src = src;
  563. if (!src) {
  564. return false;
  565. } else if (!PyUnicode_Check(load_src.ptr())) {
  566. #if PY_MAJOR_VERSION >= 3
  567. return false;
  568. // The below is a guaranteed failure in Python 3 when PyUnicode_Check returns false
  569. #else
  570. if (!PYBIND11_BYTES_CHECK(load_src.ptr()))
  571. return false;
  572. temp = reinterpret_steal<object>(PyUnicode_FromObject(load_src.ptr()));
  573. if (!temp) { PyErr_Clear(); return false; }
  574. load_src = temp;
  575. #endif
  576. }
  577. object utfNbytes = reinterpret_steal<object>(PyUnicode_AsEncodedString(
  578. load_src.ptr(), UTF_N == 8 ? "utf-8" : UTF_N == 16 ? "utf-16" : "utf-32", nullptr));
  579. if (!utfNbytes) { PyErr_Clear(); return false; }
  580. const CharT *buffer = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
  581. size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.ptr()) / sizeof(CharT);
  582. if (UTF_N > 8) { buffer++; length--; } // Skip BOM for UTF-16/32
  583. value = StringType(buffer, length);
  584. return true;
  585. }
  586. static handle cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) {
  587. const char *buffer = reinterpret_cast<const char *>(src.c_str());
  588. ssize_t nbytes = ssize_t(src.size() * sizeof(CharT));
  589. handle s = decode_utfN(buffer, nbytes);
  590. if (!s) throw error_already_set();
  591. return s;
  592. }
  593. PYBIND11_TYPE_CASTER(StringType, _(PYBIND11_STRING_NAME));
  594. private:
  595. static handle decode_utfN(const char *buffer, ssize_t nbytes) {
  596. #if !defined(PYPY_VERSION)
  597. return
  598. UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr) :
  599. UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr) :
  600. PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);
  601. #else
  602. // PyPy seems to have multiple problems related to PyUnicode_UTF*: the UTF8 version
  603. // sometimes segfaults for unknown reasons, while the UTF16 and 32 versions require a
  604. // non-const char * arguments, which is also a nuissance, so bypass the whole thing by just
  605. // passing the encoding as a string value, which works properly:
  606. return PyUnicode_Decode(buffer, nbytes, UTF_N == 8 ? "utf-8" : UTF_N == 16 ? "utf-16" : "utf-32", nullptr);
  607. #endif
  608. }
  609. };
  610. // Type caster for C-style strings. We basically use a std::string type caster, but also add the
  611. // ability to use None as a nullptr char* (which the string caster doesn't allow).
  612. template <typename CharT> struct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> {
  613. using StringType = std::basic_string<CharT>;
  614. using StringCaster = type_caster<StringType>;
  615. StringCaster str_caster;
  616. bool none = false;
  617. public:
  618. bool load(handle src, bool convert) {
  619. if (!src) return false;
  620. if (src.is_none()) {
  621. // Defer accepting None to other overloads (if we aren't in convert mode):
  622. if (!convert) return false;
  623. none = true;
  624. return true;
  625. }
  626. return str_caster.load(src, convert);
  627. }
  628. static handle cast(const CharT *src, return_value_policy policy, handle parent) {
  629. if (src == nullptr) return pybind11::none().inc_ref();
  630. return StringCaster::cast(StringType(src), policy, parent);
  631. }
  632. static handle cast(CharT src, return_value_policy policy, handle parent) {
  633. if (std::is_same<char, CharT>::value) {
  634. handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr);
  635. if (!s) throw error_already_set();
  636. return s;
  637. }
  638. return StringCaster::cast(StringType(1, src), policy, parent);
  639. }
  640. operator CharT*() { return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str()); }
  641. operator CharT() {
  642. if (none)
  643. throw value_error("Cannot convert None to a character");
  644. auto &value = static_cast<StringType &>(str_caster);
  645. size_t str_len = value.size();
  646. if (str_len == 0)
  647. throw value_error("Cannot convert empty string to a character");
  648. // If we're in UTF-8 mode, we have two possible failures: one for a unicode character that
  649. // is too high, and one for multiple unicode characters (caught later), so we need to figure
  650. // out how long the first encoded character is in bytes to distinguish between these two
  651. // errors. We also allow want to allow unicode characters U+0080 through U+00FF, as those
  652. // can fit into a single char value.
  653. if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) {
  654. unsigned char v0 = static_cast<unsigned char>(value[0]);
  655. size_t char0_bytes = !(v0 & 0x80) ? 1 : // low bits only: 0-127
  656. (v0 & 0xE0) == 0xC0 ? 2 : // 0b110xxxxx - start of 2-byte sequence
  657. (v0 & 0xF0) == 0xE0 ? 3 : // 0b1110xxxx - start of 3-byte sequence
  658. 4; // 0b11110xxx - start of 4-byte sequence
  659. if (char0_bytes == str_len) {
  660. // If we have a 128-255 value, we can decode it into a single char:
  661. if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) { // 0x110000xx 0x10xxxxxx
  662. return static_cast<CharT>(((v0 & 3) << 6) + (static_cast<unsigned char>(value[1]) & 0x3F));
  663. }
  664. // Otherwise we have a single character, but it's > U+00FF
  665. throw value_error("Character code point not in range(0x100)");
  666. }
  667. }
  668. // UTF-16 is much easier: we can only have a surrogate pair for values above U+FFFF, thus a
  669. // surrogate pair with total length 2 instantly indicates a range error (but not a "your
  670. // string was too long" error).
  671. else if (StringCaster::UTF_N == 16 && str_len == 2) {
  672. char16_t v0 = static_cast<char16_t>(value[0]);
  673. if (v0 >= 0xD800 && v0 < 0xE000)
  674. throw value_error("Character code point not in range(0x10000)");
  675. }
  676. if (str_len != 1)
  677. throw value_error("Expected a character, but multi-character string found");
  678. return value[0];
  679. }
  680. static PYBIND11_DESCR name() { return type_descr(_(PYBIND11_STRING_NAME)); }
  681. template <typename _T> using cast_op_type = typename std::remove_reference<pybind11::detail::cast_op_type<_T>>::type;
  682. };
  683. template <typename T1, typename T2> class type_caster<std::pair<T1, T2>> {
  684. typedef std::pair<T1, T2> type;
  685. public:
  686. bool load(handle src, bool convert) {
  687. if (!isinstance<sequence>(src))
  688. return false;
  689. const auto seq = reinterpret_borrow<sequence>(src);
  690. if (seq.size() != 2)
  691. return false;
  692. return first.load(seq[0], convert) && second.load(seq[1], convert);
  693. }
  694. static handle cast(const type &src, return_value_policy policy, handle parent) {
  695. auto o1 = reinterpret_steal<object>(make_caster<T1>::cast(src.first, policy, parent));
  696. auto o2 = reinterpret_steal<object>(make_caster<T2>::cast(src.second, policy, parent));
  697. if (!o1 || !o2)
  698. return handle();
  699. tuple result(2);
  700. PyTuple_SET_ITEM(result.ptr(), 0, o1.release().ptr());
  701. PyTuple_SET_ITEM(result.ptr(), 1, o2.release().ptr());
  702. return result.release();
  703. }
  704. static PYBIND11_DESCR name() {
  705. return type_descr(
  706. _("Tuple[") + make_caster<T1>::name() + _(", ") + make_caster<T2>::name() + _("]")
  707. );
  708. }
  709. template <typename T> using cast_op_type = type;
  710. operator type() {
  711. return type(cast_op<T1>(first), cast_op<T2>(second));
  712. }
  713. protected:
  714. make_caster<T1> first;
  715. make_caster<T2> second;
  716. };
  717. template <typename... Tuple> class type_caster<std::tuple<Tuple...>> {
  718. using type = std::tuple<Tuple...>;
  719. using indices = make_index_sequence<sizeof...(Tuple)>;
  720. static constexpr auto size = sizeof...(Tuple);
  721. public:
  722. bool load(handle src, bool convert) {
  723. if (!isinstance<sequence>(src))
  724. return false;
  725. const auto seq = reinterpret_borrow<sequence>(src);
  726. if (seq.size() != size)
  727. return false;
  728. return load_impl(seq, convert, indices{});
  729. }
  730. static handle cast(const type &src, return_value_policy policy, handle parent) {
  731. return cast_impl(src, policy, parent, indices{});
  732. }
  733. static PYBIND11_DESCR name() {
  734. return type_descr(_("Tuple[") + detail::concat(make_caster<Tuple>::name()...) + _("]"));
  735. }
  736. template <typename T> using cast_op_type = type;
  737. operator type() { return implicit_cast(indices{}); }
  738. protected:
  739. template <size_t... Is>
  740. type implicit_cast(index_sequence<Is...>) { return type(cast_op<Tuple>(std::get<Is>(value))...); }
  741. static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; }
  742. template <size_t... Is>
  743. bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {
  744. for (bool r : {std::get<Is>(value).load(seq[Is], convert)...})
  745. if (!r)
  746. return false;
  747. return true;
  748. }
  749. static handle cast_impl(const type &, return_value_policy, handle,
  750. index_sequence<>) { return tuple().release(); }
  751. /* Implementation: Convert a C++ tuple into a Python tuple */
  752. template <size_t... Is>
  753. static handle cast_impl(const type &src, return_value_policy policy, handle parent, index_sequence<Is...>) {
  754. std::array<object, size> entries {{
  755. reinterpret_steal<object>(make_caster<Tuple>::cast(std::get<Is>(src), policy, parent))...
  756. }};
  757. for (const auto &entry: entries)
  758. if (!entry)
  759. return handle();
  760. tuple result(size);
  761. int counter = 0;
  762. for (auto & entry: entries)
  763. PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());
  764. return result.release();
  765. }
  766. std::tuple<make_caster<Tuple>...> value;
  767. };
  768. /// Helper class which abstracts away certain actions. Users can provide specializations for
  769. /// custom holders, but it's only necessary if the type has a non-standard interface.
  770. template <typename T>
  771. struct holder_helper {
  772. static auto get(const T &p) -> decltype(p.get()) { return p.get(); }
  773. };
  774. /// Type caster for holder types like std::shared_ptr, etc.
  775. template <typename type, typename holder_type>
  776. struct copyable_holder_caster : public type_caster_base<type> {
  777. public:
  778. using base = type_caster_base<type>;
  779. using base::base;
  780. using base::cast;
  781. using base::typeinfo;
  782. using base::value;
  783. using base::temp;
  784. PYBIND11_NOINLINE bool load(handle src, bool convert) {
  785. return load(src, convert, Py_TYPE(src.ptr()));
  786. }
  787. bool load(handle src, bool convert, PyTypeObject *tobj) {
  788. if (!src || !typeinfo)
  789. return false;
  790. if (src.is_none()) {
  791. value = nullptr;
  792. return true;
  793. }
  794. if (typeinfo->default_holder)
  795. throw cast_error("Unable to load a custom holder type from a default-holder instance");
  796. if (typeinfo->simple_type) { /* Case 1: no multiple inheritance etc. involved */
  797. /* Check if we can safely perform a reinterpret-style cast */
  798. if (PyType_IsSubtype(tobj, typeinfo->type))
  799. return load_value_and_holder(src);
  800. } else { /* Case 2: multiple inheritance */
  801. /* Check if we can safely perform a reinterpret-style cast */
  802. if (tobj == typeinfo->type)
  803. return load_value_and_holder(src);
  804. /* If this is a python class, also check the parents recursively */
  805. auto const &type_dict = get_internals().registered_types_py;
  806. bool new_style_class = PyType_Check((PyObject *) tobj);
  807. if (type_dict.find(tobj) == type_dict.end() && new_style_class && tobj->tp_bases) {
  808. auto parents = reinterpret_borrow<tuple>(tobj->tp_bases);
  809. for (handle parent : parents) {
  810. bool result = load(src, convert, (PyTypeObject *) parent.ptr());
  811. if (result)
  812. return true;
  813. }
  814. }
  815. if (try_implicit_casts(src, convert))
  816. return true;
  817. }
  818. if (convert) {
  819. for (auto &converter : typeinfo->implicit_conversions) {
  820. temp = reinterpret_steal<object>(converter(src.ptr(), typeinfo->type));
  821. if (load(temp, false))
  822. return true;
  823. }
  824. }
  825. return false;
  826. }
  827. bool load_value_and_holder(handle src) {
  828. auto inst = (instance<type, holder_type> *) src.ptr();
  829. value = (void *) inst->value;
  830. if (inst->holder_constructed) {
  831. holder = inst->holder;
  832. return true;
  833. } else {
  834. throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
  835. #if defined(NDEBUG)
  836. "(compile in debug mode for type information)");
  837. #else
  838. "of type '" + type_id<holder_type>() + "''");
  839. #endif
  840. }
  841. }
  842. template <typename T = holder_type, detail::enable_if_t<!std::is_constructible<T, const T &, type*>::value, int> = 0>
  843. bool try_implicit_casts(handle, bool) { return false; }
  844. template <typename T = holder_type, detail::enable_if_t<std::is_constructible<T, const T &, type*>::value, int> = 0>
  845. bool try_implicit_casts(handle src, bool convert) {
  846. for (auto &cast : typeinfo->implicit_casts) {
  847. copyable_holder_caster sub_caster(*cast.first);
  848. if (sub_caster.load(src, convert)) {
  849. value = cast.second(sub_caster.value);
  850. holder = holder_type(sub_caster.holder, (type *) value);
  851. return true;
  852. }
  853. }
  854. return false;
  855. }
  856. explicit operator type*() { return this->value; }
  857. explicit operator type&() { return *(this->value); }
  858. explicit operator holder_type*() { return &holder; }
  859. // Workaround for Intel compiler bug
  860. // see pybind11 issue 94
  861. #if defined(__ICC) || defined(__INTEL_COMPILER)
  862. operator holder_type&() { return holder; }
  863. #else
  864. explicit operator holder_type&() { return holder; }
  865. #endif
  866. static handle cast(const holder_type &src, return_value_policy, handle) {
  867. const auto *ptr = holder_helper<holder_type>::get(src);
  868. return type_caster_base<type>::cast_holder(ptr, &src);
  869. }
  870. protected:
  871. holder_type holder;
  872. };
  873. /// Specialize for the common std::shared_ptr, so users don't need to
  874. template <typename T>
  875. class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> { };
  876. template <typename type, typename holder_type>
  877. struct move_only_holder_caster {
  878. static handle cast(holder_type &&src, return_value_policy, handle) {
  879. auto *ptr = holder_helper<holder_type>::get(src);
  880. return type_caster_base<type>::cast_holder(ptr, &src);
  881. }
  882. static PYBIND11_DESCR name() { return type_caster_base<type>::name(); }
  883. };
  884. template <typename type, typename deleter>
  885. class type_caster<std::unique_ptr<type, deleter>>
  886. : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> { };
  887. template <typename type, typename holder_type>
  888. using type_caster_holder = conditional_t<std::is_copy_constructible<holder_type>::value,
  889. copyable_holder_caster<type, holder_type>,
  890. move_only_holder_caster<type, holder_type>>;
  891. template <typename T, bool Value = false> struct always_construct_holder { static constexpr bool value = Value; };
  892. /// Create a specialization for custom holder types (silently ignores std::shared_ptr)
  893. #define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
  894. namespace pybind11 { namespace detail { \
  895. template <typename type> \
  896. struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__> { }; \
  897. template <typename type> \
  898. class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
  899. : public type_caster_holder<type, holder_type> { }; \
  900. }}
  901. // PYBIND11_DECLARE_HOLDER_TYPE holder types:
  902. template <typename base, typename holder> struct is_holder_type :
  903. std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
  904. // Specialization for always-supported unique_ptr holders:
  905. template <typename base, typename deleter> struct is_holder_type<base, std::unique_ptr<base, deleter>> :
  906. std::true_type {};
  907. template <typename T> struct handle_type_name { static PYBIND11_DESCR name() { return _<T>(); } };
  908. template <> struct handle_type_name<bytes> { static PYBIND11_DESCR name() { return _(PYBIND11_BYTES_NAME); } };
  909. template <> struct handle_type_name<args> { static PYBIND11_DESCR name() { return _("*args"); } };
  910. template <> struct handle_type_name<kwargs> { static PYBIND11_DESCR name() { return _("**kwargs"); } };
  911. template <typename type>
  912. struct pyobject_caster {
  913. template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
  914. bool load(handle src, bool /* convert */) { value = src; return static_cast<bool>(value); }
  915. template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
  916. bool load(handle src, bool /* convert */) {
  917. if (!isinstance<type>(src))
  918. return false;
  919. value = reinterpret_borrow<type>(src);
  920. return true;
  921. }
  922. static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
  923. return src.inc_ref();
  924. }
  925. PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name());
  926. };
  927. template <typename T>
  928. class type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> { };
  929. // Our conditions for enabling moving are quite restrictive:
  930. // At compile time:
  931. // - T needs to be a non-const, non-pointer, non-reference type
  932. // - type_caster<T>::operator T&() must exist
  933. // - the type must be move constructible (obviously)
  934. // At run-time:
  935. // - if the type is non-copy-constructible, the object must be the sole owner of the type (i.e. it
  936. // must have ref_count() == 1)h
  937. // If any of the above are not satisfied, we fall back to copying.
  938. template <typename T> using move_is_plain_type = satisfies_none_of<T,
  939. std::is_void, std::is_pointer, std::is_reference, std::is_const
  940. >;
  941. template <typename T, typename SFINAE = void> struct move_always : std::false_type {};
  942. template <typename T> struct move_always<T, enable_if_t<all_of<
  943. move_is_plain_type<T>,
  944. negation<std::is_copy_constructible<T>>,
  945. std::is_move_constructible<T>,
  946. std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&>
  947. >::value>> : std::true_type {};
  948. template <typename T, typename SFINAE = void> struct move_if_unreferenced : std::false_type {};
  949. template <typename T> struct move_if_unreferenced<T, enable_if_t<all_of<
  950. move_is_plain_type<T>,
  951. negation<move_always<T>>,
  952. std::is_move_constructible<T>,
  953. std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&>
  954. >::value>> : std::true_type {};
  955. template <typename T> using move_never = none_of<move_always<T>, move_if_unreferenced<T>>;
  956. // Detect whether returning a `type` from a cast on type's type_caster is going to result in a
  957. // reference or pointer to a local variable of the type_caster. Basically, only
  958. // non-reference/pointer `type`s and reference/pointers from a type_caster_generic are safe;
  959. // everything else returns a reference/pointer to a local variable.
  960. template <typename type> using cast_is_temporary_value_reference = bool_constant<
  961. (std::is_reference<type>::value || std::is_pointer<type>::value) &&
  962. !std::is_base_of<type_caster_generic, make_caster<type>>::value
  963. >;
  964. // When a value returned from a C++ function is being cast back to Python, we almost always want to
  965. // force `policy = move`, regardless of the return value policy the function/method was declared
  966. // with. Some classes (most notably Eigen::Ref and related) need to avoid this, and so can do so by
  967. // specializing this struct.
  968. template <typename Return, typename SFINAE = void> struct return_value_policy_override {
  969. static return_value_policy policy(return_value_policy p) {
  970. return !std::is_lvalue_reference<Return>::value && !std::is_pointer<Return>::value
  971. ? return_value_policy::move : p;
  972. }
  973. };
  974. // Basic python -> C++ casting; throws if casting fails
  975. template <typename T, typename SFINAE> type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {
  976. if (!conv.load(handle, true)) {
  977. #if defined(NDEBUG)
  978. throw cast_error("Unable to cast Python instance to C++ type (compile in debug mode for details)");
  979. #else
  980. throw cast_error("Unable to cast Python instance of type " +
  981. (std::string) str(handle.get_type()) + " to C++ type '" + type_id<T>() + "''");
  982. #endif
  983. }
  984. return conv;
  985. }
  986. // Wrapper around the above that also constructs and returns a type_caster
  987. template <typename T> make_caster<T> load_type(const handle &handle) {
  988. make_caster<T> conv;
  989. load_type(conv, handle);
  990. return conv;
  991. }
  992. NAMESPACE_END(detail)
  993. // pytype -> C++ type
  994. template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
  995. T cast(const handle &handle) {
  996. using namespace detail;
  997. static_assert(!cast_is_temporary_value_reference<T>::value,
  998. "Unable to cast type to reference: value is local to type caster");
  999. return cast_op<T>(load_type<T>(handle));
  1000. }
  1001. // pytype -> pytype (calls converting constructor)
  1002. template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
  1003. T cast(const handle &handle) { return T(reinterpret_borrow<object>(handle)); }
  1004. // C++ type -> py::object
  1005. template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
  1006. object cast(const T &value, return_value_policy policy = return_value_policy::automatic_reference,
  1007. handle parent = handle()) {
  1008. if (policy == return_value_policy::automatic)
  1009. policy = std::is_pointer<T>::value ? return_value_policy::take_ownership : return_value_policy::copy;
  1010. else if (policy == return_value_policy::automatic_reference)
  1011. policy = std::is_pointer<T>::value ? return_value_policy::reference : return_value_policy::copy;
  1012. return reinterpret_steal<object>(detail::make_caster<T>::cast(value, policy, parent));
  1013. }
  1014. template <typename T> T handle::cast() const { return pybind11::cast<T>(*this); }
  1015. template <> inline void handle::cast() const { return; }
  1016. template <typename T>
  1017. detail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) {
  1018. if (obj.ref_count() > 1)
  1019. #if defined(NDEBUG)
  1020. throw cast_error("Unable to cast Python instance to C++ rvalue: instance has multiple references"
  1021. " (compile in debug mode for details)");
  1022. #else
  1023. throw cast_error("Unable to move from Python " + (std::string) str(obj.get_type()) +
  1024. " instance to C++ " + type_id<T>() + " instance: instance has multiple references");
  1025. #endif
  1026. // Move into a temporary and return that, because the reference may be a local value of `conv`
  1027. T ret = std::move(detail::load_type<T>(obj).operator T&());
  1028. return ret;
  1029. }
  1030. // Calling cast() on an rvalue calls pybind::cast with the object rvalue, which does:
  1031. // - If we have to move (because T has no copy constructor), do it. This will fail if the moved
  1032. // object has multiple references, but trying to copy will fail to compile.
  1033. // - If both movable and copyable, check ref count: if 1, move; otherwise copy
  1034. // - Otherwise (not movable), copy.
  1035. template <typename T> detail::enable_if_t<detail::move_always<T>::value, T> cast(object &&object) {
  1036. return move<T>(std::move(object));
  1037. }
  1038. template <typename T> detail::enable_if_t<detail::move_if_unreferenced<T>::value, T> cast(object &&object) {
  1039. if (object.ref_count() > 1)
  1040. return cast<T>(object);
  1041. else
  1042. return move<T>(std::move(object));
  1043. }
  1044. template <typename T> detail::enable_if_t<detail::move_never<T>::value, T> cast(object &&object) {
  1045. return cast<T>(object);
  1046. }
  1047. template <typename T> T object::cast() const & { return pybind11::cast<T>(*this); }
  1048. template <typename T> T object::cast() && { return pybind11::cast<T>(std::move(*this)); }
  1049. template <> inline void object::cast() const & { return; }
  1050. template <> inline void object::cast() && { return; }
  1051. NAMESPACE_BEGIN(detail)
  1052. // Declared in pytypes.h:
  1053. template <typename T, enable_if_t<!is_pyobject<T>::value, int>>
  1054. object object_or_cast(T &&o) { return pybind11::cast(std::forward<T>(o)); }
  1055. struct overload_unused {}; // Placeholder type for the unneeded (and dead code) static variable in the OVERLOAD_INT macro
  1056. template <typename ret_type> using overload_caster_t = conditional_t<
  1057. cast_is_temporary_value_reference<ret_type>::value, make_caster<ret_type>, overload_unused>;
  1058. // Trampoline use: for reference/pointer types to value-converted values, we do a value cast, then
  1059. // store the result in the given variable. For other types, this is a no-op.
  1060. template <typename T> enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o, make_caster<T> &caster) {
  1061. return cast_op<T>(load_type(caster, o));
  1062. }
  1063. template <typename T> enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&, overload_unused &) {
  1064. pybind11_fail("Internal error: cast_ref fallback invoked"); }
  1065. // Trampoline use: Having a pybind11::cast with an invalid reference type is going to static_assert, even
  1066. // though if it's in dead code, so we provide a "trampoline" to pybind11::cast that only does anything in
  1067. // cases where pybind11::cast is valid.
  1068. template <typename T> enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&o) {
  1069. return pybind11::cast<T>(std::move(o)); }
  1070. template <typename T> enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&) {
  1071. pybind11_fail("Internal error: cast_safe fallback invoked"); }
  1072. template <> inline void cast_safe<void>(object &&) {}
  1073. NAMESPACE_END(detail)
  1074. template <return_value_policy policy = return_value_policy::automatic_reference,
  1075. typename... Args> tuple make_tuple(Args&&... args_) {
  1076. const size_t size = sizeof...(Args);
  1077. std::array<object, size> args {
  1078. { reinterpret_steal<object>(detail::make_caster<Args>::cast(
  1079. std::forward<Args>(args_), policy, nullptr))... }
  1080. };
  1081. for (auto &arg_value : args) {
  1082. if (!arg_value) {
  1083. #if defined(NDEBUG)
  1084. throw cast_error("make_tuple(): unable to convert arguments to Python object (compile in debug mode for details)");
  1085. #else
  1086. throw cast_error("make_tuple(): unable to convert arguments of types '" +
  1087. (std::string) type_id<std::tuple<Args...>>() + "' to Python object");
  1088. #endif
  1089. }
  1090. }
  1091. tuple result(size);
  1092. int counter = 0;
  1093. for (auto &arg_value : args)
  1094. PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());
  1095. return result;
  1096. }
  1097. /// \ingroup annotations
  1098. /// Annotation for arguments
  1099. struct arg {
  1100. /// Constructs an argument with the name of the argument; if null or omitted, this is a positional argument.
  1101. constexpr explicit arg(const char *name = nullptr) : name(name), flag_noconvert(false) { }
  1102. /// Assign a value to this argument
  1103. template <typename T> arg_v operator=(T &&value) const;
  1104. /// Indicate that the type should not be converted in the type caster
  1105. arg &noconvert(bool flag = true) { flag_noconvert = flag; return *this; }
  1106. const char *name; ///< If non-null, this is a named kwargs argument
  1107. bool flag_noconvert : 1; ///< If set, do not allow conversion (requires a supporting type caster!)
  1108. };
  1109. /// \ingroup annotations
  1110. /// Annotation for arguments with values
  1111. struct arg_v : arg {
  1112. private:
  1113. template <typename T>
  1114. arg_v(arg &&base, T &&x, const char *descr = nullptr)
  1115. : arg(base),
  1116. value(reinterpret_steal<object>(
  1117. detail::make_caster<T>::cast(x, return_value_policy::automatic, {})
  1118. )),
  1119. descr(descr)
  1120. #if !defined(NDEBUG)
  1121. , type(type_id<T>())
  1122. #endif
  1123. { }
  1124. public:
  1125. /// Direct construction with name, default, and description
  1126. template <typename T>
  1127. arg_v(const char *name, T &&x, const char *descr = nullptr)
  1128. : arg_v(arg(name), std::forward<T>(x), descr) { }
  1129. /// Called internally when invoking `py::arg("a") = value`
  1130. template <typename T>
  1131. arg_v(const arg &base, T &&x, const char *descr = nullptr)
  1132. : arg_v(arg(base), std::forward<T>(x), descr) { }
  1133. /// Same as `arg::noconvert()`, but returns *this as arg_v&, not arg&
  1134. arg_v &noconvert(bool flag = true) { arg::noconvert(flag); return *this; }
  1135. /// The default value
  1136. object value;
  1137. /// The (optional) description of the default value
  1138. const char *descr;
  1139. #if !defined(NDEBUG)
  1140. /// The C++ type name of the default value (only available when compiled in debug mode)
  1141. std::string type;
  1142. #endif
  1143. };
  1144. template <typename T>
  1145. arg_v arg::operator=(T &&value) const { return {std::move(*this), std::forward<T>(value)}; }
  1146. /// Alias for backward compatibility -- to be removed in version 2.0
  1147. template <typename /*unused*/> using arg_t = arg_v;
  1148. inline namespace literals {
  1149. /** \rst
  1150. String literal version of `arg`
  1151. \endrst */
  1152. constexpr arg operator"" _a(const char *name, size_t) { return arg(name); }
  1153. }
  1154. NAMESPACE_BEGIN(detail)
  1155. // forward declaration
  1156. struct function_record;
  1157. /// Internal data associated with a single function call
  1158. struct function_call {
  1159. function_call(function_record &f, handle p); // Implementation in attr.h
  1160. /// The function data:
  1161. const function_record &func;
  1162. /// Arguments passed to the function:
  1163. std::vector<handle> args;
  1164. /// The `convert` value the arguments should be loaded with
  1165. std::vector<bool> args_convert;
  1166. /// The parent, if any
  1167. handle parent;
  1168. };
  1169. /// Helper class which loads arguments for C++ functions called from Python
  1170. template <typename... Args>
  1171. class argument_loader {
  1172. using indices = make_index_sequence<sizeof...(Args)>;
  1173. template <typename Arg> using argument_is_args = std::is_same<intrinsic_t<Arg>, args>;
  1174. template <typename Arg> using argument_is_kwargs = std::is_same<intrinsic_t<Arg>, kwargs>;
  1175. // Get args/kwargs argument positions relative to the end of the argument list:
  1176. static constexpr auto args_pos = constexpr_first<argument_is_args, Args...>() - (int) sizeof...(Args),
  1177. kwargs_pos = constexpr_first<argument_is_kwargs, Args...>() - (int) sizeof...(Args);
  1178. static constexpr bool args_kwargs_are_last = kwargs_pos >= - 1 && args_pos >= kwargs_pos - 1;
  1179. static_assert(args_kwargs_are_last, "py::args/py::kwargs are only permitted as the last argument(s) of a function");
  1180. public:
  1181. static constexpr bool has_kwargs = kwargs_pos < 0;
  1182. static constexpr bool has_args = args_pos < 0;
  1183. static PYBIND11_DESCR arg_names() { return detail::concat(make_caster<Args>::name()...); }
  1184. bool load_args(function_call &call) {
  1185. return load_impl_sequence(call, indices{});
  1186. }
  1187. template <typename Return, typename Func>
  1188. enable_if_t<!std::is_void<Return>::value, Return> call(Func &&f) {
  1189. return call_impl<Return>(std::forward<Func>(f), indices{});
  1190. }
  1191. template <typename Return, typename Func>
  1192. enable_if_t<std::is_void<Return>::value, void_type> call(Func &&f) {
  1193. call_impl<Return>(std::forward<Func>(f), indices{});
  1194. return void_type();
  1195. }
  1196. private:
  1197. static bool load_impl_sequence(function_call &, index_sequence<>) { return true; }
  1198. template <size_t... Is>
  1199. bool load_impl_sequence(function_call &call, index_sequence<Is...>) {
  1200. for (bool r : {std::get<Is>(value).load(call.args[Is], call.args_convert[Is])...})
  1201. if (!r)
  1202. return false;
  1203. return true;
  1204. }
  1205. template <typename Return, typename Func, size_t... Is>
  1206. Return call_impl(Func &&f, index_sequence<Is...>) {
  1207. return std::forward<Func>(f)(cast_op<Args>(std::get<Is>(value))...);
  1208. }
  1209. std::tuple<make_caster<Args>...> value;
  1210. };
  1211. /// Helper class which collects only positional arguments for a Python function call.
  1212. /// A fancier version below can collect any argument, but this one is optimal for simple calls.
  1213. template <return_value_policy policy>
  1214. class simple_collector {
  1215. public:
  1216. template <typename... Ts>
  1217. explicit simple_collector(Ts &&...values)
  1218. : m_args(pybind11::make_tuple<policy>(std::forward<Ts>(values)...)) { }
  1219. const tuple &args() const & { return m_args; }
  1220. dict kwargs() const { return {}; }
  1221. tuple args() && { return std::move(m_args); }
  1222. /// Call a Python function and pass the collected arguments
  1223. object call(PyObject *ptr) const {
  1224. PyObject *result = PyObject_CallObject(ptr, m_args.ptr());
  1225. if (!result)
  1226. throw error_already_set();
  1227. return reinterpret_steal<object>(result);
  1228. }
  1229. private:
  1230. tuple m_args;
  1231. };
  1232. /// Helper class which collects positional, keyword, * and ** arguments for a Python function call
  1233. template <return_value_policy policy>
  1234. class unpacking_collector {
  1235. public:
  1236. template <typename... Ts>
  1237. explicit unpacking_collector(Ts &&...values) {
  1238. // Tuples aren't (easily) resizable so a list is needed for collection,
  1239. // but the actual function call strictly requires a tuple.
  1240. auto args_list = list();
  1241. int _[] = { 0, (process(args_list, std::forward<Ts>(values)), 0)... };
  1242. ignore_unused(_);
  1243. m_args = std::move(args_list);
  1244. }
  1245. const tuple &args() const & { return m_args; }
  1246. const dict &kwargs() const & { return m_kwargs; }
  1247. tuple args() && { return std::move(m_args); }
  1248. dict kwargs() && { return std::move(m_kwargs); }
  1249. /// Call a Python function and pass the collected arguments
  1250. object call(PyObject *ptr) const {
  1251. PyObject *result = PyObject_Call(ptr, m_args.ptr(), m_kwargs.ptr());
  1252. if (!result)
  1253. throw error_already_set();
  1254. return reinterpret_steal<object>(result);
  1255. }
  1256. private:
  1257. template <typename T>
  1258. void process(list &args_list, T &&x) {
  1259. auto o = reinterpret_steal<object>(detail::make_caster<T>::cast(std::forward<T>(x), policy, {}));
  1260. if (!o) {
  1261. #if defined(NDEBUG)
  1262. argument_cast_error();
  1263. #else
  1264. argument_cast_error(std::to_string(args_list.size()), type_id<T>());
  1265. #endif
  1266. }
  1267. args_list.append(o);
  1268. }
  1269. void process(list &args_list, detail::args_proxy ap) {
  1270. for (const auto &a : ap)
  1271. args_list.append(a);
  1272. }
  1273. void process(list &/*args_list*/, arg_v a) {
  1274. if (!a.name)
  1275. #if defined(NDEBUG)
  1276. nameless_argument_error();
  1277. #else
  1278. nameless_argument_error(a.type);
  1279. #endif
  1280. if (m_kwargs.contains(a.name)) {
  1281. #if defined(NDEBUG)
  1282. multiple_values_error();
  1283. #else
  1284. multiple_values_error(a.name);
  1285. #endif
  1286. }
  1287. if (!a.value) {
  1288. #if defined(NDEBUG)
  1289. argument_cast_error();
  1290. #else
  1291. argument_cast_error(a.name, a.type);
  1292. #endif
  1293. }
  1294. m_kwargs[a.name] = a.value;
  1295. }
  1296. void process(list &/*args_list*/, detail::kwargs_proxy kp) {
  1297. if (!kp)
  1298. return;
  1299. for (const auto &k : reinterpret_borrow<dict>(kp)) {
  1300. if (m_kwargs.contains(k.first)) {
  1301. #if defined(NDEBUG)
  1302. multiple_values_error();
  1303. #else
  1304. multiple_values_error(str(k.first));
  1305. #endif
  1306. }
  1307. m_kwargs[k.first] = k.second;
  1308. }
  1309. }
  1310. [[noreturn]] static void nameless_argument_error() {
  1311. throw type_error("Got kwargs without a name; only named arguments "
  1312. "may be passed via py::arg() to a python function call. "
  1313. "(compile in debug mode for details)");
  1314. }
  1315. [[noreturn]] static void nameless_argument_error(std::string type) {
  1316. throw type_error("Got kwargs without a name of type '" + type + "'; only named "
  1317. "arguments may be passed via py::arg() to a python function call. ");
  1318. }
  1319. [[noreturn]] static void multiple_values_error() {
  1320. throw type_error("Got multiple values for keyword argument "
  1321. "(compile in debug mode for details)");
  1322. }
  1323. [[noreturn]] static void multiple_values_error(std::string name) {
  1324. throw type_error("Got multiple values for keyword argument '" + name + "'");
  1325. }
  1326. [[noreturn]] static void argument_cast_error() {
  1327. throw cast_error("Unable to convert call argument to Python object "
  1328. "(compile in debug mode for details)");
  1329. }
  1330. [[noreturn]] static void argument_cast_error(std::string name, std::string type) {
  1331. throw cast_error("Unable to convert call argument '" + name
  1332. + "' of type '" + type + "' to Python object");
  1333. }
  1334. private:
  1335. tuple m_args;
  1336. dict m_kwargs;
  1337. };
  1338. /// Collect only positional arguments for a Python function call
  1339. template <return_value_policy policy, typename... Args,
  1340. typename = enable_if_t<all_of<is_positional<Args>...>::value>>
  1341. simple_collector<policy> collect_arguments(Args &&...args) {
  1342. return simple_collector<policy>(std::forward<Args>(args)...);
  1343. }
  1344. /// Collect all arguments, including keywords and unpacking (only instantiated when needed)
  1345. template <return_value_policy policy, typename... Args,
  1346. typename = enable_if_t<!all_of<is_positional<Args>...>::value>>
  1347. unpacking_collector<policy> collect_arguments(Args &&...args) {
  1348. // Following argument order rules for generalized unpacking according to PEP 448
  1349. static_assert(
  1350. constexpr_last<is_positional, Args...>() < constexpr_first<is_keyword_or_ds, Args...>()
  1351. && constexpr_last<is_s_unpacking, Args...>() < constexpr_first<is_ds_unpacking, Args...>(),
  1352. "Invalid function call: positional args must precede keywords and ** unpacking; "
  1353. "* unpacking must precede ** unpacking"
  1354. );
  1355. return unpacking_collector<policy>(std::forward<Args>(args)...);
  1356. }
  1357. template <typename Derived>
  1358. template <return_value_policy policy, typename... Args>
  1359. object object_api<Derived>::operator()(Args &&...args) const {
  1360. return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
  1361. }
  1362. template <typename Derived>
  1363. template <return_value_policy policy, typename... Args>
  1364. object object_api<Derived>::call(Args &&...args) const {
  1365. return operator()<policy>(std::forward<Args>(args)...);
  1366. }
  1367. NAMESPACE_END(detail)
  1368. #define PYBIND11_MAKE_OPAQUE(Type) \
  1369. namespace pybind11 { namespace detail { \
  1370. template<> class type_caster<Type> : public type_caster_base<Type> { }; \
  1371. }}
  1372. NAMESPACE_END(pybind11)