init.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. /*
  2. pybind11/detail/init.h: init factory function implementation and support code.
  3. Copyright (c) 2017 Jason Rhinelander <jason@imaginary.ca>
  4. All rights reserved. Use of this source code is governed by a
  5. BSD-style license that can be found in the LICENSE file.
  6. */
  7. #pragma once
  8. #include "class.h"
  9. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  10. PYBIND11_WARNING_DISABLE_MSVC(4127)
  11. PYBIND11_NAMESPACE_BEGIN(detail)
  12. template <>
  13. class type_caster<value_and_holder> {
  14. public:
  15. bool load(handle h, bool) {
  16. value = reinterpret_cast<value_and_holder *>(h.ptr());
  17. return true;
  18. }
  19. template <typename>
  20. using cast_op_type = value_and_holder &;
  21. explicit operator value_and_holder &() { return *value; }
  22. static constexpr auto name = const_name<value_and_holder>();
  23. private:
  24. value_and_holder *value = nullptr;
  25. };
  26. PYBIND11_NAMESPACE_BEGIN(initimpl)
  27. inline void no_nullptr(void *ptr) {
  28. if (!ptr) {
  29. throw type_error("pybind11::init(): factory function returned nullptr");
  30. }
  31. }
  32. // Implementing functions for all forms of py::init<...> and py::init(...)
  33. template <typename Class>
  34. using Cpp = typename Class::type;
  35. template <typename Class>
  36. using Alias = typename Class::type_alias;
  37. template <typename Class>
  38. using Holder = typename Class::holder_type;
  39. template <typename Class>
  40. using is_alias_constructible = std::is_constructible<Alias<Class>, Cpp<Class> &&>;
  41. // Takes a Cpp pointer and returns true if it actually is a polymorphic Alias instance.
  42. template <typename Class, enable_if_t<Class::has_alias, int> = 0>
  43. bool is_alias(Cpp<Class> *ptr) {
  44. return dynamic_cast<Alias<Class> *>(ptr) != nullptr;
  45. }
  46. // Failing fallback version of the above for a no-alias class (always returns false)
  47. template <typename /*Class*/>
  48. constexpr bool is_alias(void *) {
  49. return false;
  50. }
  51. // Constructs and returns a new object; if the given arguments don't map to a constructor, we fall
  52. // back to brace aggregate initialization so that for aggregate initialization can be used with
  53. // py::init, e.g. `py::init<int, int>` to initialize a `struct T { int a; int b; }`. For
  54. // non-aggregate types, we need to use an ordinary T(...) constructor (invoking as `T{...}` usually
  55. // works, but will not do the expected thing when `T` has an `initializer_list<T>` constructor).
  56. template <typename Class,
  57. typename... Args,
  58. detail::enable_if_t<std::is_constructible<Class, Args...>::value, int> = 0>
  59. inline Class *construct_or_initialize(Args &&...args) {
  60. return new Class(std::forward<Args>(args)...);
  61. }
  62. template <typename Class,
  63. typename... Args,
  64. detail::enable_if_t<!std::is_constructible<Class, Args...>::value, int> = 0>
  65. inline Class *construct_or_initialize(Args &&...args) {
  66. return new Class{std::forward<Args>(args)...};
  67. }
  68. // Attempts to constructs an alias using a `Alias(Cpp &&)` constructor. This allows types with
  69. // an alias to provide only a single Cpp factory function as long as the Alias can be
  70. // constructed from an rvalue reference of the base Cpp type. This means that Alias classes
  71. // can, when appropriate, simply define a `Alias(Cpp &&)` constructor rather than needing to
  72. // inherit all the base class constructors.
  73. template <typename Class>
  74. void construct_alias_from_cpp(std::true_type /*is_alias_constructible*/,
  75. value_and_holder &v_h,
  76. Cpp<Class> &&base) {
  77. v_h.value_ptr() = new Alias<Class>(std::move(base));
  78. }
  79. template <typename Class>
  80. [[noreturn]] void construct_alias_from_cpp(std::false_type /*!is_alias_constructible*/,
  81. value_and_holder &,
  82. Cpp<Class> &&) {
  83. throw type_error("pybind11::init(): unable to convert returned instance to required "
  84. "alias class: no `Alias<Class>(Class &&)` constructor available");
  85. }
  86. // Error-generating fallback for factories that don't match one of the below construction
  87. // mechanisms.
  88. template <typename Class>
  89. void construct(...) {
  90. static_assert(!std::is_same<Class, Class>::value /* always false */,
  91. "pybind11::init(): init function must return a compatible pointer, "
  92. "holder, or value");
  93. }
  94. // Pointer return v1: the factory function returns a class pointer for a registered class.
  95. // If we don't need an alias (because this class doesn't have one, or because the final type is
  96. // inherited on the Python side) we can simply take over ownership. Otherwise we need to try to
  97. // construct an Alias from the returned base instance.
  98. template <typename Class>
  99. void construct(value_and_holder &v_h, Cpp<Class> *ptr, bool need_alias) {
  100. PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);
  101. no_nullptr(ptr);
  102. if (Class::has_alias && need_alias && !is_alias<Class>(ptr)) {
  103. // We're going to try to construct an alias by moving the cpp type. Whether or not
  104. // that succeeds, we still need to destroy the original cpp pointer (either the
  105. // moved away leftover, if the alias construction works, or the value itself if we
  106. // throw an error), but we can't just call `delete ptr`: it might have a special
  107. // deleter, or might be shared_from_this. So we construct a holder around it as if
  108. // it was a normal instance, then steal the holder away into a local variable; thus
  109. // the holder and destruction happens when we leave the C++ scope, and the holder
  110. // class gets to handle the destruction however it likes.
  111. v_h.value_ptr() = ptr;
  112. v_h.set_instance_registered(true); // To prevent init_instance from registering it
  113. v_h.type->init_instance(v_h.inst, nullptr); // Set up the holder
  114. Holder<Class> temp_holder(std::move(v_h.holder<Holder<Class>>())); // Steal the holder
  115. v_h.type->dealloc(v_h); // Destroys the moved-out holder remains, resets value ptr to null
  116. v_h.set_instance_registered(false);
  117. construct_alias_from_cpp<Class>(is_alias_constructible<Class>{}, v_h, std::move(*ptr));
  118. } else {
  119. // Otherwise the type isn't inherited, so we don't need an Alias
  120. v_h.value_ptr() = ptr;
  121. }
  122. }
  123. // Pointer return v2: a factory that always returns an alias instance ptr. We simply take over
  124. // ownership of the pointer.
  125. template <typename Class, enable_if_t<Class::has_alias, int> = 0>
  126. void construct(value_and_holder &v_h, Alias<Class> *alias_ptr, bool) {
  127. no_nullptr(alias_ptr);
  128. v_h.value_ptr() = static_cast<Cpp<Class> *>(alias_ptr);
  129. }
  130. // Holder return: copy its pointer, and move or copy the returned holder into the new instance's
  131. // holder. This also handles types like std::shared_ptr<T> and std::unique_ptr<T> where T is a
  132. // derived type (through those holder's implicit conversion from derived class holder
  133. // constructors).
  134. template <typename Class>
  135. void construct(value_and_holder &v_h, Holder<Class> holder, bool need_alias) {
  136. PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);
  137. auto *ptr = holder_helper<Holder<Class>>::get(holder);
  138. no_nullptr(ptr);
  139. // If we need an alias, check that the held pointer is actually an alias instance
  140. if (Class::has_alias && need_alias && !is_alias<Class>(ptr)) {
  141. throw type_error("pybind11::init(): construction failed: returned holder-wrapped instance "
  142. "is not an alias instance");
  143. }
  144. v_h.value_ptr() = ptr;
  145. v_h.type->init_instance(v_h.inst, &holder);
  146. }
  147. // return-by-value version 1: returning a cpp class by value. If the class has an alias and an
  148. // alias is required the alias must have an `Alias(Cpp &&)` constructor so that we can construct
  149. // the alias from the base when needed (i.e. because of Python-side inheritance). When we don't
  150. // need it, we simply move-construct the cpp value into a new instance.
  151. template <typename Class>
  152. void construct(value_and_holder &v_h, Cpp<Class> &&result, bool need_alias) {
  153. PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);
  154. static_assert(is_move_constructible<Cpp<Class>>::value,
  155. "pybind11::init() return-by-value factory function requires a movable class");
  156. if (Class::has_alias && need_alias) {
  157. construct_alias_from_cpp<Class>(is_alias_constructible<Class>{}, v_h, std::move(result));
  158. } else {
  159. v_h.value_ptr() = new Cpp<Class>(std::move(result));
  160. }
  161. }
  162. // return-by-value version 2: returning a value of the alias type itself. We move-construct an
  163. // Alias instance (even if no the python-side inheritance is involved). The is intended for
  164. // cases where Alias initialization is always desired.
  165. template <typename Class>
  166. void construct(value_and_holder &v_h, Alias<Class> &&result, bool) {
  167. static_assert(
  168. is_move_constructible<Alias<Class>>::value,
  169. "pybind11::init() return-by-alias-value factory function requires a movable alias class");
  170. v_h.value_ptr() = new Alias<Class>(std::move(result));
  171. }
  172. // Implementing class for py::init<...>()
  173. template <typename... Args>
  174. struct constructor {
  175. template <typename Class, typename... Extra, enable_if_t<!Class::has_alias, int> = 0>
  176. static void execute(Class &cl, const Extra &...extra) {
  177. cl.def(
  178. "__init__",
  179. [](value_and_holder &v_h, Args... args) {
  180. v_h.value_ptr() = construct_or_initialize<Cpp<Class>>(std::forward<Args>(args)...);
  181. },
  182. is_new_style_constructor(),
  183. extra...);
  184. }
  185. template <
  186. typename Class,
  187. typename... Extra,
  188. enable_if_t<Class::has_alias && std::is_constructible<Cpp<Class>, Args...>::value, int>
  189. = 0>
  190. static void execute(Class &cl, const Extra &...extra) {
  191. cl.def(
  192. "__init__",
  193. [](value_and_holder &v_h, Args... args) {
  194. if (Py_TYPE(v_h.inst) == v_h.type->type) {
  195. v_h.value_ptr()
  196. = construct_or_initialize<Cpp<Class>>(std::forward<Args>(args)...);
  197. } else {
  198. v_h.value_ptr()
  199. = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
  200. }
  201. },
  202. is_new_style_constructor(),
  203. extra...);
  204. }
  205. template <
  206. typename Class,
  207. typename... Extra,
  208. enable_if_t<Class::has_alias && !std::is_constructible<Cpp<Class>, Args...>::value, int>
  209. = 0>
  210. static void execute(Class &cl, const Extra &...extra) {
  211. cl.def(
  212. "__init__",
  213. [](value_and_holder &v_h, Args... args) {
  214. v_h.value_ptr()
  215. = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
  216. },
  217. is_new_style_constructor(),
  218. extra...);
  219. }
  220. };
  221. // Implementing class for py::init_alias<...>()
  222. template <typename... Args>
  223. struct alias_constructor {
  224. template <
  225. typename Class,
  226. typename... Extra,
  227. enable_if_t<Class::has_alias && std::is_constructible<Alias<Class>, Args...>::value, int>
  228. = 0>
  229. static void execute(Class &cl, const Extra &...extra) {
  230. cl.def(
  231. "__init__",
  232. [](value_and_holder &v_h, Args... args) {
  233. v_h.value_ptr()
  234. = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
  235. },
  236. is_new_style_constructor(),
  237. extra...);
  238. }
  239. };
  240. // Implementation class for py::init(Func) and py::init(Func, AliasFunc)
  241. template <typename CFunc,
  242. typename AFunc = void_type (*)(),
  243. typename = function_signature_t<CFunc>,
  244. typename = function_signature_t<AFunc>>
  245. struct factory;
  246. // Specialization for py::init(Func)
  247. template <typename Func, typename Return, typename... Args>
  248. struct factory<Func, void_type (*)(), Return(Args...)> {
  249. remove_reference_t<Func> class_factory;
  250. // NOLINTNEXTLINE(google-explicit-constructor)
  251. factory(Func &&f) : class_factory(std::forward<Func>(f)) {}
  252. // The given class either has no alias or has no separate alias factory;
  253. // this always constructs the class itself. If the class is registered with an alias
  254. // type and an alias instance is needed (i.e. because the final type is a Python class
  255. // inheriting from the C++ type) the returned value needs to either already be an alias
  256. // instance, or the alias needs to be constructible from a `Class &&` argument.
  257. template <typename Class, typename... Extra>
  258. void execute(Class &cl, const Extra &...extra) && {
  259. #if defined(PYBIND11_CPP14)
  260. cl.def(
  261. "__init__",
  262. [func = std::move(class_factory)]
  263. #else
  264. auto &func = class_factory;
  265. cl.def(
  266. "__init__",
  267. [func]
  268. #endif
  269. (value_and_holder &v_h, Args... args) {
  270. construct<Class>(
  271. v_h, func(std::forward<Args>(args)...), Py_TYPE(v_h.inst) != v_h.type->type);
  272. },
  273. is_new_style_constructor(),
  274. extra...);
  275. }
  276. };
  277. // Specialization for py::init(Func, AliasFunc)
  278. template <typename CFunc,
  279. typename AFunc,
  280. typename CReturn,
  281. typename... CArgs,
  282. typename AReturn,
  283. typename... AArgs>
  284. struct factory<CFunc, AFunc, CReturn(CArgs...), AReturn(AArgs...)> {
  285. static_assert(sizeof...(CArgs) == sizeof...(AArgs),
  286. "pybind11::init(class_factory, alias_factory): class and alias factories "
  287. "must have identical argument signatures");
  288. static_assert(all_of<std::is_same<CArgs, AArgs>...>::value,
  289. "pybind11::init(class_factory, alias_factory): class and alias factories "
  290. "must have identical argument signatures");
  291. remove_reference_t<CFunc> class_factory;
  292. remove_reference_t<AFunc> alias_factory;
  293. factory(CFunc &&c, AFunc &&a)
  294. : class_factory(std::forward<CFunc>(c)), alias_factory(std::forward<AFunc>(a)) {}
  295. // The class factory is called when the `self` type passed to `__init__` is the direct
  296. // class (i.e. not inherited), the alias factory when `self` is a Python-side subtype.
  297. template <typename Class, typename... Extra>
  298. void execute(Class &cl, const Extra &...extra) && {
  299. static_assert(Class::has_alias,
  300. "The two-argument version of `py::init()` can "
  301. "only be used if the class has an alias");
  302. #if defined(PYBIND11_CPP14)
  303. cl.def(
  304. "__init__",
  305. [class_func = std::move(class_factory), alias_func = std::move(alias_factory)]
  306. #else
  307. auto &class_func = class_factory;
  308. auto &alias_func = alias_factory;
  309. cl.def(
  310. "__init__",
  311. [class_func, alias_func]
  312. #endif
  313. (value_and_holder &v_h, CArgs... args) {
  314. if (Py_TYPE(v_h.inst) == v_h.type->type) {
  315. // If the instance type equals the registered type we don't have inheritance,
  316. // so don't need the alias and can construct using the class function:
  317. construct<Class>(v_h, class_func(std::forward<CArgs>(args)...), false);
  318. } else {
  319. construct<Class>(v_h, alias_func(std::forward<CArgs>(args)...), true);
  320. }
  321. },
  322. is_new_style_constructor(),
  323. extra...);
  324. }
  325. };
  326. /// Set just the C++ state. Same as `__init__`.
  327. template <typename Class, typename T>
  328. void setstate(value_and_holder &v_h, T &&result, bool need_alias) {
  329. construct<Class>(v_h, std::forward<T>(result), need_alias);
  330. }
  331. /// Set both the C++ and Python states
  332. template <typename Class,
  333. typename T,
  334. typename O,
  335. enable_if_t<std::is_convertible<O, handle>::value, int> = 0>
  336. void setstate(value_and_holder &v_h, std::pair<T, O> &&result, bool need_alias) {
  337. construct<Class>(v_h, std::move(result.first), need_alias);
  338. auto d = handle(result.second);
  339. if (PyDict_Check(d.ptr()) && PyDict_Size(d.ptr()) == 0) {
  340. // Skipping setattr below, to not force use of py::dynamic_attr() for Class unnecessarily.
  341. // See PR #2972 for details.
  342. return;
  343. }
  344. setattr((PyObject *) v_h.inst, "__dict__", d);
  345. }
  346. /// Implementation for py::pickle(GetState, SetState)
  347. template <typename Get,
  348. typename Set,
  349. typename = function_signature_t<Get>,
  350. typename = function_signature_t<Set>>
  351. struct pickle_factory;
  352. template <typename Get,
  353. typename Set,
  354. typename RetState,
  355. typename Self,
  356. typename NewInstance,
  357. typename ArgState>
  358. struct pickle_factory<Get, Set, RetState(Self), NewInstance(ArgState)> {
  359. static_assert(std::is_same<intrinsic_t<RetState>, intrinsic_t<ArgState>>::value,
  360. "The type returned by `__getstate__` must be the same "
  361. "as the argument accepted by `__setstate__`");
  362. remove_reference_t<Get> get;
  363. remove_reference_t<Set> set;
  364. pickle_factory(Get get, Set set) : get(std::forward<Get>(get)), set(std::forward<Set>(set)) {}
  365. template <typename Class, typename... Extra>
  366. void execute(Class &cl, const Extra &...extra) && {
  367. cl.def("__getstate__", std::move(get));
  368. #if defined(PYBIND11_CPP14)
  369. cl.def(
  370. "__setstate__",
  371. [func = std::move(set)]
  372. #else
  373. auto &func = set;
  374. cl.def(
  375. "__setstate__",
  376. [func]
  377. #endif
  378. (value_and_holder &v_h, ArgState state) {
  379. setstate<Class>(
  380. v_h, func(std::forward<ArgState>(state)), Py_TYPE(v_h.inst) != v_h.type->type);
  381. },
  382. is_new_style_constructor(),
  383. extra...);
  384. }
  385. };
  386. PYBIND11_NAMESPACE_END(initimpl)
  387. PYBIND11_NAMESPACE_END(detail)
  388. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)