test_classh_wip.cpp 15.1 KB
Newer Older
1
2
3
4
5
#include "pybind11_tests.h"

#include <pybind11/classh.h>

#include <memory>
6
#include <string>
7
8
9
10

namespace pybind11_tests {
namespace classh_wip {

11
12
13
14
15
struct mpty {
    std::string mtxt;
};

// clang-format off
16

17
18
19
20
21
22
mpty        rtrn_mpty_valu() { mpty obj{"rtrn_valu"}; return obj; }
mpty&&      rtrn_mpty_rref() { mpty obj{"rtrn_rref"}; return std::move(obj); }
mpty const& rtrn_mpty_cref() { static mpty obj; obj.mtxt = "rtrn_cref"; return obj; }
mpty&       rtrn_mpty_mref() { static mpty obj; obj.mtxt = "rtrn_mref"; return obj; }
mpty const* rtrn_mpty_cptr() { static mpty obj; obj.mtxt = "rtrn_cptr"; return &obj; }
mpty*       rtrn_mpty_mptr() { static mpty obj; obj.mtxt = "rtrn_mptr"; return &obj; }
23

24
25
26
27
28
29
std::string pass_mpty_valu(mpty obj)        { return "pass_valu:" + obj.mtxt; }
std::string pass_mpty_rref(mpty&& obj)      { return "pass_rref:" + obj.mtxt; }
std::string pass_mpty_cref(mpty const& obj) { return "pass_cref:" + obj.mtxt; }
std::string pass_mpty_mref(mpty& obj)       { return "pass_mref:" + obj.mtxt; }
std::string pass_mpty_cptr(mpty const* obj) { return "pass_cptr:" + obj->mtxt; }
std::string pass_mpty_mptr(mpty* obj)       { return "pass_mptr:" + obj->mtxt; }
30

31
32
std::shared_ptr<mpty>       rtrn_mpty_shmp() { return std::shared_ptr<mpty      >(new mpty{"rtrn_shmp"}); }
std::shared_ptr<mpty const> rtrn_mpty_shcp() { return std::shared_ptr<mpty const>(new mpty{"rtrn_shcp"}); }
33

34
std::string pass_mpty_shmp(std::shared_ptr<mpty>       obj) { return "pass_shmp:" + obj->mtxt; }
35
std::string pass_mpty_shcp(std::shared_ptr<mpty const> obj) { return "pass_shcp:" + obj->mtxt; }
36

37
38
std::unique_ptr<mpty>       rtrn_mpty_uqmp() { return std::unique_ptr<mpty      >(new mpty{"rtrn_uqmp"}); }
std::unique_ptr<mpty const> rtrn_mpty_uqcp() { return std::unique_ptr<mpty const>(new mpty{"rtrn_uqmp"}); }
39

40
std::string pass_mpty_uqmp(std::unique_ptr<mpty      > obj) { return "pass_uqmp:" + obj->mtxt; }
41
std::string pass_mpty_uqcp(std::unique_ptr<mpty const> obj) { return "pass_uqcp:" + obj->mtxt; }
42

43
44
// clang-format on

45
46
std::string get_mtxt(mpty const &obj) { return obj.mtxt; }

47
48
} // namespace classh_wip
} // namespace pybind11_tests
49
50
51
52
53
54

namespace pybind11 {
namespace detail {

using namespace pybind11_tests::classh_wip;

55
56
57
template <typename T>
struct smart_holder_type_caster_load {
    bool load(handle src, bool /*convert*/) {
58
59
60
61
        if (!isinstance<T>(src))
            return false;
        auto inst  = reinterpret_cast<instance *>(src.ptr());
        auto v_h   = inst->get_value_and_holder(get_type_info(typeid(T)));
62
63
64
65
        smhldr_ptr = &v_h.holder<pybindit::memory::smart_holder>();
        return true;
    }

66
67
protected:
    pybindit::memory::smart_holder *smhldr_ptr = nullptr;
68
69
};

70
template <>
71
struct type_caster<mpty> : smart_holder_type_caster_load<mpty> {
72
73
74
75
76
    static constexpr auto name = _<mpty>();

