test_builtin_casters.cpp 13 KB

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