|
| 1 | +#include "pybind11_tests.h" |
| 2 | + |
| 3 | +namespace test_return_value_policy_override { |
| 4 | + |
| 5 | +struct some_type {}; |
| 6 | + |
| 7 | +} // namespace test_return_value_policy_override |
| 8 | + |
| 9 | +using test_return_value_policy_override::some_type; |
| 10 | + |
| 11 | +namespace pybind11 { |
| 12 | +namespace detail { |
| 13 | + |
| 14 | +const char *return_value_policy_name(return_value_policy policy) { |
| 15 | + switch (policy) { |
| 16 | + case return_value_policy::automatic: |
| 17 | + return "automatic"; |
| 18 | + case return_value_policy::automatic_reference: |
| 19 | + return "automatic_reference"; |
| 20 | + case return_value_policy::take_ownership: |
| 21 | + return "take_ownership"; |
| 22 | + case return_value_policy::copy: |
| 23 | + return "copy"; |
| 24 | + case return_value_policy::move: |
| 25 | + return "move"; |
| 26 | + case return_value_policy::reference: |
| 27 | + return "reference"; |
| 28 | + case return_value_policy::reference_internal: |
| 29 | + return "reference_internal"; |
| 30 | + case return_value_policy::_return_as_bytes: |
| 31 | + return "_return_as_bytes"; |
| 32 | + case return_value_policy::_clif_automatic: |
| 33 | + return "_clif_automatic"; |
| 34 | + default: |
| 35 | + return "Expected to be unreachable."; |
| 36 | + } |
| 37 | +}; |
| 38 | + |
| 39 | +template <> |
| 40 | +struct type_caster<some_type> : type_caster_base<some_type> { |
| 41 | + |
| 42 | + static handle cast(some_type &&, return_value_policy policy, handle /*parent*/) { |
| 43 | + return str(std::string(return_value_policy_name(policy))).release().ptr(); |
| 44 | + } |
| 45 | + |
| 46 | + static handle cast(some_type *, return_value_policy policy, handle /*parent*/) { |
| 47 | + return str(std::string(return_value_policy_name(policy))).release().ptr(); |
| 48 | + } |
| 49 | +}; |
| 50 | + |
| 51 | +} // namespace detail |
| 52 | +} // namespace pybind11 |
| 53 | + |
| 54 | +TEST_SUBMODULE(return_value_policy_override, m) { |
| 55 | + m.def("return_value_with_default_policy", []() { return some_type(); }); |
| 56 | + m.def( |
| 57 | + "return_value_with_policy_copy", |
| 58 | + []() { return some_type(); }, |
| 59 | + py::return_value_policy::copy); |
| 60 | + m.def( |
| 61 | + "return_value_with_policy_clif_automatic", |
| 62 | + []() { return some_type(); }, |
| 63 | + py::return_value_policy::_clif_automatic); |
| 64 | + m.def("return_pointer_with_default_policy", []() { |
| 65 | + static some_type value; |
| 66 | + return &value; |
| 67 | + }); |
| 68 | + m.def( |
| 69 | + "return_pointer_with_policy_move", |
| 70 | + []() { |
| 71 | + static some_type value; |
| 72 | + return &value; |
| 73 | + }, |
| 74 | + py::return_value_policy::move); |
| 75 | + m.def( |
| 76 | + "return_pointer_with_policy_clif_automatic", |
| 77 | + []() { |
| 78 | + static some_type value; |
| 79 | + return &value; |
| 80 | + }, |
| 81 | + py::return_value_policy::_clif_automatic); |
| 82 | +} |
0 commit comments