    // static handle cast(mpty, ...)
    // is redundant (leads to ambiguous overloads).

77
78
79
80
81
82
    static handle cast(mpty &&src, return_value_policy /*policy*/, handle parent) {
        // type_caster_base BEGIN
        // clang-format off
        return cast(&src, return_value_policy::move, parent);
        // clang-format on
        // type_caster_base END
83
84
    }

85
86
87
88
89
90
91
92
    static handle cast(mpty const &src, return_value_policy policy, handle parent) {
        // type_caster_base BEGIN
        // clang-format off
        if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference)
            policy = return_value_policy::copy;
        return cast(&src, policy, parent);
        // clang-format on
        // type_caster_base END
93
94
    }

95
96
    static handle cast(mpty &src, return_value_policy policy, handle parent) {
        return cast(const_cast<mpty const &>(src), policy, parent); // Mtbl2Const
97
98
    }

99
100
101
102
    static handle cast(mpty const *src, return_value_policy policy, handle parent) {
        // type_caster_base BEGIN
        // clang-format off
        auto st = src_and_type(src);
103
        return cast( // Originally type_caster_generic::cast.
104
105
106
107
            st.first, policy, parent, st.second,
            make_copy_constructor(src), make_move_constructor(src));
        // clang-format on
        // type_caster_base END
108
109
    }

110
111
    static handle cast(mpty *src, return_value_policy policy, handle parent) {
        return cast(const_cast<mpty const *>(src), policy, parent); // Mtbl2Const
112
113
114
115
    }

    template <typename T_>
    using cast_op_type = conditional_t<
116
117
        std::is_same<remove_reference_t<T_>, mpty const *>::value,
        mpty const *,
118
        conditional_t<
119
120
            std::is_same<remove_reference_t<T_>, mpty *>::value,
            mpty *,
121
            conditional_t<
122
123
124
125
126
127
128
                std::is_same<T_, mpty const &>::value,
                mpty const &,
                conditional_t<std::is_same<T_, mpty &>::value,
                              mpty &,
                              conditional_t<std::is_same<T_, mpty &&>::value, mpty &&, mpty>>>>>;

    // clang-format off
129

130
131
132
133
134
135
    operator mpty()        { return smhldr_ptr->lvalue_ref<mpty>(); }
    operator mpty&&() &&   { return smhldr_ptr->rvalue_ref<mpty>(); }
    operator mpty const&() { return smhldr_ptr->lvalue_ref<mpty>(); }
    operator mpty&()       { return smhldr_ptr->lvalue_ref<mpty>(); }
    operator mpty const*() { return smhldr_ptr->as_raw_ptr_unowned<mpty>(); }
    operator mpty*()       { return smhldr_ptr->as_raw_ptr_unowned<mpty>(); }
136
137

    // clang-format on
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190

    using itype = mpty;

    // type_caster_base BEGIN
    // clang-format off

    // Returns a (pointer, type_info) pair taking care of necessary type lookup for a
    // polymorphic type (using RTTI by default, but can be overridden by specializing
    // polymorphic_type_hook). If the instance isn't derived, returns the base version.
    static std::pair<const void *, const type_info *> src_and_type(const itype *src) {
        auto &cast_type = typeid(itype);
        const std::type_info *instance_type = nullptr;
        const void *vsrc = polymorphic_type_hook<itype>::get(src, instance_type);
        if (instance_type && !same_type(cast_type, *instance_type)) {
            // This is a base pointer to a derived type. If the derived type is registered
            // with pybind11, we want to make the full derived object available.
            // In the typical case where itype is polymorphic, we get the correct
            // derived pointer (which may be != base pointer) by a dynamic_cast to
            // most derived type. If itype is not polymorphic, we won't get here
            // except via a user-provided specialization of polymorphic_type_hook,
            // and the user has promised that no this-pointer adjustment is
            // required in that case, so it's OK to use static_cast.
            if (const auto *tpi = get_type_info(*instance_type))
                return {vsrc, tpi};
        }
        // Otherwise we have either a nullptr, an `itype` pointer, or an unknown derived pointer, so
        // don't do a cast
        return type_caster_generic::src_and_type(src, cast_type, instance_type);
    }

    using Constructor = void *(*)(const void *);

