ΞΌHAL (v2.8.17)
Part of the IPbus software repository
β€’All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
test_builtin_casters.cpp
Go to the documentation of this file.
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/complex.h>
11
12#include "pybind11_tests.h"
13
14struct ConstRefCasted {
15 int tag;
16};
17
20template <>
22public:
23 static constexpr auto name = const_name<ConstRefCasted>();
24
25 // Input is unimportant, a new value will always be constructed based on the
26 // cast operator.
27 bool load(handle, bool) { return true; }
28
29 explicit operator ConstRefCasted &&() {
30 value = {1};
31 // NOLINTNEXTLINE(performance-move-const-arg)
32 return std::move(value);
33 }
34 explicit operator ConstRefCasted &() {
35 value = {2};
36 return value;
37 }
38 explicit operator ConstRefCasted *() {
39 value = {3};
40 return &value;
41 }
42
43 explicit operator const ConstRefCasted &() {
44 value = {4};
45 return value;
46 }
47 explicit operator const ConstRefCasted *() {
48 value = {5};
49 return &value;
50 }
51
52 // custom cast_op to explicitly propagate types to the conversion operators.
53 template <typename T_>
57 std::is_same<remove_reference_t<T_>, const ConstRefCasted *>::value,
58 const ConstRefCasted *,
60 std::is_same<T_, const ConstRefCasted &>::value,
61 const ConstRefCasted &,
67 /* else */ ConstRefCasted &&>>>>;
68
69private:
71};
74
75TEST_SUBMODULE(builtin_casters, m) {
76 PYBIND11_WARNING_PUSH
78
79 // test_simple_string
80 m.def("string_roundtrip", [](const char *s) { return s; });
81
82 // test_unicode_conversion
83 // Some test characters in utf16 and utf32 encodings. The last one (the 𝐀) contains a null
84 // byte
85 char32_t a32 = 0x61 /*a*/, z32 = 0x7a /*z*/, ib32 = 0x203d /*β€½*/, cake32 = 0x1f382 /*πŸŽ‚*/,
86 mathbfA32 = 0x1d400 /*𝐀*/;
87 char16_t b16 = 0x62 /*b*/, z16 = 0x7a, ib16 = 0x203d, cake16_1 = 0xd83c, cake16_2 = 0xdf82,
88 mathbfA16_1 = 0xd835, mathbfA16_2 = 0xdc00;
89 std::wstring wstr;
90 wstr.push_back(0x61); // a
91 wstr.push_back(0x2e18); // ⸘
92 if (sizeof(wchar_t) == 2) {
93 wstr.push_back(mathbfA16_1);
94 wstr.push_back(mathbfA16_2);
95 } // 𝐀, utf16
96 else {
97 wstr.push_back((wchar_t) mathbfA32);
98 } // 𝐀, utf32
99 wstr.push_back(0x7a); // z
100
101 m.def("good_utf8_string", []() {
102 return std::string((const char *) u8"Say utf8\u203d \U0001f382 \U0001d400");
103 }); // Say utf8β€½ πŸŽ‚ 𝐀
104 m.def("good_utf16_string", [=]() {
105 return std::u16string({b16, ib16, cake16_1, cake16_2, mathbfA16_1, mathbfA16_2, z16});
106 }); // bβ€½πŸŽ‚π€z
107 m.def("good_utf32_string", [=]() {
108 return std::u32string({a32, mathbfA32, cake32, ib32, z32});
109 }); // aπ€πŸŽ‚β€½z
110 m.def("good_wchar_string", [=]() { return wstr; }); // a‽𝐀z
111 m.def("bad_utf8_string", []() {
112 return std::string("abc\xd0"
113 "def");
114 });
115 m.def("bad_utf16_string", [=]() { return std::u16string({b16, char16_t(0xd800), z16}); });
116 // Under Python 2.7, invalid unicode UTF-32 characters didn't appear to trigger
117 // UnicodeDecodeError
118 m.def("bad_utf32_string", [=]() { return std::u32string({a32, char32_t(0xd800), z32}); });
119 if (sizeof(wchar_t) == 2) {
120 m.def("bad_wchar_string", [=]() {
121 return std::wstring({wchar_t(0x61), wchar_t(0xd800)});
122 });
123 }
124 m.def("u8_Z", []() -> char { return 'Z'; });
125 m.def("u8_eacute", []() -> char { return '\xe9'; });
126 m.def("u16_ibang", [=]() -> char16_t { return ib16; });
127 m.def("u32_mathbfA", [=]() -> char32_t { return mathbfA32; });
128 m.def("wchar_heart", []() -> wchar_t { return 0x2665; });
129
130 // test_single_char_arguments
131 m.attr("wchar_size") = py::cast(sizeof(wchar_t));
132 m.def("ord_char", [](char c) -> int { return static_cast<unsigned char>(c); });
133 m.def("ord_char_lv", [](char &c) -> int { return static_cast<unsigned char>(c); });
134 m.def("ord_char16", [](char16_t c) -> uint16_t { return c; });
135 m.def("ord_char16_lv", [](char16_t &c) -> uint16_t { return c; });
136 m.def("ord_char32", [](char32_t c) -> uint32_t { return c; });
137 m.def("ord_wchar", [](wchar_t c) -> int { return c; });
138
139 // test_bytes_to_string
140 m.def("strlen", [](char *s) { return strlen(s); });
141 m.def("string_length", [](const std::string &s) { return s.length(); });
142
143#ifdef PYBIND11_HAS_U8STRING
144 m.attr("has_u8string") = true;
145 m.def("good_utf8_u8string", []() {
146 return std::u8string(u8"Say utf8\u203d \U0001f382 \U0001d400");
147 }); // Say utf8β€½ πŸŽ‚ 𝐀
148 m.def("bad_utf8_u8string", []() {
149 return std::u8string((const char8_t *) "abc\xd0"
150 "def");
151 });
152
153 m.def("u8_char8_Z", []() -> char8_t { return u8'Z'; });
154
155 // test_single_char_arguments
156 m.def("ord_char8", [](char8_t c) -> int { return static_cast<unsigned char>(c); });
157 m.def("ord_char8_lv", [](char8_t &c) -> int { return static_cast<unsigned char>(c); });
158#endif
159
160 // test_string_view
161#ifdef PYBIND11_HAS_STRING_VIEW
162 m.attr("has_string_view") = true;
163 m.def("string_view_print", [](std::string_view s) { py::print(s, s.size()); });
164 m.def("string_view16_print", [](std::u16string_view s) { py::print(s, s.size()); });
165 m.def("string_view32_print", [](std::u32string_view s) { py::print(s, s.size()); });
166 m.def("string_view_chars", [](std::string_view s) {
167 py::list l;
168 for (auto c : s) {
169 l.append((std::uint8_t) c);
170 }
171 return l;
172 });
173 m.def("string_view16_chars", [](std::u16string_view s) {
174 py::list l;
175 for (auto c : s) {
176 l.append((int) c);
177 }
178 return l;
179 });
180 m.def("string_view32_chars", [](std::u32string_view s) {
181 py::list l;
182 for (auto c : s) {
183 l.append((int) c);
184 }
185 return l;
186 });
187 m.def("string_view_return",
188 []() { return std::string_view((const char *) u8"utf8 secret \U0001f382"); });
189 m.def("string_view16_return",
190 []() { return std::u16string_view(u"utf16 secret \U0001f382"); });
191 m.def("string_view32_return",
192 []() { return std::u32string_view(U"utf32 secret \U0001f382"); });
193
194 // The inner lambdas here are to also test implicit conversion
195 using namespace std::literals;
196 m.def("string_view_bytes",
197 []() { return [](py::bytes b) { return b; }("abc \x80\x80 def"sv); });
198 m.def("string_view_str",
199 []() { return [](py::str s) { return s; }("abc \342\200\275 def"sv); });
200 m.def("string_view_from_bytes",
201 [](const py::bytes &b) { return [](std::string_view s) { return s; }(b); });
202 m.def("string_view_memoryview", []() {
203 static constexpr auto val = "Have some \360\237\216\202"sv;
204 return py::memoryview::from_memory(val);
205 });
206
207# ifdef PYBIND11_HAS_U8STRING
208 m.def("string_view8_print", [](std::u8string_view s) { py::print(s, s.size()); });
209 m.def("string_view8_chars", [](std::u8string_view s) {
210 py::list l;
211 for (auto c : s)
212 l.append((std::uint8_t) c);
213 return l;
214 });
215 m.def("string_view8_return", []() { return std::u8string_view(u8"utf8 secret \U0001f382"); });
216 m.def("string_view8_str", []() { return py::str{std::u8string_view{u8"abc β€½ def"}}; });
217# endif
218
219 struct TypeWithBothOperatorStringAndStringView {
220 // NOLINTNEXTLINE(google-explicit-constructor)
221 operator std::string() const { return "success"; }
222 // NOLINTNEXTLINE(google-explicit-constructor)
223 operator std::string_view() const { return "failure"; }
224 };
225 m.def("bytes_from_type_with_both_operator_string_and_string_view",
226 []() { return py::bytes(TypeWithBothOperatorStringAndStringView()); });
227 m.def("str_from_type_with_both_operator_string_and_string_view",
228 []() { return py::str(TypeWithBothOperatorStringAndStringView()); });
229#endif
230
231 // test_integer_casting
232 m.def("i32_str", [](std::int32_t v) { return std::to_string(v); });
233 m.def("u32_str", [](std::uint32_t v) { return std::to_string(v); });
234 m.def("i64_str", [](std::int64_t v) { return std::to_string(v); });
235 m.def("u64_str", [](std::uint64_t v) { return std::to_string(v); });
236
237 // test_int_convert
238 m.def("int_passthrough", [](int arg) { return arg; });
239 m.def(
240 "int_passthrough_noconvert", [](int arg) { return arg; }, py::arg{}.noconvert());
241
242 // test_tuple
243 m.def(
244 "pair_passthrough",
245 [](const std::pair<bool, std::string> &input) {
246 return std::make_pair(input.second, input.first);
247 },
248 "Return a pair in reversed order");
249 m.def(
250 "tuple_passthrough",
251 [](std::tuple<bool, std::string, int> input) {
252 return std::make_tuple(std::get<2>(input), std::get<1>(input), std::get<0>(input));
253 },
254 "Return a triple in reversed order");
255 m.def("empty_tuple", []() { return std::tuple<>(); });
256 static std::pair<RValueCaster, RValueCaster> lvpair;
257 static std::tuple<RValueCaster, RValueCaster, RValueCaster> lvtuple;
258 static std::pair<RValueCaster, std::tuple<RValueCaster, std::pair<RValueCaster, RValueCaster>>>
259 lvnested;
260 m.def("rvalue_pair", []() { return std::make_pair(RValueCaster{}, RValueCaster{}); });
261 m.def("lvalue_pair", []() -> const decltype(lvpair) & { return lvpair; });
262 m.def("rvalue_tuple",
263 []() { return std::make_tuple(RValueCaster{}, RValueCaster{}, RValueCaster{}); });
264 m.def("lvalue_tuple", []() -> const decltype(lvtuple) & { return lvtuple; });
265 m.def("rvalue_nested", []() {
266 return std::make_pair(
267 RValueCaster{},
268 std::make_tuple(RValueCaster{}, std::make_pair(RValueCaster{}, RValueCaster{})));
269 });
270 m.def("lvalue_nested", []() -> const decltype(lvnested) & { return lvnested; });
271
272 m.def(
273 "int_string_pair",
274 []() {
275 // Using no-destructor idiom to side-step warnings from overzealous compilers.
276 static auto *int_string_pair = new std::pair<int, std::string>{2, "items"};
277 return int_string_pair;
278 },
279 py::return_value_policy::reference);
280
281 // test_builtins_cast_return_none
282 m.def("return_none_string", []() -> std::string * { return nullptr; });
283 m.def("return_none_char", []() -> const char * { return nullptr; });
284 m.def("return_none_bool", []() -> bool * { return nullptr; });
285 m.def("return_none_int", []() -> int * { return nullptr; });
286 m.def("return_none_float", []() -> float * { return nullptr; });
287 m.def("return_none_pair", []() -> std::pair<int, int> * { return nullptr; });
288
289 // test_none_deferred
290 m.def("defer_none_cstring", [](char *) { return false; });
291 m.def("defer_none_cstring", [](const py::none &) { return true; });
292 m.def("defer_none_custom", [](UserType *) { return false; });
293 m.def("defer_none_custom", [](const py::none &) { return true; });
294 m.def("nodefer_none_void", [](void *) { return true; });
295 m.def("nodefer_none_void", [](const py::none &) { return false; });
296
297 // test_void_caster
298 m.def("load_nullptr_t", [](std::nullptr_t) {}); // not useful, but it should still compile
299 m.def("cast_nullptr_t", []() { return std::nullptr_t{}; });
300
301 // [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works.
302
303 // test_bool_caster
304 m.def("bool_passthrough", [](bool arg) { return arg; });
305 m.def(
306 "bool_passthrough_noconvert", [](bool arg) { return arg; }, py::arg{}.noconvert());
307
308 // TODO: This should be disabled and fixed in future Intel compilers
309#if !defined(__INTEL_COMPILER)
310 // Test "bool_passthrough_noconvert" again, but using () instead of {} to construct py::arg
311 // When compiled with the Intel compiler, this results in segmentation faults when importing
312 // the module. Tested with icc (ICC) 2021.1 Beta 20200827, this should be tested again when
313 // a newer version of icc is available.
314 m.def(
315 "bool_passthrough_noconvert2", [](bool arg) { return arg; }, py::arg().noconvert());
316#endif
317
318 // test_reference_wrapper
319 m.def("refwrap_builtin", [](std::reference_wrapper<int> p) { return 10 * p.get(); });
320 m.def("refwrap_usertype", [](std::reference_wrapper<UserType> p) { return p.get().value(); });
321 m.def("refwrap_usertype_const",
322 [](std::reference_wrapper<const UserType> p) { return p.get().value(); });
323
324 m.def("refwrap_lvalue", []() -> std::reference_wrapper<UserType> {
325 static UserType x(1);
326 return std::ref(x);
327 });
328 m.def("refwrap_lvalue_const", []() -> std::reference_wrapper<const UserType> {
329 static UserType x(1);
330 return std::cref(x);
331 });
332
333 // Not currently supported (std::pair caster has return-by-value cast operator);
334 // triggers static_assert failure.
335 // m.def("refwrap_pair", [](std::reference_wrapper<std::pair<int, int>>) { });
336
337 m.def(
338 "refwrap_list",
339 [](bool copy) {
340 static IncType x1(1), x2(2);
341 py::list l;
342 for (const auto &f : {std::ref(x1), std::ref(x2)}) {
343 l.append(py::cast(
344 f, copy ? py::return_value_policy::copy : py::return_value_policy::reference));
345 }
346 return l;
347 },
348 "copy"_a);
349
350 m.def("refwrap_iiw", [](const IncType &w) { return w.value(); });
351 m.def("refwrap_call_iiw", [](IncType &w, const py::function &f) {
352 py::list l;
353 l.append(f(std::ref(w)));
354 l.append(f(std::cref(w)));
355 IncType x(w.value());
356 l.append(f(std::ref(x)));
357 IncType y(w.value());
358 auto r3 = std::ref(y);
359 l.append(f(r3));
360 return l;
361 });
362
363 // test_complex
364 m.def("complex_cast", [](float x) { return "{}"_s.format(x); });
365 m.def("complex_cast",
366 [](std::complex<float> x) { return "({}, {})"_s.format(x.real(), x.imag()); });
367
368 // test int vs. long (Python 2)
369 m.def("int_cast", []() { return (int) 42; });
370 m.def("long_cast", []() { return (long) 42; });
371 m.def("longlong_cast", []() { return ULLONG_MAX; });
372
374 m.def("test_void_caster", []() -> bool {
375 void *v = (void *) 0xabcd;
376 py::object o = py::cast(v);
377 return py::cast<void *>(o) == v;
378 });
379
380 // Tests const/non-const propagation in cast_op.
381 m.def("takes", [](ConstRefCasted x) { return x.tag; });
382 m.def("takes_move", [](ConstRefCasted &&x) { return x.tag; });
383 m.def("takes_ptr", [](ConstRefCasted *x) { return x->tag; });
384 m.def("takes_ref", [](ConstRefCasted &x) { return x.tag; });
385 m.def("takes_ref_wrap", [](std::reference_wrapper<ConstRefCasted> x) { return x.get().tag; });
386 m.def("takes_const_ptr", [](const ConstRefCasted *x) { return x->tag; });
387 m.def("takes_const_ref", [](const ConstRefCasted &x) { return x.tag; });
388 m.def("takes_const_ref_wrap",
389 [](std::reference_wrapper<const ConstRefCasted> x) { return x.get().tag; });
390
392}
Like UserType, but increments value on copy for quick reference vs. copy tests.
A user-defined type which is exported and can be used by any test.
int value() const
\rst Holds a reference to a Python object (no reference counting)
Definition: pytypes.h:194
conditional_t< std::is_same< remove_reference_t< T_ >, const ConstRefCasted * >::value, const ConstRefCasted *, conditional_t< std::is_same< T_, const ConstRefCasted & >::value, const ConstRefCasted &, conditional_t< std::is_same< remove_reference_t< T_ >, ConstRefCasted * >::value, ConstRefCasted *, conditional_t< std::is_same< T_, ConstRefCasted & >::value, ConstRefCasted &, ConstRefCasted && > > > > cast_op_type
PYBIND11_WARNING_PUSH PYBIND11_WARNING_POP
Definition: matrix.h:35
#define PYBIND11_NAMESPACE_END(name)
Definition: common.h:21
#define PYBIND11_NAMESPACE_BEGIN(name)
Definition: common.h:20
typename std::conditional< B, T, F >::type conditional_t
Definition: common.h:627
@ copy
Create a new copy of the returned object, which will be owned by Python.
#define TEST_SUBMODULE(name, variable)
#define PYBIND11_WARNING_DISABLE_MSVC(name)
Definition: common.h:55
Custom cast-only type that casts to a string "rvalue" or "lvalue" depending on the cast context.
Annotation for arguments.
Definition: cast.h:1238
arg & noconvert(bool flag=true)
Indicate that the type should not be converted in the type caster.
Definition: cast.h:1247
Annotation for function names.
Definition: attr.h:47