|
| 1 | +/* |
| 2 | + pybind11/factory.h: Helper class for binding C++ factory functions |
| 3 | + as Python constructors. |
| 4 | +
|
| 5 | + Copyright (c) 2017 Jason Rhinelander <jason@imaginary.ca> |
| 6 | +
|
| 7 | + All rights reserved. Use of this source code is governed by a |
| 8 | + BSD-style license that can be found in the LICENSE file. |
| 9 | +*/ |
| 10 | + |
| 11 | +#pragma once |
| 12 | +#include "pybind11.h" |
| 13 | + |
| 14 | +NAMESPACE_BEGIN(pybind11) |
| 15 | + |
| 16 | +template <typename type, typename... options> |
| 17 | +template <typename... Args, typename... Extra> |
| 18 | +class_<type, options...> &class_<type, options...>::def(detail::init_factory<Args...> &&init, const Extra&... extra) { |
| 19 | + std::move(init).execute(*this, extra...); |
| 20 | + return *this; |
| 21 | +} |
| 22 | + |
| 23 | +NAMESPACE_BEGIN(detail) |
| 24 | + |
| 25 | +template <typename Func, typename Return, typename... Args> struct init_factory { |
| 26 | +private: |
| 27 | + using PlainReturn = typename std::remove_pointer<Return>::type; |
| 28 | + using ForwardReturn = typename std::add_rvalue_reference<Return>::type; |
| 29 | + |
| 30 | + template <typename Class> using Cpp = typename Class::type; |
| 31 | + template <typename Class> using Alias = typename Class::type_alias; |
| 32 | + template <typename Class> using Inst = typename Class::instance_type; |
| 33 | + template <typename Class> using Holder = typename Class::holder_type; |
| 34 | + |
| 35 | + template <typename Class, typename SFINAE = void> struct alias_constructible : std::false_type {}; |
| 36 | + template <typename Class> struct alias_constructible<Class, enable_if_t<Class::has_alias && all_of< |
| 37 | + std::is_convertible<Return, Alias<Class>>, std::is_constructible<Alias<Class>, Alias<Class> &&>, |
| 38 | + std::is_convertible<Return, Cpp<Class>>, std::is_constructible<Cpp<Class>, Cpp<Class> &&>>::value>> |
| 39 | + : std::true_type {}; |
| 40 | + |
| 41 | + // We accept a return value in the following categories, in order of precedence: |
| 42 | + struct wraps_pointer_tag {}; |
| 43 | + struct wraps_holder_tag {}; |
| 44 | + struct wraps_pyobject_tag {}; |
| 45 | + struct wraps_alias_tag {}; |
| 46 | + struct wraps_value_tag {}; |
| 47 | + struct invalid_factory_return_type {}; |
| 48 | + |
| 49 | + // Resolve the combination of Class and Return value to exactly one of the above tags: |
| 50 | + template <typename Class> using factory_type = |
| 51 | + // a pointer of the actual or a derived type: |
| 52 | + conditional_t<std::is_pointer<Return>::value && std::is_base_of<Cpp<Class>, PlainReturn>::value, |
| 53 | + wraps_pointer_tag, |
| 54 | + // a holder: |
| 55 | + conditional_t<std::is_convertible<Holder<Class>, Return>::value, |
| 56 | + wraps_holder_tag, |
| 57 | + // a python object (with compatible type checking and failure at runtime): |
| 58 | + conditional_t<std::is_convertible<Return, handle>::value, |
| 59 | + wraps_pyobject_tag, |
| 60 | + // Two accept-by-value versions: the first is for classes with an alias where the returned value |
| 61 | + // is convertible to either the alias or the value: |
| 62 | + conditional_t<alias_constructible<Class>::value, |
| 63 | + wraps_alias_tag, |
| 64 | + // Accept-by-value with no alias or a return value not convertible to the alias (e.g. a |
| 65 | + // Cpp<Class> value itself): |
| 66 | + conditional_t<std::is_convertible<Return, Cpp<Class>>::value && std::is_constructible<Cpp<Class>, Cpp<Class> &&>::value, |
| 67 | + wraps_value_tag, |
| 68 | + invalid_factory_return_type>>>>>; |
| 69 | + |
| 70 | +public: |
| 71 | + // Constructor: takes the function/lambda to call |
| 72 | + init_factory(Func &&f) : f{std::move(f)} {} |
| 73 | + |
| 74 | + template <typename Class, typename... Extra> |
| 75 | + void execute(Class &cl, const Extra&... extra) && { |
| 76 | + // Some checks against various types of failure that we can detect at compile time: |
| 77 | + static_assert(!std::is_same<factory_type<Class>, invalid_factory_return_type>::value, |
| 78 | + "pybind11::init_factory(): wrapped factory function must return a compatible pointer, " |
| 79 | + "holder, python object, or value"); |
| 80 | + |
| 81 | + handle cl_type(cl); |
| 82 | + #if defined(PYBIND11_CPP14) || defined(_MSC_VER) |
| 83 | + cl.def("__init__", [cl_type, func = std::move(f)] |
| 84 | + #else |
| 85 | + Func func = std::move(f); |
| 86 | + cl.def("__init__", [cl_type, func] |
| 87 | + #endif |
| 88 | + (handle self, Args... args) { |
| 89 | + auto *inst = (Inst<Class> *) self.ptr(); |
| 90 | + construct<Class>(inst, func(std::forward<Args>(args)...), cl_type, factory_type<Class>()); |
| 91 | + }, extra...); |
| 92 | + } |
| 93 | + |
| 94 | +protected: |
| 95 | + template <typename Class> static void dealloc(Inst<Class> *self) { |
| 96 | + // Reset/unallocate the existing values |
| 97 | + clear_instance((PyObject *) self); |
| 98 | + self->value = nullptr; |
| 99 | + self->owned = true; |
| 100 | + self->holder_constructed = false; |
| 101 | + } |
| 102 | + |
| 103 | + template <typename Class> |
| 104 | + static void construct(Inst<Class> *self, Cpp<Class> *result, handle /*cl_type*/, wraps_pointer_tag) { |
| 105 | + // We were given a pointer to CppClass (or some derived type); dealloc the existing value |
| 106 | + // and replace it with the given pointer; the dispatcher will then set up the holder for us |
| 107 | + // after we return from the lambda. |
| 108 | + dealloc<Class>(self); |
| 109 | + self->value = result; |
| 110 | + register_instance(self); |
| 111 | + } |
| 112 | + |
| 113 | + template <typename Class> |
| 114 | + static void construct(Inst<Class> *self, Holder<Class> holder, handle /*cl_type*/, wraps_holder_tag) { |
| 115 | + // We were returned a holder; copy its pointer, and move/copy the holder into place. |
| 116 | + dealloc<Class>(self); |
| 117 | + self->value = holder_helper<Holder<Class>>::get(holder); |
| 118 | + Class::init_holder((PyObject *) self, &holder); |
| 119 | + register_instance(self); |
| 120 | + } |
| 121 | + |
| 122 | + template <typename Class> |
| 123 | + static void construct(Inst<Class> *self, handle result, handle cl_type, wraps_pyobject_tag tag) { |
| 124 | + // We were given a raw handle; steal it and forward to the py::object version |
| 125 | + construct<Class>(self, reinterpret_steal<object>(result), cl_type, tag); |
| 126 | + } |
| 127 | + template <typename Class> |
| 128 | + static void construct(Inst<Class> *self, object result, handle /*cl_type*/, wraps_pyobject_tag) { |
| 129 | + // Lambda returned a py::object (or something derived from it) |
| 130 | + |
| 131 | + // Make sure we actually got something |
| 132 | + if (!result) |
| 133 | + throw type_error("__init__() factory function returned a null python object"); |
| 134 | + |
| 135 | + auto *result_inst = (Inst<Class> *) result.ptr(); |
| 136 | + auto type = Py_TYPE(self); |
| 137 | + |
| 138 | + // Make sure the factory function gave us exactly the right type (we don't allow |
| 139 | + // up/down-casting here): |
| 140 | + if (Py_TYPE(result_inst) != type) |
| 141 | + throw type_error(std::string("__init__() factory function should return '") + type->tp_name + |
| 142 | + "', not '" + Py_TYPE(result_inst)->tp_name + "'"); |
| 143 | + // The factory function must give back a unique reference: |
| 144 | + if (result.ref_count() != 1) |
| 145 | + throw type_error("__init__() factory function returned an object with multiple references"); |
| 146 | + // Guard against accidentally specifying a reference r.v. policy or similar: |
| 147 | + if (!result_inst->owned) |
| 148 | + throw type_error("__init__() factory function returned an unowned reference"); |
| 149 | + |
| 150 | + // Steal the instance internals: |
| 151 | + dealloc<Class>(self); |
| 152 | + std::swap(self->value, result_inst->value); |
| 153 | + std::swap(self->weakrefs, result_inst->weakrefs); |
| 154 | + if (type->tp_dictoffset != 0) |
| 155 | + std::swap(*_PyObject_GetDictPtr((PyObject *) self), *_PyObject_GetDictPtr((PyObject *) result_inst)); |
| 156 | + // Now steal the holder |
| 157 | + Class::init_holder((PyObject *) self, &result_inst->holder); |
| 158 | + // Find the instance we just stole and update its PyObject from `result` to `self` |
| 159 | + auto range = get_internals().registered_instances.equal_range(self->value); |
| 160 | + for (auto it = range.first; it != range.second; ++it) { |
| 161 | + if (type == Py_TYPE(it->second)) { |
| 162 | + it->second = self; |
| 163 | + break; |
| 164 | + } |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + // wrap return-by-value, version 1: returns a cpp object (or something convertible to it) by |
| 169 | + // value. (Returned values convertible to the alias class (if any) use the next version.) |
| 170 | + template <typename Class> |
| 171 | + static void construct(Inst<Class> *self, Cpp<Class> result, handle /*cl_type*/, wraps_value_tag) { |
| 172 | + new (self->value) Cpp<Class>(std::move(result)); |
| 173 | + } |
| 174 | + |
| 175 | + // Same as above, but when an alias class is involved and the return value is convertible to the |
| 176 | + // alias (which typically *won't* be called for direct CppClass return). |
| 177 | + template <typename Class> |
| 178 | + static void construct(Inst<Class> *self, Return &&result, handle cl_type, wraps_alias_tag) { |
| 179 | + if (Py_TYPE(self) == (PyTypeObject *) cl_type.ptr()) |
| 180 | + construct_alias<Class>(self, std::forward<Return>(result)); |
| 181 | + else |
| 182 | + construct<Class>(self, std::forward<Return>(result), cl_type, wraps_value_tag()); |
| 183 | + } |
| 184 | + template <typename Class> |
| 185 | + static void construct_alias(Inst<Class> *self, Alias<Class> result) { |
| 186 | + new (self->value) Alias<Class>(std::move(result)); |
| 187 | + } |
| 188 | + |
| 189 | + Func f; |
| 190 | +}; |
| 191 | + |
| 192 | +// Helper definition to infer the detail::init_factory template type from a callable object |
| 193 | +template <typename Func, typename Return, typename... Args> |
| 194 | +init_factory<Func, Return, Args...> init_factory_decltype(Return (*)(Args...)); |
| 195 | +template <typename Func> using init_factory_t = decltype(init_factory_decltype<Func>( |
| 196 | + (typename detail::remove_class<decltype(&std::remove_reference<Func>::type::operator())>::type *) nullptr)); |
| 197 | + |
| 198 | +NAMESPACE_END(detail) |
| 199 | + |
| 200 | +/// Construct a factory function constructor wrapper from a vanilla function pointer |
| 201 | +template <typename Return, typename... Args> |
| 202 | +detail::init_factory<Return (*)(Args...), Return, Args...> init_factory(Return (*f)(Args...)) { |
| 203 | + return f; |
| 204 | +} |
| 205 | +/// Construct a factory function constructor wrapper from a lambda function (possibly with internal state) |
| 206 | +template <typename Func, typename = detail::enable_if_t< |
| 207 | + detail::satisfies_none_of< |
| 208 | + typename std::remove_reference<Func>::type, |
| 209 | + std::is_function, std::is_pointer, std::is_member_pointer |
| 210 | + >::value> |
| 211 | +> |
| 212 | +detail::init_factory_t<Func> init_factory(Func &&f) { return std::move(f); } |
| 213 | + |
| 214 | +NAMESPACE_END(pybind11) |
0 commit comments