cast.h 87 KB

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