    /* Only enabled when the types are {copy,move}-constructible *and* when the type
       does not have a private operator new implementation. */
    template <typename T, typename = enable_if_t<is_copy_constructible<T>::value>>
    static auto make_copy_constructor(const T *x) -> decltype(new T(*x), Constructor{}) {
        return [](const void *arg) -> void * {
            return new T(*reinterpret_cast<const T *>(arg));
        };
    }

    template <typename T, typename = enable_if_t<std::is_move_constructible<T>::value>>
    static auto make_move_constructor(const T *x) -> decltype(new T(std::move(*const_cast<T *>(x))), Constructor{}) {
        return [](const void *arg) -> void * {
            return new T(std::move(*const_cast<T *>(reinterpret_cast<const T *>(arg))));
        };
    }

    static Constructor make_copy_constructor(...) { return nullptr; }
    static Constructor make_move_constructor(...) { return nullptr; }

    // clang-format on
    // type_caster_base END
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283

    // Originally type_caster_generic::cast.
    // clang-format off
    PYBIND11_NOINLINE static handle cast(const void *_src, return_value_policy policy, handle parent,
                                         const detail::type_info *tinfo,
                                         void *(*copy_constructor)(const void *),
                                         void *(*move_constructor)(const void *),
                                         const void *existing_holder = nullptr) {
        if (!tinfo) // no type info: error will be set already
            return handle();

        void *src = const_cast<void *>(_src);
        if (src == nullptr)
            return none().release();

        auto it_instances = get_internals().registered_instances.equal_range(src);
        for (auto it_i = it_instances.first; it_i != it_instances.second; ++it_i) {
            for (auto instance_type : detail::all_type_info(Py_TYPE(it_i->second))) {
                if (instance_type && same_type(*instance_type->cpptype, *tinfo->cpptype))
                    return handle((PyObject *) it_i->second).inc_ref();
            }
        }

        auto inst = reinterpret_steal<object>(make_new_instance(tinfo->type));
        auto wrapper = reinterpret_cast<instance *>(inst.ptr());
        wrapper->owned = false;
        void *&valueptr = values_and_holders(wrapper).begin()->value_ptr();

        switch (policy) {
            case return_value_policy::automatic:
            case return_value_policy::take_ownership:
                valueptr = src;
                wrapper->owned = true;
                break;

            case return_value_policy::automatic_reference:
            case return_value_policy::reference:
                valueptr = src;
                wrapper->owned = false;
                break;

            case return_value_policy::copy:
                if (copy_constructor)
                    valueptr = copy_constructor(src);
                else {
#if defined(NDEBUG)
                    throw cast_error("return_value_policy = copy, but type is "
                                     "non-copyable! (compile in debug mode for details)");
#else
                    std::string type_name(tinfo->cpptype->name());
                    detail::clean_type_id(type_name);
                    throw cast_error("return_value_policy = copy, but type " +
                                     type_name + " is non-copyable!");
#endif
                }
                wrapper->owned = true;
                break;

            case return_value_policy::move:
                if (move_constructor)
                    valueptr = move_constructor(src);
                else if (copy_constructor)
                    valueptr = copy_constructor(src);
                else {
#if defined(NDEBUG)
                    throw cast_error("return_value_policy = move, but type is neither "
                                     "movable nor copyable! "
                                     "(compile in debug mode for details)");
#else
                    std::string type_name(tinfo->cpptype->name());
                    detail::clean_type_id(type_name);
                    throw cast_error("return_value_policy = move, but type " +
                                     type_name + " is neither movable nor copyable!");
#endif
                }
                wrapper->owned = true;
                break;

            case return_value_policy::reference_internal:
                valueptr = src;
                wrapper->owned = false;
                keep_alive_impl(inst, parent);
                break;

            default:
                throw cast_error("unhandled return_value_policy: should not happen!");
        }

        tinfo->init_instance(wrapper, existing_holder);

        return inst.release();
    }
    // clang-format on
284
285
286
};

template <>
287
struct type_caster<std::shared_ptr<mpty>> : smart_holder_type_caster_load<mpty> {
288
289
    static constexpr auto name = _<std::shared_ptr<mpty>>();

290
    static handle cast(const std::shared_ptr<mpty> & /*src*/,
291
292
293
294
295
                       return_value_policy /*policy*/,
                       handle /*parent*/) {
        return str("cast_shmp").release();
    }

296
297
    template <typename>
    using cast_op_type = std::shared_ptr<mpty>;
298

299
    operator std::shared_ptr<mpty>() { return smhldr_ptr->as_shared_ptr<mpty>(); }
300
301
302
};

template <>
303
struct type_caster<std::shared_ptr<mpty const>> : smart_holder_type_caster_load<mpty> {
304
305
    static constexpr auto name = _<std::shared_ptr<mpty const>>();

306
    static handle cast(const std::shared_ptr<mpty const> & /*src*/,
307
308
309
310
311
                       return_value_policy /*policy*/,
                       handle /*parent*/) {
        return str("cast_shcp").release();
    }

312
313
    template <typename>
    using cast_op_type = std::shared_ptr<mpty const>;
314

315
    operator std::shared_ptr<mpty const>() { return smhldr_ptr->as_shared_ptr<mpty>(); }
316
317
318
};

template <>
319
struct type_caster<std::unique_ptr<mpty>> : smart_holder_type_caster_load<mpty> {
320
321
    static constexpr auto name = _<std::unique_ptr<mpty>>();

322
323
    static handle
    cast(std::unique_ptr<mpty> && /*src*/, return_value_policy /*policy*/, handle /*parent*/) {
324
325
326
        return str("cast_uqmp").release();
    }

327
328
    template <typename>
    using cast_op_type = std::unique_ptr<mpty>;
329

330
    operator std::unique_ptr<mpty>() { return smhldr_ptr->as_unique_ptr<mpty>(); }
331
332
333
};

template <>
334
struct type_caster<std::unique_ptr<mpty const>> : smart_holder_type_caster_load<mpty> {
335
336
    static constexpr auto name = _<std::unique_ptr<mpty const>>();

337
    static handle cast(std::unique_ptr<mpty const> && /*src*/,
338
339
340
341
342
                       return_value_policy /*policy*/,
                       handle /*parent*/) {
        return str("cast_uqcp").release();
    }

343
344
    template <typename>
    using cast_op_type = std::unique_ptr<mpty const>;
345

346
    operator std::unique_ptr<mpty const>() { return smhldr_ptr->as_unique_ptr<mpty>(); }
347
348
};

349
350
} // namespace detail
} // namespace pybind11
351
352
353
354
355
356
357

