cast.h 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015
  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. #include <tuple>
  15. #if defined(PYBIND11_CPP17)
  16. # if defined(__has_include)
  17. # if __has_include(<string_view>)
  18. # define PYBIND11_HAS_STRING_VIEW
  19. # endif
  20. # elif defined(_MSC_VER)
  21. # define PYBIND11_HAS_STRING_VIEW
  22. # endif
  23. #endif
  24. #ifdef PYBIND11_HAS_STRING_VIEW
  25. #include <string_view>
  26. #endif
  27. NAMESPACE_BEGIN(pybind11)
  28. NAMESPACE_BEGIN(detail)
  29. // Forward declarations:
  30. inline PyTypeObject *make_static_property_type();
  31. inline PyTypeObject *make_default_metaclass();
  32. inline PyObject *make_object_base_type(PyTypeObject *metaclass);
  33. struct value_and_holder;
  34. /// Additional type information which does not fit into the PyTypeObject
  35. struct type_info {
  36. PyTypeObject *type;
  37. const std::type_info *cpptype;
  38. size_t type_size, holder_size_in_ptrs;
  39. void *(*operator_new)(size_t);
  40. void (*init_holder)(instance *, const void *);
  41. void (*dealloc)(const value_and_holder &v_h);
  42. std::vector<PyObject *(*)(PyObject *, PyTypeObject *)> implicit_conversions;
  43. std::vector<std::pair<const std::type_info *, void *(*)(void *)>> implicit_casts;
  44. std::vector<bool (*)(PyObject *, void *&)> *direct_conversions;
  45. buffer_info *(*get_buffer)(PyObject *, void *) = nullptr;
  46. void *get_buffer_data = nullptr;
  47. /* A simple type never occurs as a (direct or indirect) parent
  48. * of a class that makes use of multiple inheritance */
  49. bool simple_type : 1;
  50. /* True if there is no multiple inheritance in this type's inheritance tree */
  51. bool simple_ancestors : 1;
  52. /* for base vs derived holder_type checks */
  53. bool default_holder : 1;
  54. };
  55. // Store the static internals pointer in a version-specific function so that we're guaranteed it
  56. // will be distinct for modules compiled for different pybind11 versions. Without this, some
  57. // compilers (i.e. gcc) can use the same static pointer storage location across different .so's,
  58. // even though the `get_internals()` function itself is local to each shared object.
  59. template <int = PYBIND11_VERSION_MAJOR, int = PYBIND11_VERSION_MINOR>
  60. internals *&get_internals_ptr() { static internals *internals_ptr = nullptr; return internals_ptr; }
  61. PYBIND11_NOINLINE inline internals &get_internals() {
  62. internals *&internals_ptr = get_internals_ptr();
  63. if (internals_ptr)
  64. return *internals_ptr;
  65. handle builtins(PyEval_GetBuiltins());
  66. const char *id = PYBIND11_INTERNALS_ID;
  67. if (builtins.contains(id) && isinstance<capsule>(builtins[id])) {
  68. internals_ptr = *static_cast<internals **>(capsule(builtins[id]));
  69. } else {
  70. internals_ptr = new internals();
  71. #if defined(WITH_THREAD)
  72. PyEval_InitThreads();
  73. PyThreadState *tstate = PyThreadState_Get();
  74. internals_ptr->tstate = PyThread_create_key();
  75. PyThread_set_key_value(internals_ptr->tstate, tstate);
  76. internals_ptr->istate = tstate->interp;
  77. #endif
  78. builtins[id] = capsule(&internals_ptr);
  79. internals_ptr->registered_exception_translators.push_front(
  80. [](std::exception_ptr p) -> void {
  81. try {
  82. if (p) std::rethrow_exception(p);
  83. } catch (error_already_set &e) { e.restore(); return;
  84. } catch (const builtin_exception &e) { e.set_error(); return;
  85. } catch (const std::bad_alloc &e) { PyErr_SetString(PyExc_MemoryError, e.what()); return;
  86. } catch (const std::domain_error &e) { PyErr_SetString(PyExc_ValueError, e.what()); return;
  87. } catch (const std::invalid_argument &e) { PyErr_SetString(PyExc_ValueError, e.what()); return;
  88. } catch (const std::length_error &e) { PyErr_SetString(PyExc_ValueError, e.what()); return;
  89. } catch (const std::out_of_range &e) { PyErr_SetString(PyExc_IndexError, e.what()); return;
  90. } catch (const std::range_error &e) { PyErr_SetString(PyExc_ValueError, e.what()); return;
  91. } catch (const std::exception &e) { PyErr_SetString(PyExc_RuntimeError, e.what()); return;
  92. } catch (...) {
  93. PyErr_SetString(PyExc_RuntimeError, "Caught an unknown exception!");
  94. return;
  95. }
  96. }
  97. );
  98. internals_ptr->static_property_type = make_static_property_type();
  99. internals_ptr->default_metaclass = make_default_metaclass();
  100. internals_ptr->instance_base = make_object_base_type(internals_ptr->default_metaclass);
  101. }
  102. return *internals_ptr;
  103. }
  104. /// A life support system for temporary objects created by `type_caster::load()`.
  105. /// Adding a patient will keep it alive up until the enclosing function returns.
  106. class loader_life_support {
  107. public:
  108. /// A new patient frame is created when a function is entered
  109. loader_life_support() {
  110. get_internals().loader_patient_stack.push_back(nullptr);
  111. }
  112. /// ... and destroyed after it returns
  113. ~loader_life_support() {
  114. auto &stack = get_internals().loader_patient_stack;
  115. if (stack.empty())
  116. pybind11_fail("loader_life_support: internal error");
  117. auto ptr = stack.back();
  118. stack.pop_back();
  119. Py_CLEAR(ptr);
  120. // A heuristic to reduce the stack's capacity (e.g. after long recursive calls)
  121. if (stack.capacity() > 16 && stack.size() != 0 && stack.capacity() / stack.size() > 2)
  122. stack.shrink_to_fit();
  123. }
  124. /// This can only be used inside a pybind11-bound function, either by `argument_loader`
  125. /// at argument preparation time or by `py::cast()` at execution time.
  126. PYBIND11_NOINLINE static void add_patient(handle h) {
  127. auto &stack = get_internals().loader_patient_stack;
  128. if (stack.empty())
  129. throw cast_error("When called outside a bound function, py::cast() cannot "
  130. "do Python -> C++ conversions which require the creation "
  131. "of temporary values");
  132. auto &list_ptr = stack.back();
  133. if (list_ptr == nullptr) {
  134. list_ptr = PyList_New(1);
  135. if (!list_ptr)
  136. pybind11_fail("loader_life_support: error allocating list");
  137. PyList_SET_ITEM(list_ptr, 0, h.inc_ref().ptr());
  138. } else {
  139. auto result = PyList_Append(list_ptr, h.ptr());
  140. if (result == -1)
  141. pybind11_fail("loader_life_support: error adding patient");
  142. }
  143. }
  144. };
  145. // Gets the cache entry for the given type, creating it if necessary. The return value is the pair
  146. // returned by emplace, i.e. an iterator for the entry and a bool set to `true` if the entry was
  147. // just created.
  148. inline std::pair<decltype(internals::registered_types_py)::iterator, bool> all_type_info_get_cache(PyTypeObject *type);
  149. // Populates a just-created cache entry.
  150. PYBIND11_NOINLINE inline void all_type_info_populate(PyTypeObject *t, std::vector<type_info *> &bases) {
  151. std::vector<PyTypeObject *> check;
  152. for (handle parent : reinterpret_borrow<tuple>(t->tp_bases))
  153. check.push_back((PyTypeObject *) parent.ptr());
  154. auto const &type_dict = get_internals().registered_types_py;
  155. for (size_t i = 0; i < check.size(); i++) {
  156. auto type = check[i];
  157. // Ignore Python2 old-style class super type:
  158. if (!PyType_Check((PyObject *) type)) continue;
  159. // Check `type` in the current set of registered python types:
  160. auto it = type_dict.find(type);
  161. if (it != type_dict.end()) {
  162. // We found a cache entry for it, so it's either pybind-registered or has pre-computed
  163. // pybind bases, but we have to make sure we haven't already seen the type(s) before: we
  164. // want to follow Python/virtual C++ rules that there should only be one instance of a
  165. // common base.
  166. for (auto *tinfo : it->second) {
  167. // NB: Could use a second set here, rather than doing a linear search, but since
  168. // having a large number of immediate pybind11-registered types seems fairly
  169. // unlikely, that probably isn't worthwhile.
  170. bool found = false;
  171. for (auto *known : bases) {
  172. if (known == tinfo) { found = true; break; }
  173. }
  174. if (!found) bases.push_back(tinfo);
  175. }
  176. }
  177. else if (type->tp_bases) {
  178. // It's some python type, so keep follow its bases classes to look for one or more
  179. // registered types
  180. if (i + 1 == check.size()) {
  181. // When we're at the end, we can pop off the current element to avoid growing
  182. // `check` when adding just one base (which is typical--.e. when there is no
  183. // multiple inheritance)
  184. check.pop_back();
  185. i--;
  186. }
  187. for (handle parent : reinterpret_borrow<tuple>(type->tp_bases))
  188. check.push_back((PyTypeObject *) parent.ptr());
  189. }
  190. }
  191. }
  192. /**
  193. * Extracts vector of type_info pointers of pybind-registered roots of the given Python type. Will
  194. * be just 1 pybind type for the Python type of a pybind-registered class, or for any Python-side
  195. * derived class that uses single inheritance. Will contain as many types as required for a Python
  196. * class that uses multiple inheritance to inherit (directly or indirectly) from multiple
  197. * pybind-registered classes. Will be empty if neither the type nor any base classes are
  198. * pybind-registered.
  199. *
  200. * The value is cached for the lifetime of the Python type.
  201. */
  202. inline const std::vector<detail::type_info *> &all_type_info(PyTypeObject *type) {
  203. auto ins = all_type_info_get_cache(type);
  204. if (ins.second)
  205. // New cache entry: populate it
  206. all_type_info_populate(type, ins.first->second);
  207. return ins.first->second;
  208. }
  209. /**
  210. * Gets a single pybind11 type info for a python type. Returns nullptr if neither the type nor any
  211. * ancestors are pybind11-registered. Throws an exception if there are multiple bases--use
  212. * `all_type_info` instead if you want to support multiple bases.
  213. */
  214. PYBIND11_NOINLINE inline detail::type_info* get_type_info(PyTypeObject *type) {
  215. auto &bases = all_type_info(type);
  216. if (bases.size() == 0)
  217. return nullptr;
  218. if (bases.size() > 1)
  219. pybind11_fail("pybind11::detail::get_type_info: type has multiple pybind11-registered bases");
  220. return bases.front();
  221. }
  222. PYBIND11_NOINLINE inline detail::type_info *get_type_info(const std::type_info &tp,
  223. bool throw_if_missing = false) {
  224. auto &types = get_internals().registered_types_cpp;
  225. auto it = types.find(std::type_index(tp));
  226. if (it != types.end())
  227. return (detail::type_info *) it->second;
  228. if (throw_if_missing) {
  229. std::string tname = tp.name();
  230. detail::clean_type_id(tname);
  231. pybind11_fail("pybind11::detail::get_type_info: unable to find type info for \"" + tname + "\"");
  232. }
  233. return nullptr;
  234. }
  235. PYBIND11_NOINLINE inline handle get_type_handle(const std::type_info &tp, bool throw_if_missing) {
  236. detail::type_info *type_info = get_type_info(tp, throw_if_missing);
  237. return handle(type_info ? ((PyObject *) type_info->type) : nullptr);
  238. }
  239. struct value_and_holder {
  240. instance *inst;
  241. size_t index;
  242. const detail::type_info *type;
  243. void **vh;
  244. value_and_holder(instance *i, const detail::type_info *type, size_t vpos, size_t index) :
  245. inst{i}, index{index}, type{type},
  246. vh{inst->simple_layout ? inst->simple_value_holder : &inst->nonsimple.values_and_holders[vpos]}
  247. {}
  248. // Used for past-the-end iterator
  249. value_and_holder(size_t index) : index{index} {}
  250. template <typename V = void> V *&value_ptr() const {
  251. return reinterpret_cast<V *&>(vh[0]);
  252. }
  253. // True if this `value_and_holder` has a non-null value pointer
  254. explicit operator bool() const { return value_ptr(); }
  255. template <typename H> H &holder() const {
  256. return reinterpret_cast<H &>(vh[1]);
  257. }
  258. bool holder_constructed() const {
  259. return inst->simple_layout
  260. ? inst->simple_holder_constructed
  261. : inst->nonsimple.holder_constructed[index];
  262. }
  263. void set_holder_constructed() {
  264. if (inst->simple_layout)
  265. inst->simple_holder_constructed = true;
  266. else
  267. inst->nonsimple.holder_constructed[index] = true;
  268. }
  269. };
  270. // Container for accessing and iterating over an instance's values/holders
  271. struct values_and_holders {
  272. private:
  273. instance *inst;
  274. using type_vec = std::vector<detail::type_info *>;
  275. const type_vec &tinfo;
  276. public:
  277. values_and_holders(instance *inst) : inst{inst}, tinfo(all_type_info(Py_TYPE(inst))) {}
  278. struct iterator {
  279. private:
  280. instance *inst;
  281. const type_vec *types;
  282. value_and_holder curr;
  283. friend struct values_and_holders;
  284. iterator(instance *inst, const type_vec *tinfo)
  285. : inst{inst}, types{tinfo},
  286. curr(inst /* instance */,
  287. types->empty() ? nullptr : (*types)[0] /* type info */,
  288. 0, /* vpos: (non-simple types only): the first vptr comes first */
  289. 0 /* index */)
  290. {}
  291. // Past-the-end iterator:
  292. iterator(size_t end) : curr(end) {}
  293. public:
  294. bool operator==(const iterator &other) { return curr.index == other.curr.index; }
  295. bool operator!=(const iterator &other) { return curr.index != other.curr.index; }
  296. iterator &operator++() {
  297. if (!inst->simple_layout)
  298. curr.vh += 1 + (*types)[curr.index]->holder_size_in_ptrs;
  299. ++curr.index;
  300. curr.type = curr.index < types->size() ? (*types)[curr.index] : nullptr;
  301. return *this;
  302. }
  303. value_and_holder &operator*() { return curr; }
  304. value_and_holder *operator->() { return &curr; }
  305. };
  306. iterator begin() { return iterator(inst, &tinfo); }
  307. iterator end() { return iterator(tinfo.size()); }
  308. iterator find(const type_info *find_type) {
  309. auto it = begin(), endit = end();
  310. while (it != endit && it->type != find_type) ++it;
  311. return it;
  312. }
  313. size_t size() { return tinfo.size(); }
  314. };
  315. /**
  316. * Extracts C++ value and holder pointer references from an instance (which may contain multiple
  317. * values/holders for python-side multiple inheritance) that match the given type. Throws an error
  318. * if the given type (or ValueType, if omitted) is not a pybind11 base of the given instance. If
  319. * `find_type` is omitted (or explicitly specified as nullptr) the first value/holder are returned,
  320. * regardless of type (and the resulting .type will be nullptr).
  321. *
  322. * The returned object should be short-lived: in particular, it must not outlive the called-upon
  323. * instance.
  324. */
  325. PYBIND11_NOINLINE inline value_and_holder instance::get_value_and_holder(const type_info *find_type /*= nullptr default in common.h*/) {
  326. // Optimize common case:
  327. if (!find_type || Py_TYPE(this) == find_type->type)
  328. return value_and_holder(this, find_type, 0, 0);
  329. detail::values_and_holders vhs(this);
  330. auto it = vhs.find(find_type);
  331. if (it != vhs.end())
  332. return *it;
  333. #if defined(NDEBUG)
  334. pybind11_fail("pybind11::detail::instance::get_value_and_holder: "
  335. "type is not a pybind11 base of the given instance "
  336. "(compile in debug mode for type details)");
  337. #else
  338. pybind11_fail("pybind11::detail::instance::get_value_and_holder: `" +
  339. std::string(find_type->type->tp_name) + "' is not a pybind11 base of the given `" +
  340. std::string(Py_TYPE(this)->tp_name) + "' instance");
  341. #endif
  342. }
  343. PYBIND11_NOINLINE inline void instance::allocate_layout() {
  344. auto &tinfo = all_type_info(Py_TYPE(this));
  345. const size_t n_types = tinfo.size();
  346. if (n_types == 0)
  347. pybind11_fail("instance allocation failed: new instance has no pybind11-registered base types");
  348. simple_layout =
  349. n_types == 1 && tinfo.front()->holder_size_in_ptrs <= instance_simple_holder_in_ptrs();
  350. // Simple path: no python-side multiple inheritance, and a small-enough holder
  351. if (simple_layout) {
  352. simple_value_holder[0] = nullptr;
  353. simple_holder_constructed = false;
  354. }
  355. else { // multiple base types or a too-large holder
  356. // Allocate space to hold: [v1*][h1][v2*][h2]...[bb...] where [vN*] is a value pointer,
  357. // [hN] is the (uninitialized) holder instance for value N, and [bb...] is a set of bool
  358. // values that tracks whether each associated holder has been initialized. Each [block] is
  359. // padded, if necessary, to an integer multiple of sizeof(void *).
  360. size_t space = 0;
  361. for (auto t : tinfo) {
  362. space += 1; // value pointer
  363. space += t->holder_size_in_ptrs; // holder instance
  364. }
  365. size_t flags_at = space;
  366. space += size_in_ptrs(n_types * sizeof(bool)); // holder constructed flags
  367. // Allocate space for flags, values, and holders, and initialize it to 0 (flags and values,
  368. // in particular, need to be 0). Use Python's memory allocation functions: in Python 3.6
  369. // they default to using pymalloc, which is designed to be efficient for small allocations
  370. // like the one we're doing here; in earlier versions (and for larger allocations) they are
  371. // just wrappers around malloc.
  372. #if PY_VERSION_HEX >= 0x03050000
  373. nonsimple.values_and_holders = (void **) PyMem_Calloc(space, sizeof(void *));
  374. if (!nonsimple.values_and_holders) throw std::bad_alloc();
  375. #else
  376. nonsimple.values_and_holders = (void **) PyMem_New(void *, space);
  377. if (!nonsimple.values_and_holders) throw std::bad_alloc();
  378. std::memset(nonsimple.values_and_holders, 0, space * sizeof(void *));
  379. #endif
  380. nonsimple.holder_constructed = reinterpret_cast<bool *>(&nonsimple.values_and_holders[flags_at]);
  381. }
  382. owned = true;
  383. }
  384. PYBIND11_NOINLINE inline void instance::deallocate_layout() {
  385. if (!simple_layout)
  386. PyMem_Free(nonsimple.values_and_holders);
  387. }
  388. PYBIND11_NOINLINE inline bool isinstance_generic(handle obj, const std::type_info &tp) {
  389. handle type = detail::get_type_handle(tp, false);
  390. if (!type)
  391. return false;
  392. return isinstance(obj, type);
  393. }
  394. PYBIND11_NOINLINE inline std::string error_string() {
  395. if (!PyErr_Occurred()) {
  396. PyErr_SetString(PyExc_RuntimeError, "Unknown internal error occurred");
  397. return "Unknown internal error occurred";
  398. }
  399. error_scope scope; // Preserve error state
  400. std::string errorString;
  401. if (scope.type) {
  402. errorString += handle(scope.type).attr("__name__").cast<std::string>();
  403. errorString += ": ";
  404. }
  405. if (scope.value)
  406. errorString += (std::string) str(scope.value);
  407. PyErr_NormalizeException(&scope.type, &scope.value, &scope.trace);
  408. #if PY_MAJOR_VERSION >= 3
  409. if (scope.trace != nullptr)
  410. PyException_SetTraceback(scope.value, scope.trace);
  411. #endif
  412. #if !defined(PYPY_VERSION)
  413. if (scope.trace) {
  414. PyTracebackObject *trace = (PyTracebackObject *) scope.trace;
  415. /* Get the deepest trace possible */
  416. while (trace->tb_next)
  417. trace = trace->tb_next;
  418. PyFrameObject *frame = trace->tb_frame;
  419. errorString += "\n\nAt:\n";
  420. while (frame) {
  421. int lineno = PyFrame_GetLineNumber(frame);
  422. errorString +=
  423. " " + handle(frame->f_code->co_filename).cast<std::string>() +
  424. "(" + std::to_string(lineno) + "): " +
  425. handle(frame->f_code->co_name).cast<std::string>() + "\n";
  426. frame = frame->f_back;
  427. }
  428. trace = trace->tb_next;
  429. }
  430. #endif
  431. return errorString;
  432. }
  433. PYBIND11_NOINLINE inline handle get_object_handle(const void *ptr, const detail::type_info *type ) {
  434. auto &instances = get_internals().registered_instances;
  435. auto range = instances.equal_range(ptr);
  436. for (auto it = range.first; it != range.second; ++it) {
  437. for (auto vh : values_and_holders(it->second)) {
  438. if (vh.type == type)
  439. return handle((PyObject *) it->second);
  440. }
  441. }
  442. return handle();
  443. }
  444. inline PyThreadState *get_thread_state_unchecked() {
  445. #if defined(PYPY_VERSION)
  446. return PyThreadState_GET();
  447. #elif PY_VERSION_HEX < 0x03000000
  448. return _PyThreadState_Current;
  449. #elif PY_VERSION_HEX < 0x03050000
  450. return (PyThreadState*) _Py_atomic_load_relaxed(&_PyThreadState_Current);
  451. #elif PY_VERSION_HEX < 0x03050200
  452. return (PyThreadState*) _PyThreadState_Current.value;
  453. #else
  454. return _PyThreadState_UncheckedGet();
  455. #endif
  456. }
  457. // Forward declarations
  458. inline void keep_alive_impl(handle nurse, handle patient);
  459. inline void register_instance(instance *self, void *valptr, const type_info *tinfo);
  460. inline PyObject *make_new_instance(PyTypeObject *type, bool allocate_value = true);
  461. class type_caster_generic {
  462. public:
  463. PYBIND11_NOINLINE type_caster_generic(const std::type_info &type_info)
  464. : typeinfo(get_type_info(type_info)) { }
  465. bool load(handle src, bool convert) {
  466. return load_impl<type_caster_generic>(src, convert);
  467. }
  468. PYBIND11_NOINLINE static handle cast(const void *_src, return_value_policy policy, handle parent,
  469. const detail::type_info *tinfo,
  470. void *(*copy_constructor)(const void *),
  471. void *(*move_constructor)(const void *),
  472. const void *existing_holder = nullptr) {
  473. if (!tinfo) // no type info: error will be set already
  474. return handle();
  475. void *src = const_cast<void *>(_src);
  476. if (src == nullptr)
  477. return none().release();
  478. auto it_instances = get_internals().registered_instances.equal_range(src);
  479. for (auto it_i = it_instances.first; it_i != it_instances.second; ++it_i) {
  480. for (auto instance_type : detail::all_type_info(Py_TYPE(it_i->second))) {
  481. if (instance_type && instance_type == tinfo)
  482. return handle((PyObject *) it_i->second).inc_ref();
  483. }
  484. }
  485. auto inst = reinterpret_steal<object>(make_new_instance(tinfo->type, false /* don't allocate value */));
  486. auto wrapper = reinterpret_cast<instance *>(inst.ptr());
  487. wrapper->owned = false;
  488. void *&valueptr = values_and_holders(wrapper).begin()->value_ptr();
  489. switch (policy) {
  490. case return_value_policy::automatic:
  491. case return_value_policy::take_ownership:
  492. valueptr = src;
  493. wrapper->owned = true;
  494. break;
  495. case return_value_policy::automatic_reference:
  496. case return_value_policy::reference:
  497. valueptr = src;
  498. wrapper->owned = false;
  499. break;
  500. case return_value_policy::copy:
  501. if (copy_constructor)
  502. valueptr = copy_constructor(src);
  503. else
  504. throw cast_error("return_value_policy = copy, but the "
  505. "object is non-copyable!");
  506. wrapper->owned = true;
  507. break;
  508. case return_value_policy::move:
  509. if (move_constructor)
  510. valueptr = move_constructor(src);
  511. else if (copy_constructor)
  512. valueptr = copy_constructor(src);
  513. else
  514. throw cast_error("return_value_policy = move, but the "
  515. "object is neither movable nor copyable!");
  516. wrapper->owned = true;
  517. break;
  518. case return_value_policy::reference_internal:
  519. valueptr = src;
  520. wrapper->owned = false;
  521. keep_alive_impl(inst, parent);
  522. break;
  523. default:
  524. throw cast_error("unhandled return_value_policy: should not happen!");
  525. }
  526. register_instance(wrapper, valueptr, tinfo);
  527. tinfo->init_holder(wrapper, existing_holder);
  528. return inst.release();
  529. }
  530. protected:
  531. // Base methods for generic caster; there are overridden in copyable_holder_caster
  532. void load_value(const value_and_holder &v_h) {
  533. value = v_h.value_ptr();
  534. }
  535. bool try_implicit_casts(handle src, bool convert) {
  536. for (auto &cast : typeinfo->implicit_casts) {
  537. type_caster_generic sub_caster(*cast.first);
  538. if (sub_caster.load(src, convert)) {
  539. value = cast.second(sub_caster.value);
  540. return true;
  541. }
  542. }
  543. return false;
  544. }
  545. bool try_direct_conversions(handle src) {
  546. for (auto &converter : *typeinfo->direct_conversions) {
  547. if (converter(src.ptr(), value))
  548. return true;
  549. }
  550. return false;
  551. }
  552. void check_holder_compat() {}
  553. // Implementation of `load`; this takes the type of `this` so that it can dispatch the relevant
  554. // bits of code between here and copyable_holder_caster where the two classes need different
  555. // logic (without having to resort to virtual inheritance).
  556. template <typename ThisT>
  557. PYBIND11_NOINLINE bool load_impl(handle src, bool convert) {
  558. if (!src || !typeinfo)
  559. return false;
  560. if (src.is_none()) {
  561. // Defer accepting None to other overloads (if we aren't in convert mode):
  562. if (!convert) return false;
  563. value = nullptr;
  564. return true;
  565. }
  566. auto &this_ = static_cast<ThisT &>(*this);
  567. this_.check_holder_compat();
  568. PyTypeObject *srctype = Py_TYPE(src.ptr());
  569. // Case 1: If src is an exact type match for the target type then we can reinterpret_cast
  570. // the instance's value pointer to the target type:
  571. if (srctype == typeinfo->type) {
  572. this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
  573. return true;
  574. }
  575. // Case 2: We have a derived class
  576. else if (PyType_IsSubtype(srctype, typeinfo->type)) {
  577. auto &bases = all_type_info(srctype);
  578. bool no_cpp_mi = typeinfo->simple_type;
  579. // Case 2a: the python type is a Python-inherited derived class that inherits from just
  580. // one simple (no MI) pybind11 class, or is an exact match, so the C++ instance is of
  581. // the right type and we can use reinterpret_cast.
  582. // (This is essentially the same as case 2b, but because not using multiple inheritance
  583. // is extremely common, we handle it specially to avoid the loop iterator and type
  584. // pointer lookup overhead)
  585. if (bases.size() == 1 && (no_cpp_mi || bases.front()->type == typeinfo->type)) {
  586. this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
  587. return true;
  588. }
  589. // Case 2b: the python type inherits from multiple C++ bases. Check the bases to see if
  590. // we can find an exact match (or, for a simple C++ type, an inherited match); if so, we
  591. // can safely reinterpret_cast to the relevant pointer.
  592. else if (bases.size() > 1) {
  593. for (auto base : bases) {
  594. if (no_cpp_mi ? PyType_IsSubtype(base->type, typeinfo->type) : base->type == typeinfo->type) {
  595. this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder(base));
  596. return true;
  597. }
  598. }
  599. }
  600. // Case 2c: C++ multiple inheritance is involved and we couldn't find an exact type match
  601. // in the registered bases, above, so try implicit casting (needed for proper C++ casting
  602. // when MI is involved).
  603. if (this_.try_implicit_casts(src, convert))
  604. return true;
  605. }
  606. // Perform an implicit conversion
  607. if (convert) {
  608. for (auto &converter : typeinfo->implicit_conversions) {
  609. auto temp = reinterpret_steal<object>(converter(src.ptr(), typeinfo->type));
  610. if (load_impl<ThisT>(temp, false)) {
  611. loader_life_support::add_patient(temp);
  612. return true;
  613. }
  614. }
  615. if (this_.try_direct_conversions(src))
  616. return true;
  617. }
  618. return false;
  619. }
  620. // Called to do type lookup and wrap the pointer and type in a pair when a dynamic_cast
  621. // isn't needed or can't be used. If the type is unknown, sets the error and returns a pair
  622. // with .second = nullptr. (p.first = nullptr is not an error: it becomes None).
  623. PYBIND11_NOINLINE static std::pair<const void *, const type_info *> src_and_type(
  624. const void *src, const std::type_info &cast_type, const std::type_info *rtti_type = nullptr) {
  625. auto &internals = get_internals();
  626. auto it = internals.registered_types_cpp.find(std::type_index(cast_type));
  627. if (it != internals.registered_types_cpp.end())
  628. return {src, (const type_info *) it->second};
  629. // Not found, set error:
  630. std::string tname = rtti_type ? rtti_type->name() : cast_type.name();
  631. detail::clean_type_id(tname);
  632. std::string msg = "Unregistered type : " + tname;
  633. PyErr_SetString(PyExc_TypeError, msg.c_str());
  634. return {nullptr, nullptr};
  635. }
  636. const type_info *typeinfo = nullptr;
  637. void *value = nullptr;
  638. };
  639. /**
  640. * Determine suitable casting operator for pointer-or-lvalue-casting type casters. The type caster
  641. * needs to provide `operator T*()` and `operator T&()` operators.
  642. *
  643. * If the type supports moving the value away via an `operator T&&() &&` method, it should use
  644. * `movable_cast_op_type` instead.
  645. */
  646. template <typename T>
  647. using cast_op_type =
  648. conditional_t<std::is_pointer<remove_reference_t<T>>::value,
  649. typename std::add_pointer<intrinsic_t<T>>::type,
  650. typename std::add_lvalue_reference<intrinsic_t<T>>::type>;
  651. /**
  652. * Determine suitable casting operator for a type caster with a movable value. Such a type caster
  653. * needs to provide `operator T*()`, `operator T&()`, and `operator T&&() &&`. The latter will be
  654. * called in appropriate contexts where the value can be moved rather than copied.
  655. *
  656. * These operator are automatically provided when using the PYBIND11_TYPE_CASTER macro.
  657. */
  658. template <typename T>
  659. using movable_cast_op_type =
  660. conditional_t<std::is_pointer<typename std::remove_reference<T>::type>::value,
  661. typename std::add_pointer<intrinsic_t<T>>::type,
  662. conditional_t<std::is_rvalue_reference<T>::value,
  663. typename std::add_rvalue_reference<intrinsic_t<T>>::type,
  664. typename std::add_lvalue_reference<intrinsic_t<T>>::type>>;
  665. // std::is_copy_constructible isn't quite enough: it lets std::vector<T> (and similar) through when
  666. // T is non-copyable, but code containing such a copy constructor fails to actually compile.
  667. template <typename T, typename SFINAE = void> struct is_copy_constructible : std::is_copy_constructible<T> {};
  668. // Specialization for types that appear to be copy constructible but also look like stl containers
  669. // (we specifically check for: has `value_type` and `reference` with `reference = value_type&`): if
  670. // so, copy constructability depends on whether the value_type is copy constructible.
  671. template <typename Container> struct is_copy_constructible<Container, enable_if_t<
  672. std::is_copy_constructible<Container>::value &&
  673. std::is_same<typename Container::value_type &, typename Container::reference>::value
  674. >> : std::is_copy_constructible<typename Container::value_type> {};
  675. /// Generic type caster for objects stored on the heap
  676. template <typename type> class type_caster_base : public type_caster_generic {
  677. using itype = intrinsic_t<type>;
  678. public:
  679. static PYBIND11_DESCR name() { return type_descr(_<type>()); }
  680. type_caster_base() : type_caster_base(typeid(type)) { }
  681. explicit type_caster_base(const std::type_info &info) : type_caster_generic(info) { }
  682. static handle cast(const itype &src, return_value_policy policy, handle parent) {
  683. if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference)
  684. policy = return_value_policy::copy;
  685. return cast(&src, policy, parent);
  686. }
  687. static handle cast(itype &&src, return_value_policy, handle parent) {
  688. return cast(&src, return_value_policy::move, parent);
  689. }
  690. // Returns a (pointer, type_info) pair taking care of necessary RTTI type lookup for a
  691. // polymorphic type. If the instance isn't derived, returns the non-RTTI base version.
  692. template <typename T = itype, enable_if_t<std::is_polymorphic<T>::value, int> = 0>
  693. static std::pair<const void *, const type_info *> src_and_type(const itype *src) {
  694. const void *vsrc = src;
  695. auto &internals = get_internals();
  696. auto &cast_type = typeid(itype);
  697. const std::type_info *instance_type = nullptr;
  698. if (vsrc) {
  699. instance_type = &typeid(*src);
  700. if (!same_type(cast_type, *instance_type)) {
  701. // This is a base pointer to a derived type; if it is a pybind11-registered type, we
  702. // can get the correct derived pointer (which may be != base pointer) by a
  703. // dynamic_cast to most derived type:
  704. auto it = internals.registered_types_cpp.find(std::type_index(*instance_type));
  705. if (it != internals.registered_types_cpp.end())
  706. return {dynamic_cast<const void *>(src), (const type_info *) it->second};
  707. }
  708. }
  709. // Otherwise we have either a nullptr, an `itype` pointer, or an unknown derived pointer, so
  710. // don't do a cast
  711. return type_caster_generic::src_and_type(vsrc, cast_type, instance_type);
  712. }
  713. // Non-polymorphic type, so no dynamic casting; just call the generic version directly
  714. template <typename T = itype, enable_if_t<!std::is_polymorphic<T>::value, int> = 0>
  715. static std::pair<const void *, const type_info *> src_and_type(const itype *src) {
  716. return type_caster_generic::src_and_type(src, typeid(itype));
  717. }
  718. static handle cast(const itype *src, return_value_policy policy, handle parent) {
  719. auto st = src_and_type(src);
  720. return type_caster_generic::cast(
  721. st.first, policy, parent, st.second,
  722. make_copy_constructor(src), make_move_constructor(src));
  723. }
  724. static handle cast_holder(const itype *src, const void *holder) {
  725. auto st = src_and_type(src);
  726. return type_caster_generic::cast(
  727. st.first, return_value_policy::take_ownership, {}, st.second,
  728. nullptr, nullptr, holder);
  729. }
  730. template <typename T> using cast_op_type = cast_op_type<T>;
  731. operator itype*() { return (type *) value; }
  732. operator itype&() { if (!value) throw reference_cast_error(); return *((itype *) value); }
  733. protected:
  734. using Constructor = void *(*)(const void *);
  735. /* Only enabled when the types are {copy,move}-constructible *and* when the type
  736. does not have a private operator new implementation. */
  737. template <typename T, typename = enable_if_t<is_copy_constructible<T>::value>>
  738. static auto make_copy_constructor(const T *x) -> decltype(new T(*x), Constructor{}) {
  739. return [](const void *arg) -> void * {
  740. return new T(*reinterpret_cast<const T *>(arg));
  741. };
  742. }
  743. template <typename T, typename = enable_if_t<std::is_move_constructible<T>::value>>
  744. static auto make_move_constructor(const T *x) -> decltype(new T(std::move(*const_cast<T *>(x))), Constructor{}) {
  745. return [](const void *arg) -> void * {
  746. return new T(std::move(*const_cast<T *>(reinterpret_cast<const T *>(arg))));
  747. };
  748. }
  749. static Constructor make_copy_constructor(...) { return nullptr; }
  750. static Constructor make_move_constructor(...) { return nullptr; }
  751. };
  752. template <typename type, typename SFINAE = void> class type_caster : public type_caster_base<type> { };
  753. template <typename type> using make_caster = type_caster<intrinsic_t<type>>;
  754. // Shortcut for calling a caster's `cast_op_type` cast operator for casting a type_caster to a T
  755. template <typename T> typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) {
  756. return caster.operator typename make_caster<T>::template cast_op_type<T>();
  757. }
  758. template <typename T> typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>
  759. cast_op(make_caster<T> &&caster) {
  760. return std::move(caster).operator
  761. typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>();
  762. }
  763. template <typename type> class type_caster<std::reference_wrapper<type>> {
  764. private:
  765. using caster_t = make_caster<type>;
  766. caster_t subcaster;
  767. using subcaster_cast_op_type = typename caster_t::template cast_op_type<type>;
  768. static_assert(std::is_same<typename std::remove_const<type>::type &, subcaster_cast_op_type>::value,
  769. "std::reference_wrapper<T> caster requires T to have a caster with an `T &` operator");
  770. public:
  771. bool load(handle src, bool convert) { return subcaster.load(src, convert); }
  772. static PYBIND11_DESCR name() { return caster_t::name(); }
  773. static handle cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) {
  774. // It is definitely wrong to take ownership of this pointer, so mask that rvp
  775. if (policy == return_value_policy::take_ownership || policy == return_value_policy::automatic)
  776. policy = return_value_policy::automatic_reference;
  777. return caster_t::cast(&src.get(), policy, parent);
  778. }
  779. template <typename T> using cast_op_type = std::reference_wrapper<type>;
  780. operator std::reference_wrapper<type>() { return subcaster.operator subcaster_cast_op_type&(); }
  781. };
  782. #define PYBIND11_TYPE_CASTER(type, py_name) \
  783. protected: \
  784. type value; \
  785. public: \
  786. static PYBIND11_DESCR name() { return type_descr(py_name); } \
  787. template <typename T_, enable_if_t<std::is_same<type, remove_cv_t<T_>>::value, int> = 0> \
  788. static handle cast(T_ *src, return_value_policy policy, handle parent) { \
  789. if (!src) return none().release(); \
  790. if (policy == return_value_policy::take_ownership) { \
  791. auto h = cast(std::move(*src), policy, parent); delete src; return h; \
  792. } else { \
  793. return cast(*src, policy, parent); \
  794. } \
  795. } \
  796. operator type*() { return &value; } \
  797. operator type&() { return value; } \
  798. operator type&&() && { return std::move(value); } \
  799. template <typename T_> using cast_op_type = pybind11::detail::movable_cast_op_type<T_>
  800. template <typename CharT> using is_std_char_type = any_of<
  801. std::is_same<CharT, char>, /* std::string */
  802. std::is_same<CharT, char16_t>, /* std::u16string */
  803. std::is_same<CharT, char32_t>, /* std::u32string */
  804. std::is_same<CharT, wchar_t> /* std::wstring */
  805. >;
  806. template <typename T>
  807. struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_type<T>::value>> {
  808. using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>;
  809. using _py_type_1 = conditional_t<std::is_signed<T>::value, _py_type_0, typename std::make_unsigned<_py_type_0>::type>;
  810. using py_type = conditional_t<std::is_floating_point<T>::value, double, _py_type_1>;
  811. public:
  812. bool load(handle src, bool convert) {
  813. py_type py_value;
  814. if (!src)
  815. return false;
  816. if (std::is_floating_point<T>::value) {
  817. if (convert || PyFloat_Check(src.ptr()))
  818. py_value = (py_type) PyFloat_AsDouble(src.ptr());
  819. else
  820. return false;
  821. } else if (PyFloat_Check(src.ptr())) {
  822. return false;
  823. } else if (std::is_unsigned<py_type>::value) {
  824. py_value = as_unsigned<py_type>(src.ptr());
  825. } else { // signed integer:
  826. py_value = sizeof(T) <= sizeof(long)
  827. ? (py_type) PyLong_AsLong(src.ptr())
  828. : (py_type) PYBIND11_LONG_AS_LONGLONG(src.ptr());
  829. }
  830. bool py_err = py_value == (py_type) -1 && PyErr_Occurred();
  831. if (py_err || (std::is_integral<T>::value && sizeof(py_type) != sizeof(T) &&
  832. (py_value < (py_type) std::numeric_limits<T>::min() ||
  833. py_value > (py_type) std::numeric_limits<T>::max()))) {
  834. bool type_error = py_err && PyErr_ExceptionMatches(
  835. #if PY_VERSION_HEX < 0x03000000 && !defined(PYPY_VERSION)
  836. PyExc_SystemError
  837. #else
  838. PyExc_TypeError
  839. #endif
  840. );
  841. PyErr_Clear();
  842. if (type_error && convert && PyNumber_Check(src.ptr())) {
  843. auto tmp = reinterpret_borrow<object>(std::is_floating_point<T>::value
  844. ? PyNumber_Float(src.ptr())
  845. : PyNumber_Long(src.ptr()));
  846. PyErr_Clear();
  847. return load(tmp, false);
  848. }
  849. return false;
  850. }
  851. value = (T) py_value;
  852. return true;
  853. }
  854. static handle cast(T src, return_value_policy /* policy */, handle /* parent */) {
  855. if (std::is_floating_point<T>::value) {
  856. return PyFloat_FromDouble((double) src);
  857. } else if (sizeof(T) <= sizeof(long)) {
  858. if (std::is_signed<T>::value)
  859. return PyLong_FromLong((long) src);
  860. else
  861. return PyLong_FromUnsignedLong((unsigned long) src);
  862. } else {
  863. if (std::is_signed<T>::value)
  864. return PyLong_FromLongLong((long long) src);
  865. else
  866. return PyLong_FromUnsignedLongLong((unsigned long long) src);
  867. }
  868. }
  869. PYBIND11_TYPE_CASTER(T, _<std::is_integral<T>::value>("int", "float"));
  870. };
  871. template<typename T> struct void_caster {
  872. public:
  873. bool load(handle src, bool) {
  874. if (src && src.is_none())
  875. return true;
  876. return false;
  877. }
  878. static handle cast(T, return_value_policy /* policy */, handle /* parent */) {
  879. return none().inc_ref();
  880. }
  881. PYBIND11_TYPE_CASTER(T, _("None"));
  882. };
  883. template <> class type_caster<void_type> : public void_caster<void_type> {};
  884. template <> class type_caster<void> : public type_caster<void_type> {
  885. public:
  886. using type_caster<void_type>::cast;
  887. bool load(handle h, bool) {
  888. if (!h) {
  889. return false;
  890. } else if (h.is_none()) {
  891. value = nullptr;
  892. return true;
  893. }
  894. /* Check if this is a capsule */
  895. if (isinstance<capsule>(h)) {
  896. value = reinterpret_borrow<capsule>(h);
  897. return true;
  898. }
  899. /* Check if this is a C++ type */
  900. auto &bases = all_type_info((PyTypeObject *) h.get_type().ptr());
  901. if (bases.size() == 1) { // Only allowing loading from a single-value type
  902. value = values_and_holders(reinterpret_cast<instance *>(h.ptr())).begin()->value_ptr();
  903. return true;
  904. }
  905. /* Fail */
  906. return false;
  907. }
  908. static handle cast(const void *ptr, return_value_policy /* policy */, handle /* parent */) {
  909. if (ptr)
  910. return capsule(ptr).release();
  911. else
  912. return none().inc_ref();
  913. }
  914. template <typename T> using cast_op_type = void*&;
  915. operator void *&() { return value; }
  916. static PYBIND11_DESCR name() { return type_descr(_("capsule")); }
  917. private:
  918. void *value = nullptr;
  919. };
  920. template <> class type_caster<std::nullptr_t> : public void_caster<std::nullptr_t> { };
  921. template <> class type_caster<bool> {
  922. public:
  923. bool load(handle src, bool) {
  924. if (!src) return false;
  925. else if (src.ptr() == Py_True) { value = true; return true; }
  926. else if (src.ptr() == Py_False) { value = false; return true; }
  927. else return false;
  928. }
  929. static handle cast(bool src, return_value_policy /* policy */, handle /* parent */) {
  930. return handle(src ? Py_True : Py_False).inc_ref();
  931. }
  932. PYBIND11_TYPE_CASTER(bool, _("bool"));
  933. };
  934. // Helper class for UTF-{8,16,32} C++ stl strings:
  935. template <typename StringType, bool IsView = false> struct string_caster {
  936. using CharT = typename StringType::value_type;
  937. // Simplify life by being able to assume standard char sizes (the standard only guarantees
  938. // minimums, but Python requires exact sizes)
  939. static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1, "Unsupported char size != 1");
  940. static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2, "Unsupported char16_t size != 2");
  941. static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4, "Unsupported char32_t size != 4");
  942. // wchar_t can be either 16 bits (Windows) or 32 (everywhere else)
  943. static_assert(!std::is_same<CharT, wchar_t>::value || sizeof(CharT) == 2 || sizeof(CharT) == 4,
  944. "Unsupported wchar_t size != 2/4");
  945. static constexpr size_t UTF_N = 8 * sizeof(CharT);
  946. bool load(handle src, bool) {
  947. #if PY_MAJOR_VERSION < 3
  948. object temp;
  949. #endif
  950. handle load_src = src;
  951. if (!src) {
  952. return false;
  953. } else if (!PyUnicode_Check(load_src.ptr())) {
  954. #if PY_MAJOR_VERSION >= 3
  955. return load_bytes(load_src);
  956. #else
  957. if (sizeof(CharT) == 1) {
  958. return load_bytes(load_src);
  959. }
  960. // The below is a guaranteed failure in Python 3 when PyUnicode_Check returns false
  961. if (!PYBIND11_BYTES_CHECK(load_src.ptr()))
  962. return false;
  963. temp = reinterpret_steal<object>(PyUnicode_FromObject(load_src.ptr()));
  964. if (!temp) { PyErr_Clear(); return false; }
  965. load_src = temp;
  966. #endif
  967. }
  968. object utfNbytes = reinterpret_steal<object>(PyUnicode_AsEncodedString(
  969. load_src.ptr(), UTF_N == 8 ? "utf-8" : UTF_N == 16 ? "utf-16" : "utf-32", nullptr));
  970. if (!utfNbytes) { PyErr_Clear(); return false; }
  971. const CharT *buffer = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
  972. size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.ptr()) / sizeof(CharT);
  973. if (UTF_N > 8) { buffer++; length--; } // Skip BOM for UTF-16/32
  974. value = StringType(buffer, length);
  975. // If we're loading a string_view we need to keep the encoded Python object alive:
  976. if (IsView)
  977. loader_life_support::add_patient(utfNbytes);
  978. return true;
  979. }
  980. static handle cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) {
  981. const char *buffer = reinterpret_cast<const char *>(src.data());
  982. ssize_t nbytes = ssize_t(src.size() * sizeof(CharT));
  983. handle s = decode_utfN(buffer, nbytes);
  984. if (!s) throw error_already_set();
  985. return s;
  986. }
  987. PYBIND11_TYPE_CASTER(StringType, _(PYBIND11_STRING_NAME));
  988. private:
  989. static handle decode_utfN(const char *buffer, ssize_t nbytes) {
  990. #if !defined(PYPY_VERSION)
  991. return
  992. UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr) :
  993. UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr) :
  994. PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);
  995. #else
  996. // PyPy seems to have multiple problems related to PyUnicode_UTF*: the UTF8 version
  997. // sometimes segfaults for unknown reasons, while the UTF16 and 32 versions require a
  998. // non-const char * arguments, which is also a nuissance, so bypass the whole thing by just
  999. // passing the encoding as a string value, which works properly:
  1000. return PyUnicode_Decode(buffer, nbytes, UTF_N == 8 ? "utf-8" : UTF_N == 16 ? "utf-16" : "utf-32", nullptr);
  1001. #endif
  1002. }
  1003. // When loading into a std::string or char*, accept a bytes object as-is (i.e.
  1004. // without any encoding/decoding attempt). For other C++ char sizes this is a no-op.
  1005. // which supports loading a unicode from a str, doesn't take this path.
  1006. template <typename C = CharT>
  1007. bool load_bytes(enable_if_t<sizeof(C) == 1, handle> src) {
  1008. if (PYBIND11_BYTES_CHECK(src.ptr())) {
  1009. // We were passed a Python 3 raw bytes; accept it into a std::string or char*
  1010. // without any encoding attempt.
  1011. const char *bytes = PYBIND11_BYTES_AS_STRING(src.ptr());
  1012. if (bytes) {
  1013. value = StringType(bytes, (size_t) PYBIND11_BYTES_SIZE(src.ptr()));
  1014. return true;
  1015. }
  1016. }
  1017. return false;
  1018. }
  1019. template <typename C = CharT>
  1020. bool load_bytes(enable_if_t<sizeof(C) != 1, handle>) { return false; }
  1021. };
  1022. template <typename CharT, class Traits, class Allocator>
  1023. struct type_caster<std::basic_string<CharT, Traits, Allocator>, enable_if_t<is_std_char_type<CharT>::value>>
  1024. : string_caster<std::basic_string<CharT, Traits, Allocator>> {};
  1025. #ifdef PYBIND11_HAS_STRING_VIEW
  1026. template <typename CharT, class Traits>
  1027. struct type_caster<std::basic_string_view<CharT, Traits>, enable_if_t<is_std_char_type<CharT>::value>>
  1028. : string_caster<std::basic_string_view<CharT, Traits>, true> {};
  1029. #endif
  1030. // Type caster for C-style strings. We basically use a std::string type caster, but also add the
  1031. // ability to use None as a nullptr char* (which the string caster doesn't allow).
  1032. template <typename CharT> struct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> {
  1033. using StringType = std::basic_string<CharT>;
  1034. using StringCaster = type_caster<StringType>;
  1035. StringCaster str_caster;
  1036. bool none = false;
  1037. public:
  1038. bool load(handle src, bool convert) {
  1039. if (!src) return false;
  1040. if (src.is_none()) {
  1041. // Defer accepting None to other overloads (if we aren't in convert mode):
  1042. if (!convert) return false;
  1043. none = true;
  1044. return true;
  1045. }
  1046. return str_caster.load(src, convert);
  1047. }
  1048. static handle cast(const CharT *src, return_value_policy policy, handle parent) {
  1049. if (src == nullptr) return pybind11::none().inc_ref();
  1050. return StringCaster::cast(StringType(src), policy, parent);
  1051. }
  1052. static handle cast(CharT src, return_value_policy policy, handle parent) {
  1053. if (std::is_same<char, CharT>::value) {
  1054. handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr);
  1055. if (!s) throw error_already_set();
  1056. return s;
  1057. }
  1058. return StringCaster::cast(StringType(1, src), policy, parent);
  1059. }
  1060. operator CharT*() { return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str()); }
  1061. operator CharT() {
  1062. if (none)
  1063. throw value_error("Cannot convert None to a character");
  1064. auto &value = static_cast<StringType &>(str_caster);
  1065. size_t str_len = value.size();
  1066. if (str_len == 0)
  1067. throw value_error("Cannot convert empty string to a character");
  1068. // If we're in UTF-8 mode, we have two possible failures: one for a unicode character that
  1069. // is too high, and one for multiple unicode characters (caught later), so we need to figure
  1070. // out how long the first encoded character is in bytes to distinguish between these two
  1071. // errors. We also allow want to allow unicode characters U+0080 through U+00FF, as those
  1072. // can fit into a single char value.
  1073. if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) {
  1074. unsigned char v0 = static_cast<unsigned char>(value[0]);
  1075. size_t char0_bytes = !(v0 & 0x80) ? 1 : // low bits only: 0-127
  1076. (v0 & 0xE0) == 0xC0 ? 2 : // 0b110xxxxx - start of 2-byte sequence
  1077. (v0 & 0xF0) == 0xE0 ? 3 : // 0b1110xxxx - start of 3-byte sequence
  1078. 4; // 0b11110xxx - start of 4-byte sequence
  1079. if (char0_bytes == str_len) {
  1080. // If we have a 128-255 value, we can decode it into a single char:
  1081. if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) { // 0x110000xx 0x10xxxxxx
  1082. return static_cast<CharT>(((v0 & 3) << 6) + (static_cast<unsigned char>(value[1]) & 0x3F));
  1083. }
  1084. // Otherwise we have a single character, but it's > U+00FF
  1085. throw value_error("Character code point not in range(0x100)");
  1086. }
  1087. }
  1088. // UTF-16 is much easier: we can only have a surrogate pair for values above U+FFFF, thus a
  1089. // surrogate pair with total length 2 instantly indicates a range error (but not a "your
  1090. // string was too long" error).
  1091. else if (StringCaster::UTF_N == 16 && str_len == 2) {
  1092. char16_t v0 = static_cast<char16_t>(value[0]);
  1093. if (v0 >= 0xD800 && v0 < 0xE000)
  1094. throw value_error("Character code point not in range(0x10000)");
  1095. }
  1096. if (str_len != 1)
  1097. throw value_error("Expected a character, but multi-character string found");
  1098. return value[0];
  1099. }
  1100. static PYBIND11_DESCR name() { return type_descr(_(PYBIND11_STRING_NAME)); }
  1101. template <typename _T> using cast_op_type = remove_reference_t<pybind11::detail::cast_op_type<_T>>;
  1102. };
  1103. // Base implementation for std::tuple and std::pair
  1104. template <template<typename...> class Tuple, typename... Ts> class tuple_caster {
  1105. using type = Tuple<Ts...>;
  1106. static constexpr auto size = sizeof...(Ts);
  1107. using indices = make_index_sequence<size>;
  1108. public:
  1109. bool load(handle src, bool convert) {
  1110. if (!isinstance<sequence>(src))
  1111. return false;
  1112. const auto seq = reinterpret_borrow<sequence>(src);
  1113. if (seq.size() != size)
  1114. return false;
  1115. return load_impl(seq, convert, indices{});
  1116. }
  1117. template <typename T>
  1118. static handle cast(T &&src, return_value_policy policy, handle parent) {
  1119. return cast_impl(std::forward<T>(src), policy, parent, indices{});
  1120. }
  1121. static PYBIND11_DESCR name() {
  1122. return type_descr(_("Tuple[") + detail::concat(make_caster<Ts>::name()...) + _("]"));
  1123. }
  1124. template <typename T> using cast_op_type = type;
  1125. operator type() & { return implicit_cast(indices{}); }
  1126. operator type() && { return std::move(*this).implicit_cast(indices{}); }
  1127. protected:
  1128. template <size_t... Is>
  1129. type implicit_cast(index_sequence<Is...>) & { return type(cast_op<Ts>(std::get<Is>(subcasters))...); }
  1130. template <size_t... Is>
  1131. type implicit_cast(index_sequence<Is...>) && { return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...); }
  1132. static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; }
  1133. template <size_t... Is>
  1134. bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {
  1135. for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...})
  1136. if (!r)
  1137. return false;
  1138. return true;
  1139. }
  1140. /* Implementation: Convert a C++ tuple into a Python tuple */
  1141. template <typename T, size_t... Is>
  1142. static handle cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence<Is...>) {
  1143. std::array<object, size> entries{{
  1144. reinterpret_steal<object>(make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...
  1145. }};
  1146. for (const auto &entry: entries)
  1147. if (!entry)
  1148. return handle();
  1149. tuple result(size);
  1150. int counter = 0;
  1151. for (auto & entry: entries)
  1152. PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());
  1153. return result.release();
  1154. }
  1155. Tuple<make_caster<Ts>...> subcasters;
  1156. };
  1157. template <typename T1, typename T2> class type_caster<std::pair<T1, T2>>
  1158. : public tuple_caster<std::pair, T1, T2> {};
  1159. template <typename... Ts> class type_caster<std::tuple<Ts...>>
  1160. : public tuple_caster<std::tuple, Ts...> {};
  1161. /// Helper class which abstracts away certain actions. Users can provide specializations for
  1162. /// custom holders, but it's only necessary if the type has a non-standard interface.
  1163. template <typename T>
  1164. struct holder_helper {
  1165. static auto get(const T &p) -> decltype(p.get()) { return p.get(); }
  1166. };
  1167. /// Type caster for holder types like std::shared_ptr, etc.
  1168. template <typename type, typename holder_type>
  1169. struct copyable_holder_caster : public type_caster_base<type> {
  1170. public:
  1171. using base = type_caster_base<type>;
  1172. static_assert(std::is_base_of<base, type_caster<type>>::value,
  1173. "Holder classes are only supported for custom types");
  1174. using base::base;
  1175. using base::cast;
  1176. using base::typeinfo;
  1177. using base::value;
  1178. bool load(handle src, bool convert) {
  1179. return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
  1180. }
  1181. explicit operator type*() { return this->value; }
  1182. explicit operator type&() { return *(this->value); }
  1183. explicit operator holder_type*() { return &holder; }
  1184. // Workaround for Intel compiler bug
  1185. // see pybind11 issue 94
  1186. #if defined(__ICC) || defined(__INTEL_COMPILER)
  1187. operator holder_type&() { return holder; }
  1188. #else
  1189. explicit operator holder_type&() { return holder; }
  1190. #endif
  1191. static handle cast(const holder_type &src, return_value_policy, handle) {
  1192. const auto *ptr = holder_helper<holder_type>::get(src);
  1193. return type_caster_base<type>::cast_holder(ptr, &src);
  1194. }
  1195. protected:
  1196. friend class type_caster_generic;
  1197. void check_holder_compat() {
  1198. if (typeinfo->default_holder)
  1199. throw cast_error("Unable to load a custom holder type from a default-holder instance");
  1200. }
  1201. bool load_value(const value_and_holder &v_h) {
  1202. if (v_h.holder_constructed()) {
  1203. value = v_h.value_ptr();
  1204. holder = v_h.holder<holder_type>();
  1205. return true;
  1206. } else {
  1207. throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
  1208. #if defined(NDEBUG)
  1209. "(compile in debug mode for type information)");
  1210. #else
  1211. "of type '" + type_id<holder_type>() + "''");
  1212. #endif
  1213. }
  1214. }
  1215. template <typename T = holder_type, detail::enable_if_t<!std::is_constructible<T, const T &, type*>::value, int> = 0>
  1216. bool try_implicit_casts(handle, bool) { return false; }
  1217. template <typename T = holder_type, detail::enable_if_t<std::is_constructible<T, const T &, type*>::value, int> = 0>
  1218. bool try_implicit_casts(handle src, bool convert) {
  1219. for (auto &cast : typeinfo->implicit_casts) {
  1220. copyable_holder_caster sub_caster(*cast.first);
  1221. if (sub_caster.load(src, convert)) {
  1222. value = cast.second(sub_caster.value);
  1223. holder = holder_type(sub_caster.holder, (type *) value);
  1224. return true;
  1225. }
  1226. }
  1227. return false;
  1228. }
  1229. static bool try_direct_conversions(handle) { return false; }
  1230. holder_type holder;
  1231. };
  1232. /// Specialize for the common std::shared_ptr, so users don't need to
  1233. template <typename T>
  1234. class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> { };
  1235. template <typename type, typename holder_type>
  1236. struct move_only_holder_caster {
  1237. static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value,
  1238. "Holder classes are only supported for custom types");
  1239. static handle cast(holder_type &&src, return_value_policy, handle) {
  1240. auto *ptr = holder_helper<holder_type>::get(src);
  1241. return type_caster_base<type>::cast_holder(ptr, &src);
  1242. }
  1243. static PYBIND11_DESCR name() { return type_caster_base<type>::name(); }
  1244. };
  1245. template <typename type, typename deleter>
  1246. class type_caster<std::unique_ptr<type, deleter>>
  1247. : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> { };
  1248. template <typename type, typename holder_type>
  1249. using type_caster_holder = conditional_t<std::is_copy_constructible<holder_type>::value,
  1250. copyable_holder_caster<type, holder_type>,
  1251. move_only_holder_caster<type, holder_type>>;
  1252. template <typename T, bool Value = false> struct always_construct_holder { static constexpr bool value = Value; };
  1253. /// Create a specialization for custom holder types (silently ignores std::shared_ptr)
  1254. #define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
  1255. namespace pybind11 { namespace detail { \
  1256. template <typename type> \
  1257. struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__> { }; \
  1258. template <typename type> \
  1259. class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
  1260. : public type_caster_holder<type, holder_type> { }; \
  1261. }}
  1262. // PYBIND11_DECLARE_HOLDER_TYPE holder types:
  1263. template <typename base, typename holder> struct is_holder_type :
  1264. std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
  1265. // Specialization for always-supported unique_ptr holders:
  1266. template <typename base, typename deleter> struct is_holder_type<base, std::unique_ptr<base, deleter>> :
  1267. std::true_type {};
  1268. template <typename T> struct handle_type_name { static PYBIND11_DESCR name() { return _<T>(); } };
  1269. template <> struct handle_type_name<bytes> { static PYBIND11_DESCR name() { return _(PYBIND11_BYTES_NAME); } };
  1270. template <> struct handle_type_name<args> { static PYBIND11_DESCR name() { return _("*args"); } };
  1271. template <> struct handle_type_name<kwargs> { static PYBIND11_DESCR name() { return _("**kwargs"); } };
  1272. template <typename type>
  1273. struct pyobject_caster {
  1274. template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
  1275. bool load(handle src, bool /* convert */) { value = src; return static_cast<bool>(value); }
  1276. template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
  1277. bool load(handle src, bool /* convert */) {
  1278. if (!isinstance<type>(src))
  1279. return false;
  1280. value = reinterpret_borrow<type>(src);
  1281. return true;
  1282. }
  1283. static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
  1284. return src.inc_ref();
  1285. }
  1286. PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name());
  1287. };
  1288. template <typename T>
  1289. class type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> { };
  1290. // Our conditions for enabling moving are quite restrictive:
  1291. // At compile time:
  1292. // - T needs to be a non-const, non-pointer, non-reference type
  1293. // - type_caster<T>::operator T&() must exist
  1294. // - the type must be move constructible (obviously)
  1295. // At run-time:
  1296. // - if the type is non-copy-constructible, the object must be the sole owner of the type (i.e. it
  1297. // must have ref_count() == 1)h
  1298. // If any of the above are not satisfied, we fall back to copying.
  1299. template <typename T> using move_is_plain_type = satisfies_none_of<T,
  1300. std::is_void, std::is_pointer, std::is_reference, std::is_const
  1301. >;
  1302. template <typename T, typename SFINAE = void> struct move_always : std::false_type {};
  1303. template <typename T> struct move_always<T, enable_if_t<all_of<
  1304. move_is_plain_type<T>,
  1305. negation<std::is_copy_constructible<T>>,
  1306. std::is_move_constructible<T>,
  1307. std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&>
  1308. >::value>> : std::true_type {};
  1309. template <typename T, typename SFINAE = void> struct move_if_unreferenced : std::false_type {};
  1310. template <typename T> struct move_if_unreferenced<T, enable_if_t<all_of<
  1311. move_is_plain_type<T>,
  1312. negation<move_always<T>>,
  1313. std::is_move_constructible<T>,
  1314. std::is_same<decltype(std::declval<make_caster<T>>().operator T&()), T&>
  1315. >::value>> : std::true_type {};
  1316. template <typename T> using move_never = none_of<move_always<T>, move_if_unreferenced<T>>;
  1317. // Detect whether returning a `type` from a cast on type's type_caster is going to result in a
  1318. // reference or pointer to a local variable of the type_caster. Basically, only
  1319. // non-reference/pointer `type`s and reference/pointers from a type_caster_generic are safe;
  1320. // everything else returns a reference/pointer to a local variable.
  1321. template <typename type> using cast_is_temporary_value_reference = bool_constant<
  1322. (std::is_reference<type>::value || std::is_pointer<type>::value) &&
  1323. !std::is_base_of<type_caster_generic, make_caster<type>>::value
  1324. >;
  1325. // When a value returned from a C++ function is being cast back to Python, we almost always want to
  1326. // force `policy = move`, regardless of the return value policy the function/method was declared
  1327. // with. Some classes (most notably Eigen::Ref and related) need to avoid this, and so can do so by
  1328. // specializing this struct.
  1329. template <typename Return, typename SFINAE = void> struct return_value_policy_override {
  1330. static return_value_policy policy(return_value_policy p) {
  1331. return !std::is_lvalue_reference<Return>::value && !std::is_pointer<Return>::value
  1332. ? return_value_policy::move : p;
  1333. }
  1334. };
  1335. // Basic python -> C++ casting; throws if casting fails
  1336. template <typename T, typename SFINAE> type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {
  1337. if (!conv.load(handle, true)) {
  1338. #if defined(NDEBUG)
  1339. throw cast_error("Unable to cast Python instance to C++ type (compile in debug mode for details)");
  1340. #else
  1341. throw cast_error("Unable to cast Python instance of type " +
  1342. (std::string) str(handle.get_type()) + " to C++ type '" + type_id<T>() + "''");
  1343. #endif
  1344. }
  1345. return conv;
  1346. }
  1347. // Wrapper around the above that also constructs and returns a type_caster
  1348. template <typename T> make_caster<T> load_type(const handle &handle) {
  1349. make_caster<T> conv;
  1350. load_type(conv, handle);
  1351. return conv;
  1352. }
  1353. NAMESPACE_END(detail)
  1354. // pytype -> C++ type
  1355. template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
  1356. T cast(const handle &handle) {
  1357. using namespace detail;
  1358. static_assert(!cast_is_temporary_value_reference<T>::value,
  1359. "Unable to cast type to reference: value is local to type caster");
  1360. return cast_op<T>(load_type<T>(handle));
  1361. }
  1362. // pytype -> pytype (calls converting constructor)
  1363. template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
  1364. T cast(const handle &handle) { return T(reinterpret_borrow<object>(handle)); }
  1365. // C++ type -> py::object
  1366. template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
  1367. object cast(const T &value, return_value_policy policy = return_value_policy::automatic_reference,
  1368. handle parent = handle()) {
  1369. if (policy == return_value_policy::automatic)
  1370. policy = std::is_pointer<T>::value ? return_value_policy::take_ownership : return_value_policy::copy;
  1371. else if (policy == return_value_policy::automatic_reference)
  1372. policy = std::is_pointer<T>::value ? return_value_policy::reference : return_value_policy::copy;
  1373. return reinterpret_steal<object>(detail::make_caster<T>::cast(value, policy, parent));
  1374. }
  1375. template <typename T> T handle::cast() const { return pybind11::cast<T>(*this); }
  1376. template <> inline void handle::cast() const { return; }
  1377. template <typename T>
  1378. detail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) {
  1379. if (obj.ref_count() > 1)
  1380. #if defined(NDEBUG)
  1381. throw cast_error("Unable to cast Python instance to C++ rvalue: instance has multiple references"
  1382. " (compile in debug mode for details)");
  1383. #else
  1384. throw cast_error("Unable to move from Python " + (std::string) str(obj.get_type()) +
  1385. " instance to C++ " + type_id<T>() + " instance: instance has multiple references");
  1386. #endif
  1387. // Move into a temporary and return that, because the reference may be a local value of `conv`
  1388. T ret = std::move(detail::load_type<T>(obj).operator T&());
  1389. return ret;
  1390. }
  1391. // Calling cast() on an rvalue calls pybind::cast with the object rvalue, which does:
  1392. // - If we have to move (because T has no copy constructor), do it. This will fail if the moved
  1393. // object has multiple references, but trying to copy will fail to compile.
  1394. // - If both movable and copyable, check ref count: if 1, move; otherwise copy
  1395. // - Otherwise (not movable), copy.
  1396. template <typename T> detail::enable_if_t<detail::move_always<T>::value, T> cast(object &&object) {
  1397. return move<T>(std::move(object));
  1398. }
  1399. template <typename T> detail::enable_if_t<detail::move_if_unreferenced<T>::value, T> cast(object &&object) {
  1400. if (object.ref_count() > 1)
  1401. return cast<T>(object);
  1402. else
  1403. return move<T>(std::move(object));
  1404. }
  1405. template <typename T> detail::enable_if_t<detail::move_never<T>::value, T> cast(object &&object) {
  1406. return cast<T>(object);
  1407. }
  1408. template <typename T> T object::cast() const & { return pybind11::cast<T>(*this); }
  1409. template <typename T> T object::cast() && { return pybind11::cast<T>(std::move(*this)); }
  1410. template <> inline void object::cast() const & { return; }
  1411. template <> inline void object::cast() && { return; }
  1412. NAMESPACE_BEGIN(detail)
  1413. // Declared in pytypes.h:
  1414. template <typename T, enable_if_t<!is_pyobject<T>::value, int>>
  1415. object object_or_cast(T &&o) { return pybind11::cast(std::forward<T>(o)); }
  1416. struct overload_unused {}; // Placeholder type for the unneeded (and dead code) static variable in the OVERLOAD_INT macro
  1417. template <typename ret_type> using overload_caster_t = conditional_t<
  1418. cast_is_temporary_value_reference<ret_type>::value, make_caster<ret_type>, overload_unused>;
  1419. // Trampoline use: for reference/pointer types to value-converted values, we do a value cast, then
  1420. // store the result in the given variable. For other types, this is a no-op.
  1421. template <typename T> enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o, make_caster<T> &caster) {
  1422. return cast_op<T>(load_type(caster, o));
  1423. }
  1424. template <typename T> enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&, overload_unused &) {
  1425. pybind11_fail("Internal error: cast_ref fallback invoked"); }
  1426. // Trampoline use: Having a pybind11::cast with an invalid reference type is going to static_assert, even
  1427. // though if it's in dead code, so we provide a "trampoline" to pybind11::cast that only does anything in
  1428. // cases where pybind11::cast is valid.
  1429. template <typename T> enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&o) {
  1430. return pybind11::cast<T>(std::move(o)); }
  1431. template <typename T> enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&) {
  1432. pybind11_fail("Internal error: cast_safe fallback invoked"); }
  1433. template <> inline void cast_safe<void>(object &&) {}
  1434. NAMESPACE_END(detail)
  1435. template <return_value_policy policy = return_value_policy::automatic_reference,
  1436. typename... Args> tuple make_tuple(Args&&... args_) {
  1437. constexpr size_t size = sizeof...(Args);
  1438. std::array<object, size> args {
  1439. { reinterpret_steal<object>(detail::make_caster<Args>::cast(
  1440. std::forward<Args>(args_), policy, nullptr))... }
  1441. };
  1442. for (size_t i = 0; i < args.size(); i++) {
  1443. if (!args[i]) {
  1444. #if defined(NDEBUG)
  1445. throw cast_error("make_tuple(): unable to convert arguments to Python object (compile in debug mode for details)");
  1446. #else
  1447. std::array<std::string, size> argtypes { {type_id<Args>()...} };
  1448. throw cast_error("make_tuple(): unable to convert argument of type '" +
  1449. argtypes[i] + "' to Python object");
  1450. #endif
  1451. }
  1452. }
  1453. tuple result(size);
  1454. int counter = 0;
  1455. for (auto &arg_value : args)
  1456. PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());
  1457. return result;
  1458. }
  1459. /// \ingroup annotations
  1460. /// Annotation for arguments
  1461. struct arg {
  1462. /// Constructs an argument with the name of the argument; if null or omitted, this is a positional argument.
  1463. constexpr explicit arg(const char *name = nullptr) : name(name), flag_noconvert(false), flag_none(true) { }
  1464. /// Assign a value to this argument
  1465. template <typename T> arg_v operator=(T &&value) const;
  1466. /// Indicate that the type should not be converted in the type caster
  1467. arg &noconvert(bool flag = true) { flag_noconvert = flag; return *this; }
  1468. /// Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args)
  1469. arg &none(bool flag = true) { flag_none = flag; return *this; }
  1470. const char *name; ///< If non-null, this is a named kwargs argument
  1471. bool flag_noconvert : 1; ///< If set, do not allow conversion (requires a supporting type caster!)
  1472. bool flag_none : 1; ///< If set (the default), allow None to be passed to this argument
  1473. };
  1474. /// \ingroup annotations
  1475. /// Annotation for arguments with values
  1476. struct arg_v : arg {
  1477. private:
  1478. template <typename T>
  1479. arg_v(arg &&base, T &&x, const char *descr = nullptr)
  1480. : arg(base),
  1481. value(reinterpret_steal<object>(
  1482. detail::make_caster<T>::cast(x, return_value_policy::automatic, {})
  1483. )),
  1484. descr(descr)
  1485. #if !defined(NDEBUG)
  1486. , type(type_id<T>())
  1487. #endif
  1488. { }
  1489. public:
  1490. /// Direct construction with name, default, and description
  1491. template <typename T>
  1492. arg_v(const char *name, T &&x, const char *descr = nullptr)
  1493. : arg_v(arg(name), std::forward<T>(x), descr) { }
  1494. /// Called internally when invoking `py::arg("a") = value`
  1495. template <typename T>
  1496. arg_v(const arg &base, T &&x, const char *descr = nullptr)
  1497. : arg_v(arg(base), std::forward<T>(x), descr) { }
  1498. /// Same as `arg::noconvert()`, but returns *this as arg_v&, not arg&
  1499. arg_v &noconvert(bool flag = true) { arg::noconvert(flag); return *this; }
  1500. /// Same as `arg::nonone()`, but returns *this as arg_v&, not arg&
  1501. arg_v &none(bool flag = true) { arg::none(flag); return *this; }
  1502. /// The default value
  1503. object value;
  1504. /// The (optional) description of the default value
  1505. const char *descr;
  1506. #if !defined(NDEBUG)
  1507. /// The C++ type name of the default value (only available when compiled in debug mode)
  1508. std::string type;
  1509. #endif
  1510. };
  1511. template <typename T>
  1512. arg_v arg::operator=(T &&value) const { return {std::move(*this), std::forward<T>(value)}; }
  1513. /// Alias for backward compatibility -- to be removed in version 2.0
  1514. template <typename /*unused*/> using arg_t = arg_v;
  1515. inline namespace literals {
  1516. /** \rst
  1517. String literal version of `arg`
  1518. \endrst */
  1519. constexpr arg operator"" _a(const char *name, size_t) { return arg(name); }
  1520. }
  1521. NAMESPACE_BEGIN(detail)
  1522. // forward declaration (definition in attr.h)
  1523. struct function_record;
  1524. /// Internal data associated with a single function call
  1525. struct function_call {
  1526. function_call(function_record &f, handle p); // Implementation in attr.h
  1527. /// The function data:
  1528. const function_record &func;
  1529. /// Arguments passed to the function:
  1530. std::vector<handle> args;
  1531. /// The `convert` value the arguments should be loaded with
  1532. std::vector<bool> args_convert;
  1533. /// The parent, if any
  1534. handle parent;
  1535. };
  1536. /// Helper class which loads arguments for C++ functions called from Python
  1537. template <typename... Args>
  1538. class argument_loader {
  1539. using indices = make_index_sequence<sizeof...(Args)>;
  1540. template <typename Arg> using argument_is_args = std::is_same<intrinsic_t<Arg>, args>;
  1541. template <typename Arg> using argument_is_kwargs = std::is_same<intrinsic_t<Arg>, kwargs>;
  1542. // Get args/kwargs argument positions relative to the end of the argument list:
  1543. static constexpr auto args_pos = constexpr_first<argument_is_args, Args...>() - (int) sizeof...(Args),
  1544. kwargs_pos = constexpr_first<argument_is_kwargs, Args...>() - (int) sizeof...(Args);
  1545. static constexpr bool args_kwargs_are_last = kwargs_pos >= - 1 && args_pos >= kwargs_pos - 1;
  1546. static_assert(args_kwargs_are_last, "py::args/py::kwargs are only permitted as the last argument(s) of a function");
  1547. public:
  1548. static constexpr bool has_kwargs = kwargs_pos < 0;
  1549. static constexpr bool has_args = args_pos < 0;
  1550. static PYBIND11_DESCR arg_names() { return detail::concat(make_caster<Args>::name()...); }
  1551. bool load_args(function_call &call) {
  1552. return load_impl_sequence(call, indices{});
  1553. }
  1554. template <typename Return, typename Guard, typename Func>
  1555. enable_if_t<!std::is_void<Return>::value, Return> call(Func &&f) && {
  1556. return std::move(*this).template call_impl<Return>(std::forward<Func>(f), indices{}, Guard{});
  1557. }
  1558. template <typename Return, typename Guard, typename Func>
  1559. enable_if_t<std::is_void<Return>::value, void_type> call(Func &&f) && {
  1560. std::move(*this).template call_impl<Return>(std::forward<Func>(f), indices{}, Guard{});
  1561. return void_type();
  1562. }
  1563. private:
  1564. static bool load_impl_sequence(function_call &, index_sequence<>) { return true; }
  1565. template <size_t... Is>
  1566. bool load_impl_sequence(function_call &call, index_sequence<Is...>) {
  1567. for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...})
  1568. if (!r)
  1569. return false;
  1570. return true;
  1571. }
  1572. template <typename Return, typename Func, size_t... Is, typename Guard>
  1573. Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) {
  1574. return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...);
  1575. }
  1576. std::tuple<make_caster<Args>...> argcasters;
  1577. };
  1578. /// Helper class which collects only positional arguments for a Python function call.
  1579. /// A fancier version below can collect any argument, but this one is optimal for simple calls.
  1580. template <return_value_policy policy>
  1581. class simple_collector {
  1582. public:
  1583. template <typename... Ts>
  1584. explicit simple_collector(Ts &&...values)
  1585. : m_args(pybind11::make_tuple<policy>(std::forward<Ts>(values)...)) { }
  1586. const tuple &args() const & { return m_args; }
  1587. dict kwargs() const { return {}; }
  1588. tuple args() && { return std::move(m_args); }
  1589. /// Call a Python function and pass the collected arguments
  1590. object call(PyObject *ptr) const {
  1591. PyObject *result = PyObject_CallObject(ptr, m_args.ptr());
  1592. if (!result)
  1593. throw error_already_set();
  1594. return reinterpret_steal<object>(result);
  1595. }
  1596. private:
  1597. tuple m_args;
  1598. };
  1599. /// Helper class which collects positional, keyword, * and ** arguments for a Python function call
  1600. template <return_value_policy policy>
  1601. class unpacking_collector {
  1602. public:
  1603. template <typename... Ts>
  1604. explicit unpacking_collector(Ts &&...values) {
  1605. // Tuples aren't (easily) resizable so a list is needed for collection,
  1606. // but the actual function call strictly requires a tuple.
  1607. auto args_list = list();
  1608. int _[] = { 0, (process(args_list, std::forward<Ts>(values)), 0)... };
  1609. ignore_unused(_);
  1610. m_args = std::move(args_list);
  1611. }
  1612. const tuple &args() const & { return m_args; }
  1613. const dict &kwargs() const & { return m_kwargs; }
  1614. tuple args() && { return std::move(m_args); }
  1615. dict kwargs() && { return std::move(m_kwargs); }
  1616. /// Call a Python function and pass the collected arguments
  1617. object call(PyObject *ptr) const {
  1618. PyObject *result = PyObject_Call(ptr, m_args.ptr(), m_kwargs.ptr());
  1619. if (!result)
  1620. throw error_already_set();
  1621. return reinterpret_steal<object>(result);
  1622. }
  1623. private:
  1624. template <typename T>
  1625. void process(list &args_list, T &&x) {
  1626. auto o = reinterpret_steal<object>(detail::make_caster<T>::cast(std::forward<T>(x), policy, {}));
  1627. if (!o) {
  1628. #if defined(NDEBUG)
  1629. argument_cast_error();
  1630. #else
  1631. argument_cast_error(std::to_string(args_list.size()), type_id<T>());
  1632. #endif
  1633. }
  1634. args_list.append(o);
  1635. }
  1636. void process(list &args_list, detail::args_proxy ap) {
  1637. for (const auto &a : ap)
  1638. args_list.append(a);
  1639. }
  1640. void process(list &/*args_list*/, arg_v a) {
  1641. if (!a.name)
  1642. #if defined(NDEBUG)
  1643. nameless_argument_error();
  1644. #else
  1645. nameless_argument_error(a.type);
  1646. #endif
  1647. if (m_kwargs.contains(a.name)) {
  1648. #if defined(NDEBUG)
  1649. multiple_values_error();
  1650. #else
  1651. multiple_values_error(a.name);
  1652. #endif
  1653. }
  1654. if (!a.value) {
  1655. #if defined(NDEBUG)
  1656. argument_cast_error();
  1657. #else
  1658. argument_cast_error(a.name, a.type);
  1659. #endif
  1660. }
  1661. m_kwargs[a.name] = a.value;
  1662. }
  1663. void process(list &/*args_list*/, detail::kwargs_proxy kp) {
  1664. if (!kp)
  1665. return;
  1666. for (const auto &k : reinterpret_borrow<dict>(kp)) {
  1667. if (m_kwargs.contains(k.first)) {
  1668. #if defined(NDEBUG)
  1669. multiple_values_error();
  1670. #else
  1671. multiple_values_error(str(k.first));
  1672. #endif
  1673. }
  1674. m_kwargs[k.first] = k.second;
  1675. }
  1676. }
  1677. [[noreturn]] static void nameless_argument_error() {
  1678. throw type_error("Got kwargs without a name; only named arguments "
  1679. "may be passed via py::arg() to a python function call. "
  1680. "(compile in debug mode for details)");
  1681. }
  1682. [[noreturn]] static void nameless_argument_error(std::string type) {
  1683. throw type_error("Got kwargs without a name of type '" + type + "'; only named "
  1684. "arguments may be passed via py::arg() to a python function call. ");
  1685. }
  1686. [[noreturn]] static void multiple_values_error() {
  1687. throw type_error("Got multiple values for keyword argument "
  1688. "(compile in debug mode for details)");
  1689. }
  1690. [[noreturn]] static void multiple_values_error(std::string name) {
  1691. throw type_error("Got multiple values for keyword argument '" + name + "'");
  1692. }
  1693. [[noreturn]] static void argument_cast_error() {
  1694. throw cast_error("Unable to convert call argument to Python object "
  1695. "(compile in debug mode for details)");
  1696. }
  1697. [[noreturn]] static void argument_cast_error(std::string name, std::string type) {
  1698. throw cast_error("Unable to convert call argument '" + name
  1699. + "' of type '" + type + "' to Python object");
  1700. }
  1701. private:
  1702. tuple m_args;
  1703. dict m_kwargs;
  1704. };
  1705. /// Collect only positional arguments for a Python function call
  1706. template <return_value_policy policy, typename... Args,
  1707. typename = enable_if_t<all_of<is_positional<Args>...>::value>>
  1708. simple_collector<policy> collect_arguments(Args &&...args) {
  1709. return simple_collector<policy>(std::forward<Args>(args)...);
  1710. }
  1711. /// Collect all arguments, including keywords and unpacking (only instantiated when needed)
  1712. template <return_value_policy policy, typename... Args,
  1713. typename = enable_if_t<!all_of<is_positional<Args>...>::value>>
  1714. unpacking_collector<policy> collect_arguments(Args &&...args) {
  1715. // Following argument order rules for generalized unpacking according to PEP 448
  1716. static_assert(
  1717. constexpr_last<is_positional, Args...>() < constexpr_first<is_keyword_or_ds, Args...>()
  1718. && constexpr_last<is_s_unpacking, Args...>() < constexpr_first<is_ds_unpacking, Args...>(),
  1719. "Invalid function call: positional args must precede keywords and ** unpacking; "
  1720. "* unpacking must precede ** unpacking"
  1721. );
  1722. return unpacking_collector<policy>(std::forward<Args>(args)...);
  1723. }
  1724. template <typename Derived>
  1725. template <return_value_policy policy, typename... Args>
  1726. object object_api<Derived>::operator()(Args &&...args) const {
  1727. return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
  1728. }
  1729. template <typename Derived>
  1730. template <return_value_policy policy, typename... Args>
  1731. object object_api<Derived>::call(Args &&...args) const {
  1732. return operator()<policy>(std::forward<Args>(args)...);
  1733. }
  1734. NAMESPACE_END(detail)
  1735. #define PYBIND11_MAKE_OPAQUE(Type) \
  1736. namespace pybind11 { namespace detail { \
  1737. template<> class type_caster<Type> : public type_caster_base<Type> { }; \
  1738. }}
  1739. NAMESPACE_END(pybind11)