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 &,
67  /* else */ ConstRefCasted &&>>>>;
68 
69 private:
71 };
74 
75 TEST_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}); }); // aπ€πŸŽ‚β€½z
109  m.def("good_wchar_string", [=]() { return wstr; }); // a‽𝐀z
110  m.def("bad_utf8_string", []() {
111  return std::string("abc\xd0"
112  "def");
113  });
114  m.def("bad_utf16_string", [=]() { return std::u16string({b16, char16_t(0xd800), z16}); });
115  // Under Python 2.7, invalid unicode UTF-32 characters didn't appear to trigger
116  // UnicodeDecodeError
117  m.def("bad_utf32_string", [=]() { return std::u32string({a32, char32_t(0xd800), z32}); });
118  if (sizeof(wchar_t) == 2) {
119  m.def("bad_wchar_string",
120  [=]() { return std::wstring({wchar_t(0x61), wchar_t(0xd800)}); });
121  }
122  m.def("u8_Z", []() -> char { return 'Z'; });
123  m.def("u8_eacute", []() -> char { return '\xe9'; });
124  m.def("u16_ibang", [=]() -> char16_t { return ib16; });
125  m.def("u32_mathbfA", [=]() -> char32_t { return mathbfA32; });
126  m.def("wchar_heart", []() -> wchar_t { return 0x2665; });
127 
128  // test_single_char_arguments
129  m.attr("wchar_size") = py::cast(sizeof(wchar_t));
130  m.def("ord_char", [](char c) -> int { return static_cast<unsigned char>(c); });
131  m.def("ord_char_lv", [](char &c) -> int { return static_cast<unsigned char>(c); });
132  m.def("ord_char16", [](char16_t c) -> uint16_t { return c; });
133  m.def("ord_char16_lv", [](char16_t &c) -> uint16_t { return c; });
134  m.def("ord_char32", [](char32_t c) -> uint32_t { return c; });
135  m.def("ord_wchar", [](wchar_t c) -> int { return c; });
136 
137  // test_bytes_to_string
138  m.def("strlen", [](char *s) { return strlen(s); });
139  m.def("string_length", [](const std::string &s) { return s.length(); });
140 
141 #ifdef PYBIND11_HAS_U8STRING
142  m.attr("has_u8string") = true;
143  m.def("good_utf8_u8string", []() {
144  return std::u8string(u8"Say utf8\u203d \U0001f382 \U0001d400");
145  }); // Say utf8β€½ πŸŽ‚ 𝐀
146  m.def("bad_utf8_u8string", []() {
147  return std::u8string((const char8_t *) "abc\xd0"
148  "def");
149  });
150 
151  m.def("u8_char8_Z", []() -> char8_t { return u8'Z'; });
152 
153  // test_single_char_arguments
154  m.def("ord_char8", [](char8_t c) -> int { return static_cast<unsigned char>(c); });
155  m.def("ord_char8_lv", [](char8_t &c) -> int { return static_cast<unsigned char>(c); });
156 #endif
157 
158  // test_string_view
159 #ifdef PYBIND11_HAS_STRING_VIEW
160  m.attr("has_string_view") = true;
161  m.def("string_view_print", [](std::string_view s) { py::print(s, s.size()); });
162  m.def("string_view16_print", [](std::u16string_view s) { py::print(s, s.size()); });
163  m.def("string_view32_print", [](std::u32string_view s) { py::print(s, s.size()); });
164  m.def("string_view_chars", [](std::string_view s) {
165  py::list l;
166  for (auto c : s) {
167  l.append((std::uint8_t) c);
168  }
169  return l;
170  });
171  m.def("string_view16_chars", [](std::u16string_view s) {
172  py::list l;
173  for (auto c : s) {
174  l.append((int) c);
175  }
176  return l;
177  });
178  m.def("string_view32_chars", [](std::u32string_view s) {
179  py::list l;
180  for (auto c : s) {
181  l.append((int) c);
182  }
183  return l;
184  });
185  m.def("string_view_return",
186  []() { return std::string_view((const char *) u8"utf8 secret \U0001f382"); });
187  m.def("string_view16_return",
188  []() { return std::u16string_view(u"utf16 secret \U0001f382"); });
189  m.def("string_view32_return",
190  []() { return std::u32string_view(U"utf32 secret \U0001f382"); });
191 
192  // The inner lambdas here are to also test implicit conversion
193  using namespace std::literals;
194  m.def("string_view_bytes",
195  []() { return [](py::bytes b) { return b; }("abc \x80\x80 def"sv); });
196  m.def("string_view_str",
197  []() { return [](py::str s) { return s; }("abc \342\200\275 def"sv); });
198  m.def("string_view_from_bytes",
199  [](const py::bytes &b) { return [](std::string_view s) { return s; }(b); });
200  m.def("string_view_memoryview", []() {
201  static constexpr auto val = "Have some \360\237\216\202"sv;
202  return py::memoryview::from_memory(val);
203  });
204 
205 # ifdef PYBIND11_HAS_U8STRING
206  m.def("string_view8_print", [](std::u8string_view s) { py::print(s, s.size()); });
207  m.def("string_view8_chars", [](std::u8string_view s) {
208  py::list l;
209  for (auto c : s)
210  l.append((std::uint8_t) c);
211  return l;
212  });
213  m.def("string_view8_return", []() { return std::u8string_view(u8"utf8 secret \U0001f382"); });
214  m.def("string_view8_str", []() { return py::str{std::u8string_view{u8"abc β€½ def"}}; });
215 # endif
216 
217  struct TypeWithBothOperatorStringAndStringView {
218  // NOLINTNEXTLINE(google-explicit-constructor)
219  operator std::string() const { return "success"; }
220  // NOLINTNEXTLINE(google-explicit-constructor)
221  operator std::string_view() const { return "failure"; }
222  };
223  m.def("bytes_from_type_with_both_operator_string_and_string_view",
224  []() { return py::bytes(TypeWithBothOperatorStringAndStringView()); });
225  m.def("str_from_type_with_both_operator_string_and_string_view",
226  []() { return py::str(TypeWithBothOperatorStringAndStringView()); });
227 #endif
228 
229  // test_integer_casting
230  m.def("i32_str", [](std::int32_t v) { return std::to_string(v); });
231  m.def("u32_str", [](std::uint32_t v) { return std::to_string(v); });
232  m.def("i64_str", [](std::int64_t v) { return std::to_string(v); });
233  m.def("u64_str", [](std::uint64_t v) { return std::to_string(v); });
234 
235  // test_int_convert
236  m.def("int_passthrough", [](int arg) { return arg; });
237  m.def("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  m.def(
270  "int_string_pair",
271  []() {
272  // Using no-destructor idiom to side-step warnings from overzealous compilers.
273  static auto *int_string_pair = new std::pair<int, std::string>{2, "items"};
274  return int_string_pair;
275  },
276  py::return_value_policy::reference);
277 
278  // test_builtins_cast_return_none
279  m.def("return_none_string", []() -> std::string * { return nullptr; });
280  m.def("return_none_char", []() -> const char * { return nullptr; });
281  m.def("return_none_bool", []() -> bool * { return nullptr; });
282  m.def("return_none_int", []() -> int * { return nullptr; });
283  m.def("return_none_float", []() -> float * { return nullptr; });
284  m.def("return_none_pair", []() -> std::pair<int, int> * { return nullptr; });
285 
286  // test_none_deferred
287  m.def("defer_none_cstring", [](char *) { return false; });
288  m.def("defer_none_cstring", [](const py::none &) { return true; });
289  m.def("defer_none_custom", [](UserType *) { return false; });
290  m.def("defer_none_custom", [](const py::none &) { return true; });
291  m.def("nodefer_none_void", [](void *) { return true; });
292  m.def("nodefer_none_void", [](const py::none &) { return false; });
293 
294  // test_void_caster
295  m.def("load_nullptr_t", [](std::nullptr_t) {}); // not useful, but it should still compile
296  m.def("cast_nullptr_t", []() { return std::nullptr_t{}; });
297 
298  // [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works.
299 
300  // test_bool_caster
301  m.def("bool_passthrough", [](bool arg) { return arg; });
302  m.def("bool_passthrough_noconvert", [](bool arg) { return arg; }, py::arg{}.noconvert());
303 
304  // TODO: This should be disabled and fixed in future Intel compilers
305 #if !defined(__INTEL_COMPILER)
306  // Test "bool_passthrough_noconvert" again, but using () instead of {} to construct py::arg
307  // When compiled with the Intel compiler, this results in segmentation faults when importing
308  // the module. Tested with icc (ICC) 2021.1 Beta 20200827, this should be tested again when
309  // a newer version of icc is available.
310  m.def("bool_passthrough_noconvert2", [](bool arg) { return arg; }, py::arg().noconvert());
311 #endif
312 
313  // test_reference_wrapper
314  m.def("refwrap_builtin", [](std::reference_wrapper<int> p) { return 10 * p.get(); });
315  m.def("refwrap_usertype", [](std::reference_wrapper<UserType> p) { return p.get().value(); });
316  m.def("refwrap_usertype_const",
317  [](std::reference_wrapper<const UserType> p) { return p.get().value(); });
318 
319  m.def("refwrap_lvalue", []() -> std::reference_wrapper<UserType> {
320  static UserType x(1);
321  return std::ref(x);
322  });
323  m.def("refwrap_lvalue_const", []() -> std::reference_wrapper<const UserType> {
324  static UserType x(1);
325  return std::cref(x);
326  });
327 
328  // Not currently supported (std::pair caster has return-by-value cast operator);
329  // triggers static_assert failure.
330  // m.def("refwrap_pair", [](std::reference_wrapper<std::pair<int, int>>) { });
331 
332  m.def(
333  "refwrap_list",
334  [](bool copy) {
335  static IncType x1(1), x2(2);
336  py::list l;
337  for (const auto &f : {std::ref(x1), std::ref(x2)}) {
338  l.append(py::cast(
339  f, copy ? py::return_value_policy::copy : py::return_value_policy::reference));
340  }
341  return l;
342  },
343  "copy"_a);
344 
345  m.def("refwrap_iiw", [](const IncType &w) { return w.value(); });
346  m.def("refwrap_call_iiw", [](IncType &w, const py::function &f) {
347  py::list l;
348  l.append(f(std::ref(w)));
349  l.append(f(std::cref(w)));
350  IncType x(w.value());
351  l.append(f(std::ref(x)));
352  IncType y(w.value());
353  auto r3 = std::ref(y);
354  l.append(f(r3));
355  return l;
356  });
357 
358  // test_complex
359  m.def("complex_cast", [](float x) { return "{}"_s.format(x); });
360  m.def("complex_cast",
361  [](std::complex<float> x) { return "({}, {})"_s.format(x.real(), x.imag()); });
362 
363  // test int vs. long (Python 2)
364  m.def("int_cast", []() { return (int) 42; });
365  m.def("long_cast", []() { return (long) 42; });
366  m.def("longlong_cast", []() { return ULLONG_MAX; });
367 
369  m.def("test_void_caster", []() -> bool {
370  void *v = (void *) 0xabcd;
371  py::object o = py::cast(v);
372  return py::cast<void *>(o) == v;
373  });
374 
375  // Tests const/non-const propagation in cast_op.
376  m.def("takes", [](ConstRefCasted x) { return x.tag; });
377  m.def("takes_move", [](ConstRefCasted &&x) { return x.tag; });
378  m.def("takes_ptr", [](ConstRefCasted *x) { return x->tag; });
379  m.def("takes_ref", [](ConstRefCasted &x) { return x.tag; });
380  m.def("takes_ref_wrap", [](std::reference_wrapper<ConstRefCasted> x) { return x.get().tag; });
381  m.def("takes_const_ptr", [](const ConstRefCasted *x) { return x->tag; });
382  m.def("takes_const_ref", [](const ConstRefCasted &x) { return x.tag; });
383  m.def("takes_const_ref_wrap",
384  [](std::reference_wrapper<const ConstRefCasted> x) { return x.get().tag; });
385 
387 }
w
RowVector3d w
Definition: Matrix_resize_int.cpp:3
Eigen::internal::print
EIGEN_STRONG_INLINE Packet4f print(const Packet4f &a)
Definition: NEON/PacketMath.h:3115
name
Annotation for function names.
Definition: attr.h:51
s
RealScalar s
Definition: level1_cplx_impl.h:126
ConstRefCasted::tag
int tag
Definition: test_builtin_casters.cpp:15
uint32_t
unsigned int uint32_t
Definition: ms_stdint.h:85
c
Scalar Scalar * c
Definition: benchVecAdd.cpp:17
b
Scalar * b
Definition: benchVecAdd.cpp:17
type_caster_generic::value
void * value
Definition: type_caster_base.h:828
x
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
Definition: gnuplot_common_settings.hh:12
PYBIND11_WARNING_POP
PYBIND11_WARNING_PUSH PYBIND11_WARNING_POP
Definition: tensor.h:30
PYBIND11_NAMESPACE_END
#define PYBIND11_NAMESPACE_END(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:80
copy
int EIGEN_BLAS_FUNC() copy(int *n, RealScalar *px, int *incx, RealScalar *py, int *incy)
Definition: level1_impl.h:29
detail
Definition: testSerializationNonlinear.cpp:70
PYBIND11_NAMESPACE_BEGIN
#define PYBIND11_NAMESPACE_BEGIN(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:76
uint8_t
unsigned char uint8_t
Definition: ms_stdint.h:83
conditional_t
typename std::conditional< B, T, F >::type conditional_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:656
complex.h
handle
Definition: pytypes.h:226
type_caster
Definition: cast.h:38
make_tuple
tuple make_tuple()
Definition: cast.h:1383
int64_t
signed __int64 int64_t
Definition: ms_stdint.h:94
x1
Pose3 x1
Definition: testPose3.cpp:663
type_caster< ConstRefCasted >::load
bool load(handle, bool)
Definition: test_builtin_casters.cpp:27
l
static const Line3 l(Rot3(), 1, 1)
arg
Definition: cast.h:1412
r3
static const double r3
Definition: testSmartRangeFactor.cpp:32
RValueCaster
Definition: pybind11_tests.h:70
m
Matrix3f m
Definition: AngleAxis_mimic_euler.cpp:1
arg
EIGEN_DEVICE_FUNC const EIGEN_STRONG_INLINE ArgReturnType arg() const
Definition: ArrayCwiseUnaryOps.h:66
cast_op_type
conditional_t< std::is_pointer< remove_reference_t< T > >::value, typename std::add_pointer< intrinsic_t< T > >::type, typename std::add_lvalue_reference< intrinsic_t< T > >::type > cast_op_type
Definition: type_caster_base.h:841
y
Scalar * y
Definition: level1_cplx_impl.h:124
tree::f
Point2(* f)(const Point3 &, OptionalJacobian< 2, 3 >)
Definition: testExpression.cpp:218
PYBIND11_WARNING_DISABLE_MSVC
PYBIND11_WARNING_PUSH PYBIND11_WARNING_DISABLE_MSVC(5054) PYBIND11_WARNING_POP static_assert(EIGEN_VERSION_AT_LEAST(3
pybind11_tests.h
p
float * p
Definition: Tutorial_Map_using.cpp:9
uint16_t
unsigned short uint16_t
Definition: ms_stdint.h:84
v
Array< int, Dynamic, 1 > v
Definition: Array_initializer_list_vector_cxx11.cpp:1
U
@ U
Definition: testDecisionTree.cpp:296
pybind11
Definition: wrap/pybind11/pybind11/__init__.py:1
int32_t
signed int int32_t
Definition: ms_stdint.h:82
uint64_t
unsigned __int64 uint64_t
Definition: ms_stdint.h:95
gtsam.examples.ShonanAveragingCLI.str
str
Definition: ShonanAveragingCLI.py:115
test_callbacks.value
value
Definition: test_callbacks.py:160
x2
Pose3 x2(Rot3::Ypr(0.0, 0.0, 0.0), l2)
TEST_SUBMODULE
TEST_SUBMODULE(builtin_casters, m)
Definition: test_builtin_casters.cpp:75
Eigen::internal::cast
EIGEN_DEVICE_FUNC NewType cast(const OldType &x)
Definition: Eigen/src/Core/MathFunctions.h:460
test_eigen.ref
ref
Definition: test_eigen.py:9
ConstRefCasted
Definition: test_builtin_casters.cpp:14


gtsam
Author(s):
autogenerated on Thu Jul 4 2024 03:06:00