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 
15  int tag;
16 };
17 
20 template <>
22 public:
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_>
54  using cast_op_type =
57  std::is_same<remove_reference_t<T_>, const ConstRefCasted *>::value,
58  const ConstRefCasted *,
61  const ConstRefCasted &,
64  ConstRefCasted *,
66  ConstRefCasted &,
67  /* else */ ConstRefCasted &&>>>>;
68 
69 private:
70  ConstRefCasted value = {0};
71 };
74 
75 TEST_SUBMODULE(builtin_casters, m) {
76  // test_simple_string
77  m.def("string_roundtrip", [](const char *s) { return s; });
78 
79  // test_unicode_conversion
80  // Some test characters in utf16 and utf32 encodings. The last one (the 𝐀) contains a null
81  // byte
82  char32_t a32 = 0x61 /*a*/, z32 = 0x7a /*z*/, ib32 = 0x203d /*β€½*/, cake32 = 0x1f382 /*πŸŽ‚*/,
83  mathbfA32 = 0x1d400 /*𝐀*/;
84  char16_t b16 = 0x62 /*b*/, z16 = 0x7a, ib16 = 0x203d, cake16_1 = 0xd83c, cake16_2 = 0xdf82,
85  mathbfA16_1 = 0xd835, mathbfA16_2 = 0xdc00;
86  std::wstring wstr;
87  wstr.push_back(0x61); // a
88  wstr.push_back(0x2e18); // ⸘
89  if (PYBIND11_SILENCE_MSVC_C4127(sizeof(wchar_t) == 2)) {
90  wstr.push_back(mathbfA16_1);
91  wstr.push_back(mathbfA16_2);
92  } // 𝐀, utf16
93  else {
94  wstr.push_back((wchar_t) mathbfA32);
95  } // 𝐀, utf32
96  wstr.push_back(0x7a); // z
97 
98  m.def("good_utf8_string", []() {
99  return std::string((const char *) u8"Say utf8\u203d \U0001f382 \U0001d400");
100  }); // Say utf8β€½ πŸŽ‚ 𝐀
101  m.def("good_utf16_string", [=]() {
102  return std::u16string({b16, ib16, cake16_1, cake16_2, mathbfA16_1, mathbfA16_2, z16});
103  }); // bβ€½πŸŽ‚π€z
104  m.def("good_utf32_string", [=]() {
105  return std::u32string({a32, mathbfA32, cake32, ib32, z32});
106  }); // aπ€πŸŽ‚β€½z
107  m.def("good_wchar_string", [=]() { return wstr; }); // a‽𝐀z
108  m.def("bad_utf8_string", []() {
109  return std::string("abc\xd0"
110  "def");
111  });
112  m.def("bad_utf16_string", [=]() { return std::u16string({b16, char16_t(0xd800), z16}); });
113  // Under Python 2.7, invalid unicode UTF-32 characters didn't appear to trigger
114  // UnicodeDecodeError
115  m.def("bad_utf32_string", [=]() { return std::u32string({a32, char32_t(0xd800), z32}); });
116  if (PYBIND11_SILENCE_MSVC_C4127(sizeof(wchar_t) == 2)) {
117  m.def("bad_wchar_string", [=]() {
118  return std::wstring({wchar_t(0x61), wchar_t(0xd800)});
119  });
120  }
121  m.def("u8_Z", []() -> char { return 'Z'; });
122  m.def("u8_eacute", []() -> char { return '\xe9'; });
123  m.def("u16_ibang", [=]() -> char16_t { return ib16; });
124  m.def("u32_mathbfA", [=]() -> char32_t { return mathbfA32; });
125  m.def("wchar_heart", []() -> wchar_t { return 0x2665; });
126 
127  // test_single_char_arguments
128  m.attr("wchar_size") = py::cast(sizeof(wchar_t));
129  m.def("ord_char", [](char c) -> int { return static_cast<unsigned char>(c); });
130  m.def("ord_char_lv", [](char &c) -> int { return static_cast<unsigned char>(c); });
131  m.def("ord_char16", [](char16_t c) -> uint16_t { return c; });
132  m.def("ord_char16_lv", [](char16_t &c) -> uint16_t { return c; });
133  m.def("ord_char32", [](char32_t c) -> uint32_t { return c; });
134  m.def("ord_wchar", [](wchar_t c) -> int { return c; });
135 
136  // test_bytes_to_string
137  m.def("strlen", [](char *s) { return strlen(s); });
138  m.def("string_length", [](const std::string &s) { return s.length(); });
139 
140 #ifdef PYBIND11_HAS_U8STRING
141  m.attr("has_u8string") = true;
142  m.def("good_utf8_u8string", []() {
143  return std::u8string(u8"Say utf8\u203d \U0001f382 \U0001d400");
144  }); // Say utf8β€½ πŸŽ‚ 𝐀
145  m.def("bad_utf8_u8string", []() {
146  return std::u8string((const char8_t *) "abc\xd0"
147  "def");
148  });
149 
150  m.def("u8_char8_Z", []() -> char8_t { return u8'Z'; });
151 
152  // test_single_char_arguments
153  m.def("ord_char8", [](char8_t c) -> int { return static_cast<unsigned char>(c); });
154  m.def("ord_char8_lv", [](char8_t &c) -> int { return static_cast<unsigned char>(c); });
155 #endif
156 
157  // test_string_view
158 #ifdef PYBIND11_HAS_STRING_VIEW
159  m.attr("has_string_view") = true;
160  m.def("string_view_print", [](std::string_view s) { py::print(s, s.size()); });
161  m.def("string_view16_print", [](std::u16string_view s) { py::print(s, s.size()); });
162  m.def("string_view32_print", [](std::u32string_view s) { py::print(s, s.size()); });
163  m.def("string_view_chars", [](std::string_view s) {
164  py::list l;
165  for (auto c : s) {
166  l.append((std::uint8_t) c);
167  }
168  return l;
169  });
170  m.def("string_view16_chars", [](std::u16string_view s) {
171  py::list l;
172  for (auto c : s) {
173  l.append((int) c);
174  }
175  return l;
176  });
177  m.def("string_view32_chars", [](std::u32string_view s) {
178  py::list l;
179  for (auto c : s) {
180  l.append((int) c);
181  }
182  return l;
183  });
184  m.def("string_view_return",
185  []() { return std::string_view((const char *) u8"utf8 secret \U0001f382"); });
186  m.def("string_view16_return",
187  []() { return std::u16string_view(u"utf16 secret \U0001f382"); });
188  m.def("string_view32_return",
189  []() { return std::u32string_view(U"utf32 secret \U0001f382"); });
190 
191  // The inner lambdas here are to also test implicit conversion
192  using namespace std::literals;
193  m.def("string_view_bytes",
194  []() { return [](py::bytes b) { return b; }("abc \x80\x80 def"sv); });
195  m.def("string_view_str",
196  []() { return [](py::str s) { return s; }("abc \342\200\275 def"sv); });
197  m.def("string_view_from_bytes",
198  [](const py::bytes &b) { return [](std::string_view s) { return s; }(b); });
199  m.def("string_view_memoryview", []() {
200  static constexpr auto val = "Have some \360\237\216\202"sv;
201  return py::memoryview::from_memory(val);
202  });
203 
204 # ifdef PYBIND11_HAS_U8STRING
205  m.def("string_view8_print", [](std::u8string_view s) { py::print(s, s.size()); });
206  m.def("string_view8_chars", [](std::u8string_view s) {
207  py::list l;
208  for (auto c : s)
209  l.append((std::uint8_t) c);
210  return l;
211  });
212  m.def("string_view8_return", []() { return std::u8string_view(u8"utf8 secret \U0001f382"); });
213  m.def("string_view8_str", []() { return py::str{std::u8string_view{u8"abc β€½ def"}}; });
214 # endif
215 
216  struct TypeWithBothOperatorStringAndStringView {
217  // NOLINTNEXTLINE(google-explicit-constructor)
218  operator std::string() const { return "success"; }
219  // NOLINTNEXTLINE(google-explicit-constructor)
220  operator std::string_view() const { return "failure"; }
221  };
222  m.def("bytes_from_type_with_both_operator_string_and_string_view",
223  []() { return py::bytes(TypeWithBothOperatorStringAndStringView()); });
224  m.def("str_from_type_with_both_operator_string_and_string_view",
225  []() { return py::str(TypeWithBothOperatorStringAndStringView()); });
226 #endif
227 
228  // test_integer_casting
229  m.def("i32_str", [](std::int32_t v) { return std::to_string(v); });
230  m.def("u32_str", [](std::uint32_t v) { return std::to_string(v); });
231  m.def("i64_str", [](std::int64_t v) { return std::to_string(v); });
232  m.def("u64_str", [](std::uint64_t v) { return std::to_string(v); });
233 
234  // test_int_convert
235  m.def("int_passthrough", [](int arg) { return arg; });
236  m.def(
237  "int_passthrough_noconvert", [](int arg) { return arg; }, py::arg{}.noconvert());
238 
239  // test_tuple
240  m.def(
241  "pair_passthrough",
242  [](const std::pair<bool, std::string> &input) {
243  return std::make_pair(input.second, input.first);
244  },
245  "Return a pair in reversed order");
246  m.def(
247  "tuple_passthrough",
248  [](std::tuple<bool, std::string, int> input) {
249  return std::make_tuple(std::get<2>(input), std::get<1>(input), std::get<0>(input));
250  },
251  "Return a triple in reversed order");
252  m.def("empty_tuple", []() { return std::tuple<>(); });
253  static std::pair<RValueCaster, RValueCaster> lvpair;
254  static std::tuple<RValueCaster, RValueCaster, RValueCaster> lvtuple;
255  static std::pair<RValueCaster, std::tuple<RValueCaster, std::pair<RValueCaster, RValueCaster>>>
256  lvnested;
257  m.def("rvalue_pair", []() { return std::make_pair(RValueCaster{}, RValueCaster{}); });
258  m.def("lvalue_pair", []() -> const decltype(lvpair) & { return lvpair; });
259  m.def("rvalue_tuple",
260  []() { return std::make_tuple(RValueCaster{}, RValueCaster{}, RValueCaster{}); });
261  m.def("lvalue_tuple", []() -> const decltype(lvtuple) & { return lvtuple; });
262  m.def("rvalue_nested", []() {
263  return std::make_pair(
264  RValueCaster{},
265  std::make_tuple(RValueCaster{}, std::make_pair(RValueCaster{}, RValueCaster{})));
266  });
267  m.def("lvalue_nested", []() -> const decltype(lvnested) & { return lvnested; });
268 
269  static std::pair<int, std::string> int_string_pair{2, "items"};
270  m.def(
271  "int_string_pair", []() { return &int_string_pair; }, py::return_value_policy::reference);
272 
273  // test_builtins_cast_return_none
274  m.def("return_none_string", []() -> std::string * { return nullptr; });
275  m.def("return_none_char", []() -> const char * { return nullptr; });
276  m.def("return_none_bool", []() -> bool * { return nullptr; });
277  m.def("return_none_int", []() -> int * { return nullptr; });
278  m.def("return_none_float", []() -> float * { return nullptr; });
279  m.def("return_none_pair", []() -> std::pair<int, int> * { return nullptr; });
280 
281  // test_none_deferred
282  m.def("defer_none_cstring", [](char *) { return false; });
283  m.def("defer_none_cstring", [](const py::none &) { return true; });
284  m.def("defer_none_custom", [](UserType *) { return false; });
285  m.def("defer_none_custom", [](const py::none &) { return true; });
286  m.def("nodefer_none_void", [](void *) { return true; });
287  m.def("nodefer_none_void", [](const py::none &) { return false; });
288 
289  // test_void_caster
290  m.def("load_nullptr_t", [](std::nullptr_t) {}); // not useful, but it should still compile
291  m.def("cast_nullptr_t", []() { return std::nullptr_t{}; });
292 
293  // [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works.
294 
295  // test_bool_caster
296  m.def("bool_passthrough", [](bool arg) { return arg; });
297  m.def(
298  "bool_passthrough_noconvert", [](bool arg) { return arg; }, py::arg{}.noconvert());
299 
300  // TODO: This should be disabled and fixed in future Intel compilers
301 #if !defined(__INTEL_COMPILER)
302  // Test "bool_passthrough_noconvert" again, but using () instead of {} to construct py::arg
303  // When compiled with the Intel compiler, this results in segmentation faults when importing
304  // the module. Tested with icc (ICC) 2021.1 Beta 20200827, this should be tested again when
305  // a newer version of icc is available.
306  m.def(
307  "bool_passthrough_noconvert2", [](bool arg) { return arg; }, py::arg().noconvert());
308 #endif
309 
310  // test_reference_wrapper
311  m.def("refwrap_builtin", [](std::reference_wrapper<int> p) { return 10 * p.get(); });
312  m.def("refwrap_usertype", [](std::reference_wrapper<UserType> p) { return p.get().value(); });
313  m.def("refwrap_usertype_const",
314  [](std::reference_wrapper<const UserType> p) { return p.get().value(); });
315 
316  m.def("refwrap_lvalue", []() -> std::reference_wrapper<UserType> {
317  static UserType x(1);
318  return std::ref(x);
319  });
320  m.def("refwrap_lvalue_const", []() -> std::reference_wrapper<const UserType> {
321  static UserType x(1);
322  return std::cref(x);
323  });
324 
325  // Not currently supported (std::pair caster has return-by-value cast operator);
326  // triggers static_assert failure.
327  // m.def("refwrap_pair", [](std::reference_wrapper<std::pair<int, int>>) { });
328 
329  m.def(
330  "refwrap_list",
331  [](bool copy) {
332  static IncType x1(1), x2(2);
333  py::list l;
334  for (const auto &f : {std::ref(x1), std::ref(x2)}) {
335  l.append(py::cast(
336  f, copy ? py::return_value_policy::copy : py::return_value_policy::reference));
337  }
338  return l;
339  },
340  "copy"_a);
341 
342  m.def("refwrap_iiw", [](const IncType &w) { return w.value(); });
343  m.def("refwrap_call_iiw", [](IncType &w, const py::function &f) {
344  py::list l;
345  l.append(f(std::ref(w)));
346  l.append(f(std::cref(w)));
347  IncType x(w.value());
348  l.append(f(std::ref(x)));
349  IncType y(w.value());
350  auto r3 = std::ref(y);
351  l.append(f(r3));
352  return l;
353  });
354 
355  // test_complex
356  m.def("complex_cast", [](float x) { return "{}"_s.format(x); });
357  m.def("complex_cast",
358  [](std::complex<float> x) { return "({}, {})"_s.format(x.real(), x.imag()); });
359 
360  // test int vs. long (Python 2)
361  m.def("int_cast", []() { return (int) 42; });
362  m.def("long_cast", []() { return (long) 42; });
363  m.def("longlong_cast", []() { return ULLONG_MAX; });
364 
366  m.def("test_void_caster", []() -> bool {
367  void *v = (void *) 0xabcd;
368  py::object o = py::cast(v);
369  return py::cast<void *>(o) == v;
370  });
371 
372  // Tests const/non-const propagation in cast_op.
373  m.def("takes", [](ConstRefCasted x) { return x.tag; });
374  m.def("takes_move", [](ConstRefCasted &&x) { return x.tag; });
375  m.def("takes_ptr", [](ConstRefCasted *x) { return x->tag; });
376  m.def("takes_ref", [](ConstRefCasted &x) { return x.tag; });
377  m.def("takes_ref_wrap", [](std::reference_wrapper<ConstRefCasted> x) { return x.get().tag; });
378  m.def("takes_const_ptr", [](const ConstRefCasted *x) { return x->tag; });
379  m.def("takes_const_ref", [](const ConstRefCasted &x) { return x.tag; });
380  m.def("takes_const_ref_wrap",
381  [](std::reference_wrapper<const ConstRefCasted> x) { return x.get().tag; });
382 }
typename std::conditional< B, T, F >::type conditional_t
Matrix3f m
unsigned char uint8_t
Definition: ms_stdint.h:83
Scalar * y
Scalar * b
Definition: benchVecAdd.cpp:17
tuple make_tuple()
Definition: cast.h:1209
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
#define PYBIND11_SILENCE_MSVC_C4127(...)
Scalar Scalar * c
Definition: benchVecAdd.cpp:17
unsigned short uint16_t
Definition: ms_stdint.h:84
Pose3 x2(Rot3::Ypr(0.0, 0.0, 0.0), l2)
EIGEN_STRONG_INLINE Packet4f print(const Packet4f &a)
Definition: cast.h:1238
static const Line3 l(Rot3(), 1, 1)
signed __int64 int64_t
Definition: ms_stdint.h:94
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const ArgReturnType arg() const
Array< int, Dynamic, 1 > v
unsigned __int64 uint64_t
Definition: ms_stdint.h:95
unsigned int uint32_t
Definition: ms_stdint.h:85
EIGEN_DEVICE_FUNC NewType cast(const OldType &x)
signed int int32_t
Definition: ms_stdint.h:82
Point2(* f)(const Point3 &, OptionalJacobian< 2, 3 >)
RealScalar s
static const double r3
RowVector3d w
Pose3 x1
Definition: testPose3.cpp:663
float * p
Annotation for function names.
Definition: attr.h:48
int EIGEN_BLAS_FUNC() copy(int *n, RealScalar *px, int *incx, RealScalar *py, int *incy)
Definition: level1_impl.h:29
set noclip points set clip one set noclip two set bar set border lt lw set xdata set ydata set zdata set x2data set y2data set boxwidth set dummy x
#define PYBIND11_NAMESPACE_END(name)
#define PYBIND11_NAMESPACE_BEGIN(name)
TEST_SUBMODULE(builtin_casters, m)


gtsam
Author(s):
autogenerated on Tue Jul 4 2023 02:37:45