1 /*
2 tests/test_builtin_casters.cpp -- Casters available without any additional headers
3
4 Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
6 All rights reserved. Use of this source code is governed by a
7 BSD-style license that can be found in the LICENSE file.
8 */
9
10 #include "pybind11_tests.h"
11 #include <pybind11/complex.h>
12
13 #if defined(_MSC_VER)
14 # pragma warning(push)
15 # pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
16 #endif
17
18 struct ConstRefCasted {
19 int tag;
20 };
21
22 PYBIND11_NAMESPACE_BEGIN(pybind11)
23 PYBIND11_NAMESPACE_BEGIN(detail)
24 template <>
25 class type_caster<ConstRefCasted> {
26 public:
27 static constexpr auto name = _<ConstRefCasted>();
28
29 // Input is unimportant, a new value will always be constructed based on the
30 // cast operator.
load(handle,bool)31 bool load(handle, bool) { return true; }
32
operator ConstRefCasted&&()33 operator ConstRefCasted&&() { value = {1}; return std::move(value); }
operator ConstRefCasted&()34 operator ConstRefCasted&() { value = {2}; return value; }
operator ConstRefCasted*()35 operator ConstRefCasted*() { value = {3}; return &value; }
36
operator const ConstRefCasted&()37 operator const ConstRefCasted&() { value = {4}; return value; }
operator const ConstRefCasted*()38 operator const ConstRefCasted*() { value = {5}; return &value; }
39
40 // custom cast_op to explicitly propagate types to the conversion operators.
41 template <typename T_>
42 using cast_op_type =
43 /// const
44 conditional_t<
45 std::is_same<remove_reference_t<T_>, const ConstRefCasted*>::value, const ConstRefCasted*,
46 conditional_t<
47 std::is_same<T_, const ConstRefCasted&>::value, const ConstRefCasted&,
48 /// non-const
49 conditional_t<
50 std::is_same<remove_reference_t<T_>, ConstRefCasted*>::value, ConstRefCasted*,
51 conditional_t<
52 std::is_same<T_, ConstRefCasted&>::value, ConstRefCasted&,
53 /* else */ConstRefCasted&&>>>>;
54
55 private:
56 ConstRefCasted value = {0};
57 };
58 PYBIND11_NAMESPACE_END(detail)
PYBIND11_NAMESPACE_END(pybind11)59 PYBIND11_NAMESPACE_END(pybind11)
60
61 TEST_SUBMODULE(builtin_casters, m) {
62 // test_simple_string
63 m.def("string_roundtrip", [](const char *s) { return s; });
64
65 // test_unicode_conversion
66 // Some test characters in utf16 and utf32 encodings. The last one (the ) contains a null byte
67 char32_t a32 = 0x61 /*a*/, z32 = 0x7a /*z*/, ib32 = 0x203d /*‽*/, cake32 = 0x1f382 /**/, mathbfA32 = 0x1d400 /**/;
68 char16_t b16 = 0x62 /*b*/, z16 = 0x7a, ib16 = 0x203d, cake16_1 = 0xd83c, cake16_2 = 0xdf82, mathbfA16_1 = 0xd835, mathbfA16_2 = 0xdc00;
69 std::wstring wstr;
70 wstr.push_back(0x61); // a
71 wstr.push_back(0x2e18); // ⸘
72 if (sizeof(wchar_t) == 2) { wstr.push_back(mathbfA16_1); wstr.push_back(mathbfA16_2); } // , utf16
73 else { wstr.push_back((wchar_t) mathbfA32); } // , utf32
74 wstr.push_back(0x7a); // z
75
76 m.def("good_utf8_string", []() { return std::string((const char*)u8"Say utf8\u203d \U0001f382 \U0001d400"); }); // Say utf8‽
77 m.def("good_utf16_string", [=]() { return std::u16string({ b16, ib16, cake16_1, cake16_2, mathbfA16_1, mathbfA16_2, z16 }); }); // b‽z
78 m.def("good_utf32_string", [=]() { return std::u32string({ a32, mathbfA32, cake32, ib32, z32 }); }); // a‽z
79 m.def("good_wchar_string", [=]() { return wstr; }); // a‽z
80 m.def("bad_utf8_string", []() { return std::string("abc\xd0" "def"); });
81 m.def("bad_utf16_string", [=]() { return std::u16string({ b16, char16_t(0xd800), z16 }); });
82 // Under Python 2.7, invalid unicode UTF-32 characters don't appear to trigger UnicodeDecodeError
83 if (PY_MAJOR_VERSION >= 3)
84 m.def("bad_utf32_string", [=]() { return std::u32string({ a32, char32_t(0xd800), z32 }); });
85 if (PY_MAJOR_VERSION >= 3 || sizeof(wchar_t) == 2)
86 m.def("bad_wchar_string", [=]() { return std::wstring({ wchar_t(0x61), wchar_t(0xd800) }); });
87 m.def("u8_Z", []() -> char { return 'Z'; });
88 m.def("u8_eacute", []() -> char { return '\xe9'; });
89 m.def("u16_ibang", [=]() -> char16_t { return ib16; });
90 m.def("u32_mathbfA", [=]() -> char32_t { return mathbfA32; });
91 m.def("wchar_heart", []() -> wchar_t { return 0x2665; });
92
93 // test_single_char_arguments
94 m.attr("wchar_size") = py::cast(sizeof(wchar_t));
95 m.def("ord_char", [](char c) -> int { return static_cast<unsigned char>(c); });
96 m.def("ord_char_lv", [](char &c) -> int { return static_cast<unsigned char>(c); });
97 m.def("ord_char16", [](char16_t c) -> uint16_t { return c; });
98 m.def("ord_char16_lv", [](char16_t &c) -> uint16_t { return c; });
99 m.def("ord_char32", [](char32_t c) -> uint32_t { return c; });
100 m.def("ord_wchar", [](wchar_t c) -> int { return c; });
101
102 // test_bytes_to_string
103 m.def("strlen", [](char *s) { return strlen(s); });
104 m.def("string_length", [](std::string s) { return s.length(); });
105
106 #ifdef PYBIND11_HAS_U8STRING
107 m.attr("has_u8string") = true;
108 m.def("good_utf8_u8string", []() { return std::u8string(u8"Say utf8\u203d \U0001f382 \U0001d400"); }); // Say utf8‽
109 m.def("bad_utf8_u8string", []() { return std::u8string((const char8_t*)"abc\xd0" "def"); });
110
111 m.def("u8_char8_Z", []() -> char8_t { return u8'Z'; });
112
113 // test_single_char_arguments
114 m.def("ord_char8", [](char8_t c) -> int { return static_cast<unsigned char>(c); });
115 m.def("ord_char8_lv", [](char8_t &c) -> int { return static_cast<unsigned char>(c); });
116 #endif
117
118 // test_string_view
119 #ifdef PYBIND11_HAS_STRING_VIEW
120 m.attr("has_string_view") = true;
121 m.def("string_view_print", [](std::string_view s) { py::print(s, s.size()); });
122 m.def("string_view16_print", [](std::u16string_view s) { py::print(s, s.size()); });
123 m.def("string_view32_print", [](std::u32string_view s) { py::print(s, s.size()); });
124 m.def("string_view_chars", [](std::string_view s) { py::list l; for (auto c : s) l.append((std::uint8_t) c); return l; });
125 m.def("string_view16_chars", [](std::u16string_view s) { py::list l; for (auto c : s) l.append((int) c); return l; });
126 m.def("string_view32_chars", [](std::u32string_view s) { py::list l; for (auto c : s) l.append((int) c); return l; });
127 m.def("string_view_return", []() { return std::string_view((const char*)u8"utf8 secret \U0001f382"); });
128 m.def("string_view16_return", []() { return std::u16string_view(u"utf16 secret \U0001f382"); });
129 m.def("string_view32_return", []() { return std::u32string_view(U"utf32 secret \U0001f382"); });
130
131 # ifdef PYBIND11_HAS_U8STRING
132 m.def("string_view8_print", [](std::u8string_view s) { py::print(s, s.size()); });
133 m.def("string_view8_chars", [](std::u8string_view s) { py::list l; for (auto c : s) l.append((std::uint8_t) c); return l; });
134 m.def("string_view8_return", []() { return std::u8string_view(u8"utf8 secret \U0001f382"); });
135 # endif
136 #endif
137
138 // test_integer_casting
139 m.def("i32_str", [](std::int32_t v) { return std::to_string(v); });
140 m.def("u32_str", [](std::uint32_t v) { return std::to_string(v); });
141 m.def("i64_str", [](std::int64_t v) { return std::to_string(v); });
142 m.def("u64_str", [](std::uint64_t v) { return std::to_string(v); });
143
144 // test_int_convert
145 m.def("int_passthrough", [](int arg) { return arg; });
146 m.def("int_passthrough_noconvert", [](int arg) { return arg; }, py::arg{}.noconvert());
147
148 // test_tuple
149 m.def("pair_passthrough", [](std::pair<bool, std::string> input) {
150 return std::make_pair(input.second, input.first);
151 }, "Return a pair in reversed order");
152 m.def("tuple_passthrough", [](std::tuple<bool, std::string, int> input) {
153 return std::make_tuple(std::get<2>(input), std::get<1>(input), std::get<0>(input));
154 }, "Return a triple in reversed order");
155 m.def("empty_tuple", []() { return std::tuple<>(); });
156 static std::pair<RValueCaster, RValueCaster> lvpair;
157 static std::tuple<RValueCaster, RValueCaster, RValueCaster> lvtuple;
158 static std::pair<RValueCaster, std::tuple<RValueCaster, std::pair<RValueCaster, RValueCaster>>> lvnested;
159 m.def("rvalue_pair", []() { return std::make_pair(RValueCaster{}, RValueCaster{}); });
160 m.def("lvalue_pair", []() -> const decltype(lvpair) & { return lvpair; });
161 m.def("rvalue_tuple", []() { return std::make_tuple(RValueCaster{}, RValueCaster{}, RValueCaster{}); });
162 m.def("lvalue_tuple", []() -> const decltype(lvtuple) & { return lvtuple; });
163 m.def("rvalue_nested", []() {
164 return std::make_pair(RValueCaster{}, std::make_tuple(RValueCaster{}, std::make_pair(RValueCaster{}, RValueCaster{}))); });
165 m.def("lvalue_nested", []() -> const decltype(lvnested) & { return lvnested; });
166
167 static std::pair<int, std::string> int_string_pair{2, "items"};
168 m.def("int_string_pair", []() { return &int_string_pair; });
169
170 // test_builtins_cast_return_none
171 m.def("return_none_string", []() -> std::string * { return nullptr; });
172 m.def("return_none_char", []() -> const char * { return nullptr; });
173 m.def("return_none_bool", []() -> bool * { return nullptr; });
174 m.def("return_none_int", []() -> int * { return nullptr; });
175 m.def("return_none_float", []() -> float * { return nullptr; });
176 m.def("return_none_pair", []() -> std::pair<int,int> * { return nullptr; });
177
178 // test_none_deferred
179 m.def("defer_none_cstring", [](char *) { return false; });
180 m.def("defer_none_cstring", [](py::none) { return true; });
181 m.def("defer_none_custom", [](UserType *) { return false; });
182 m.def("defer_none_custom", [](py::none) { return true; });
183 m.def("nodefer_none_void", [](void *) { return true; });
184 m.def("nodefer_none_void", [](py::none) { return false; });
185
186 // test_void_caster
187 m.def("load_nullptr_t", [](std::nullptr_t) {}); // not useful, but it should still compile
188 m.def("cast_nullptr_t", []() { return std::nullptr_t{}; });
189
190 // [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works.
191
192 // test_bool_caster
193 m.def("bool_passthrough", [](bool arg) { return arg; });
194 m.def("bool_passthrough_noconvert", [](bool arg) { return arg; }, py::arg{}.noconvert());
195
196 // TODO: This should be disabled and fixed in future Intel compilers
197 #if !defined(__INTEL_COMPILER)
198 // Test "bool_passthrough_noconvert" again, but using () instead of {} to construct py::arg
199 // When compiled with the Intel compiler, this results in segmentation faults when importing
200 // the module. Tested with icc (ICC) 2021.1 Beta 20200827, this should be tested again when
201 // a newer version of icc is available.
202 m.def("bool_passthrough_noconvert2", [](bool arg) { return arg; }, py::arg().noconvert());
203 #endif
204
205 // test_reference_wrapper
206 m.def("refwrap_builtin", [](std::reference_wrapper<int> p) { return 10 * p.get(); });
207 m.def("refwrap_usertype", [](std::reference_wrapper<UserType> p) { return p.get().value(); });
208 m.def("refwrap_usertype_const", [](std::reference_wrapper<const UserType> p) { return p.get().value(); });
209
210 m.def("refwrap_lvalue", []() -> std::reference_wrapper<UserType> {
211 static UserType x(1);
212 return std::ref(x);
213 });
214 m.def("refwrap_lvalue_const", []() -> std::reference_wrapper<const UserType> {
215 static UserType x(1);
216 return std::cref(x);
217 });
218
219 // Not currently supported (std::pair caster has return-by-value cast operator);
220 // triggers static_assert failure.
221 //m.def("refwrap_pair", [](std::reference_wrapper<std::pair<int, int>>) { });
222
223 m.def("refwrap_list", [](bool copy) {
224 static IncType x1(1), x2(2);
225 py::list l;
226 for (auto &f : {std::ref(x1), std::ref(x2)}) {
227 l.append(py::cast(f, copy ? py::return_value_policy::copy
228 : py::return_value_policy::reference));
229 }
230 return l;
231 }, "copy"_a);
232
233 m.def("refwrap_iiw", [](const IncType &w) { return w.value(); });
234 m.def("refwrap_call_iiw", [](IncType &w, py::function f) {
235 py::list l;
236 l.append(f(std::ref(w)));
237 l.append(f(std::cref(w)));
238 IncType x(w.value());
239 l.append(f(std::ref(x)));
240 IncType y(w.value());
241 auto r3 = std::ref(y);
242 l.append(f(r3));
243 return l;
244 });
245
246 // test_complex
247 m.def("complex_cast", [](float x) { return "{}"_s.format(x); });
248 m.def("complex_cast", [](std::complex<float> x) { return "({}, {})"_s.format(x.real(), x.imag()); });
249
250 // test int vs. long (Python 2)
251 m.def("int_cast", []() {return (int) 42;});
252 m.def("long_cast", []() {return (long) 42;});
253 m.def("longlong_cast", []() {return ULLONG_MAX;});
254
255 /// test void* cast operator
256 m.def("test_void_caster", []() -> bool {
257 void *v = (void *) 0xabcd;
258 py::object o = py::cast(v);
259 return py::cast<void *>(o) == v;
260 });
261
262 // Tests const/non-const propagation in cast_op.
263 m.def("takes", [](ConstRefCasted x) { return x.tag; });
264 m.def("takes_move", [](ConstRefCasted&& x) { return x.tag; });
265 m.def("takes_ptr", [](ConstRefCasted* x) { return x->tag; });
266 m.def("takes_ref", [](ConstRefCasted& x) { return x.tag; });
267 m.def("takes_ref_wrap", [](std::reference_wrapper<ConstRefCasted> x) { return x.get().tag; });
268 m.def("takes_const_ptr", [](const ConstRefCasted* x) { return x->tag; });
269 m.def("takes_const_ref", [](const ConstRefCasted& x) { return x.tag; });
270 m.def("takes_const_ref_wrap", [](std::reference_wrapper<const ConstRefCasted> x) { return x.get().tag; });
271 }
272