namespace pybind11_tests {
namespace classh_wip {

TEST_SUBMODULE(classh_wip, m) {
    namespace py = pybind11;

358
359
360
361
362
    py::classh<mpty>(m, "mpty").def(py::init<>()).def(py::init([](const std::string &mtxt) {
        mpty obj;
        obj.mtxt = mtxt;
        return obj;
    }));
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388

    m.def("rtrn_mpty_valu", rtrn_mpty_valu);
    m.def("rtrn_mpty_rref", rtrn_mpty_rref);
    m.def("rtrn_mpty_cref", rtrn_mpty_cref);
    m.def("rtrn_mpty_mref", rtrn_mpty_mref);
    m.def("rtrn_mpty_cptr", rtrn_mpty_cptr);
    m.def("rtrn_mpty_mptr", rtrn_mpty_mptr);

    m.def("pass_mpty_valu", pass_mpty_valu);
    m.def("pass_mpty_rref", pass_mpty_rref);
    m.def("pass_mpty_cref", pass_mpty_cref);
    m.def("pass_mpty_mref", pass_mpty_mref);
    m.def("pass_mpty_cptr", pass_mpty_cptr);
    m.def("pass_mpty_mptr", pass_mpty_mptr);

    m.def("rtrn_mpty_shmp", rtrn_mpty_shmp);
    m.def("rtrn_mpty_shcp", rtrn_mpty_shcp);

    m.def("pass_mpty_shmp", pass_mpty_shmp);
    m.def("pass_mpty_shcp", pass_mpty_shcp);

    m.def("rtrn_mpty_uqmp", rtrn_mpty_uqmp);
    m.def("rtrn_mpty_uqcp", rtrn_mpty_uqcp);

    m.def("pass_mpty_uqmp", pass_mpty_uqmp);
    m.def("pass_mpty_uqcp", pass_mpty_uqcp);
389
390

    m.def("get_mtxt", get_mtxt); // Requires pass_mpty_cref to work properly.
391
392
}

393
394
} // namespace classh_wip
} // namespace pybind11_tests