init.h 18 KB

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