init.h 16 KB

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