PageRenderTime 56ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/ext/pybind11/tests/test_class.cpp

https://bitbucket.org/lawa1215/gem5-cache_locking
C++ | 357 lines | 252 code | 51 blank | 54 comment | 8 complexity | df7a70c98c1edb2394232655290ae345 MD5 | raw file
Possible License(s): BSD-2-Clause, Apache-2.0, BSD-3-Clause
  1. /*
  2. tests/test_class.cpp -- test py::class_ definitions and basic functionality
  3. Copyright (c) 2016 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 "constructor_stats.h"
  9. #include "local_bindings.h"
  10. TEST_SUBMODULE(class_, m) {
  11. // test_instance
  12. struct NoConstructor {
  13. static NoConstructor *new_instance() {
  14. auto *ptr = new NoConstructor();
  15. print_created(ptr, "via new_instance");
  16. return ptr;
  17. }
  18. ~NoConstructor() { print_destroyed(this); }
  19. };
  20. py::class_<NoConstructor>(m, "NoConstructor")
  21. .def_static("new_instance", &NoConstructor::new_instance, "Return an instance");
  22. // test_inheritance
  23. class Pet {
  24. public:
  25. Pet(const std::string &name, const std::string &species)
  26. : m_name(name), m_species(species) {}
  27. std::string name() const { return m_name; }
  28. std::string species() const { return m_species; }
  29. private:
  30. std::string m_name;
  31. std::string m_species;
  32. };
  33. class Dog : public Pet {
  34. public:
  35. Dog(const std::string &name) : Pet(name, "dog") {}
  36. std::string bark() const { return "Woof!"; }
  37. };
  38. class Rabbit : public Pet {
  39. public:
  40. Rabbit(const std::string &name) : Pet(name, "parrot") {}
  41. };
  42. class Hamster : public Pet {
  43. public:
  44. Hamster(const std::string &name) : Pet(name, "rodent") {}
  45. };
  46. class Chimera : public Pet {
  47. Chimera() : Pet("Kimmy", "chimera") {}
  48. };
  49. py::class_<Pet> pet_class(m, "Pet");
  50. pet_class
  51. .def(py::init<std::string, std::string>())
  52. .def("name", &Pet::name)
  53. .def("species", &Pet::species);
  54. /* One way of declaring a subclass relationship: reference parent's class_ object */
  55. py::class_<Dog>(m, "Dog", pet_class)
  56. .def(py::init<std::string>());
  57. /* Another way of declaring a subclass relationship: reference parent's C++ type */
  58. py::class_<Rabbit, Pet>(m, "Rabbit")
  59. .def(py::init<std::string>());
  60. /* And another: list parent in class template arguments */
  61. py::class_<Hamster, Pet>(m, "Hamster")
  62. .def(py::init<std::string>());
  63. /* Constructors are not inherited by default */
  64. py::class_<Chimera, Pet>(m, "Chimera");
  65. m.def("pet_name_species", [](const Pet &pet) { return pet.name() + " is a " + pet.species(); });
  66. m.def("dog_bark", [](const Dog &dog) { return dog.bark(); });
  67. // test_automatic_upcasting
  68. struct BaseClass { virtual ~BaseClass() {} };
  69. struct DerivedClass1 : BaseClass { };
  70. struct DerivedClass2 : BaseClass { };
  71. py::class_<BaseClass>(m, "BaseClass").def(py::init<>());
  72. py::class_<DerivedClass1>(m, "DerivedClass1").def(py::init<>());
  73. py::class_<DerivedClass2>(m, "DerivedClass2").def(py::init<>());
  74. m.def("return_class_1", []() -> BaseClass* { return new DerivedClass1(); });
  75. m.def("return_class_2", []() -> BaseClass* { return new DerivedClass2(); });
  76. m.def("return_class_n", [](int n) -> BaseClass* {
  77. if (n == 1) return new DerivedClass1();
  78. if (n == 2) return new DerivedClass2();
  79. return new BaseClass();
  80. });
  81. m.def("return_none", []() -> BaseClass* { return nullptr; });
  82. // test_isinstance
  83. m.def("check_instances", [](py::list l) {
  84. return py::make_tuple(
  85. py::isinstance<py::tuple>(l[0]),
  86. py::isinstance<py::dict>(l[1]),
  87. py::isinstance<Pet>(l[2]),
  88. py::isinstance<Pet>(l[3]),
  89. py::isinstance<Dog>(l[4]),
  90. py::isinstance<Rabbit>(l[5]),
  91. py::isinstance<UnregisteredType>(l[6])
  92. );
  93. });
  94. // test_mismatched_holder
  95. struct MismatchBase1 { };
  96. struct MismatchDerived1 : MismatchBase1 { };
  97. struct MismatchBase2 { };
  98. struct MismatchDerived2 : MismatchBase2 { };
  99. m.def("mismatched_holder_1", []() {
  100. auto mod = py::module::import("__main__");
  101. py::class_<MismatchBase1, std::shared_ptr<MismatchBase1>>(mod, "MismatchBase1");
  102. py::class_<MismatchDerived1, MismatchBase1>(mod, "MismatchDerived1");
  103. });
  104. m.def("mismatched_holder_2", []() {
  105. auto mod = py::module::import("__main__");
  106. py::class_<MismatchBase2>(mod, "MismatchBase2");
  107. py::class_<MismatchDerived2, std::shared_ptr<MismatchDerived2>,
  108. MismatchBase2>(mod, "MismatchDerived2");
  109. });
  110. // test_override_static
  111. // #511: problem with inheritance + overwritten def_static
  112. struct MyBase {
  113. static std::unique_ptr<MyBase> make() {
  114. return std::unique_ptr<MyBase>(new MyBase());
  115. }
  116. };
  117. struct MyDerived : MyBase {
  118. static std::unique_ptr<MyDerived> make() {
  119. return std::unique_ptr<MyDerived>(new MyDerived());
  120. }
  121. };
  122. py::class_<MyBase>(m, "MyBase")
  123. .def_static("make", &MyBase::make);
  124. py::class_<MyDerived, MyBase>(m, "MyDerived")
  125. .def_static("make", &MyDerived::make)
  126. .def_static("make2", &MyDerived::make);
  127. // test_implicit_conversion_life_support
  128. struct ConvertibleFromUserType {
  129. int i;
  130. ConvertibleFromUserType(UserType u) : i(u.value()) { }
  131. };
  132. py::class_<ConvertibleFromUserType>(m, "AcceptsUserType")
  133. .def(py::init<UserType>());
  134. py::implicitly_convertible<UserType, ConvertibleFromUserType>();
  135. m.def("implicitly_convert_argument", [](const ConvertibleFromUserType &r) { return r.i; });
  136. m.def("implicitly_convert_variable", [](py::object o) {
  137. // `o` is `UserType` and `r` is a reference to a temporary created by implicit
  138. // conversion. This is valid when called inside a bound function because the temp
  139. // object is attached to the same life support system as the arguments.
  140. const auto &r = o.cast<const ConvertibleFromUserType &>();
  141. return r.i;
  142. });
  143. m.add_object("implicitly_convert_variable_fail", [&] {
  144. auto f = [](PyObject *, PyObject *args) -> PyObject * {
  145. auto o = py::reinterpret_borrow<py::tuple>(args)[0];
  146. try { // It should fail here because there is no life support.
  147. o.cast<const ConvertibleFromUserType &>();
  148. } catch (const py::cast_error &e) {
  149. return py::str(e.what()).release().ptr();
  150. }
  151. return py::str().release().ptr();
  152. };
  153. auto def = new PyMethodDef{"f", f, METH_VARARGS, nullptr};
  154. return py::reinterpret_steal<py::object>(PyCFunction_NewEx(def, nullptr, m.ptr()));
  155. }());
  156. // test_operator_new_delete
  157. struct HasOpNewDel {
  158. std::uint64_t i;
  159. static void *operator new(size_t s) { py::print("A new", s); return ::operator new(s); }
  160. static void *operator new(size_t s, void *ptr) { py::print("A placement-new", s); return ptr; }
  161. static void operator delete(void *p) { py::print("A delete"); return ::operator delete(p); }
  162. };
  163. struct HasOpNewDelSize {
  164. std::uint32_t i;
  165. static void *operator new(size_t s) { py::print("B new", s); return ::operator new(s); }
  166. static void *operator new(size_t s, void *ptr) { py::print("B placement-new", s); return ptr; }
  167. static void operator delete(void *p, size_t s) { py::print("B delete", s); return ::operator delete(p); }
  168. };
  169. struct AliasedHasOpNewDelSize {
  170. std::uint64_t i;
  171. static void *operator new(size_t s) { py::print("C new", s); return ::operator new(s); }
  172. static void *operator new(size_t s, void *ptr) { py::print("C placement-new", s); return ptr; }
  173. static void operator delete(void *p, size_t s) { py::print("C delete", s); return ::operator delete(p); }
  174. virtual ~AliasedHasOpNewDelSize() = default;
  175. };
  176. struct PyAliasedHasOpNewDelSize : AliasedHasOpNewDelSize {
  177. PyAliasedHasOpNewDelSize() = default;
  178. PyAliasedHasOpNewDelSize(int) { }
  179. std::uint64_t j;
  180. };
  181. struct HasOpNewDelBoth {
  182. std::uint32_t i[8];
  183. static void *operator new(size_t s) { py::print("D new", s); return ::operator new(s); }
  184. static void *operator new(size_t s, void *ptr) { py::print("D placement-new", s); return ptr; }
  185. static void operator delete(void *p) { py::print("D delete"); return ::operator delete(p); }
  186. static void operator delete(void *p, size_t s) { py::print("D wrong delete", s); return ::operator delete(p); }
  187. };
  188. py::class_<HasOpNewDel>(m, "HasOpNewDel").def(py::init<>());
  189. py::class_<HasOpNewDelSize>(m, "HasOpNewDelSize").def(py::init<>());
  190. py::class_<HasOpNewDelBoth>(m, "HasOpNewDelBoth").def(py::init<>());
  191. py::class_<AliasedHasOpNewDelSize, PyAliasedHasOpNewDelSize> aliased(m, "AliasedHasOpNewDelSize");
  192. aliased.def(py::init<>());
  193. aliased.attr("size_noalias") = py::int_(sizeof(AliasedHasOpNewDelSize));
  194. aliased.attr("size_alias") = py::int_(sizeof(PyAliasedHasOpNewDelSize));
  195. // This test is actually part of test_local_bindings (test_duplicate_local), but we need a
  196. // definition in a different compilation unit within the same module:
  197. bind_local<LocalExternal, 17>(m, "LocalExternal", py::module_local());
  198. // test_bind_protected_functions
  199. class ProtectedA {
  200. protected:
  201. int foo() const { return value; }
  202. private:
  203. int value = 42;
  204. };
  205. class PublicistA : public ProtectedA {
  206. public:
  207. using ProtectedA::foo;
  208. };
  209. py::class_<ProtectedA>(m, "ProtectedA")
  210. .def(py::init<>())
  211. #if !defined(_MSC_VER) || _MSC_VER >= 1910
  212. .def("foo", &PublicistA::foo);
  213. #else
  214. .def("foo", static_cast<int (ProtectedA::*)() const>(&PublicistA::foo));
  215. #endif
  216. class ProtectedB {
  217. public:
  218. virtual ~ProtectedB() = default;
  219. protected:
  220. virtual int foo() const { return value; }
  221. private:
  222. int value = 42;
  223. };
  224. class TrampolineB : public ProtectedB {
  225. public:
  226. int foo() const override { PYBIND11_OVERLOAD(int, ProtectedB, foo, ); }
  227. };
  228. class PublicistB : public ProtectedB {
  229. public:
  230. using ProtectedB::foo;
  231. };
  232. py::class_<ProtectedB, TrampolineB>(m, "ProtectedB")
  233. .def(py::init<>())
  234. #if !defined(_MSC_VER) || _MSC_VER >= 1910
  235. .def("foo", &PublicistB::foo);
  236. #else
  237. .def("foo", static_cast<int (ProtectedB::*)() const>(&PublicistB::foo));
  238. #endif
  239. // test_brace_initialization
  240. struct BraceInitialization {
  241. int field1;
  242. std::string field2;
  243. };
  244. py::class_<BraceInitialization>(m, "BraceInitialization")
  245. .def(py::init<int, const std::string &>())
  246. .def_readwrite("field1", &BraceInitialization::field1)
  247. .def_readwrite("field2", &BraceInitialization::field2);
  248. // test_reentrant_implicit_conversion_failure
  249. // #1035: issue with runaway reentrant implicit conversion
  250. struct BogusImplicitConversion {
  251. BogusImplicitConversion(const BogusImplicitConversion &) { }
  252. };
  253. py::class_<BogusImplicitConversion>(m, "BogusImplicitConversion")
  254. .def(py::init<const BogusImplicitConversion &>());
  255. py::implicitly_convertible<int, BogusImplicitConversion>();
  256. }
  257. template <int N> class BreaksBase { public: virtual ~BreaksBase() = default; };
  258. template <int N> class BreaksTramp : public BreaksBase<N> {};
  259. // These should all compile just fine:
  260. typedef py::class_<BreaksBase<1>, std::unique_ptr<BreaksBase<1>>, BreaksTramp<1>> DoesntBreak1;
  261. typedef py::class_<BreaksBase<2>, BreaksTramp<2>, std::unique_ptr<BreaksBase<2>>> DoesntBreak2;
  262. typedef py::class_<BreaksBase<3>, std::unique_ptr<BreaksBase<3>>> DoesntBreak3;
  263. typedef py::class_<BreaksBase<4>, BreaksTramp<4>> DoesntBreak4;
  264. typedef py::class_<BreaksBase<5>> DoesntBreak5;
  265. typedef py::class_<BreaksBase<6>, std::shared_ptr<BreaksBase<6>>, BreaksTramp<6>> DoesntBreak6;
  266. typedef py::class_<BreaksBase<7>, BreaksTramp<7>, std::shared_ptr<BreaksBase<7>>> DoesntBreak7;
  267. typedef py::class_<BreaksBase<8>, std::shared_ptr<BreaksBase<8>>> DoesntBreak8;
  268. #define CHECK_BASE(N) static_assert(std::is_same<typename DoesntBreak##N::type, BreaksBase<N>>::value, \
  269. "DoesntBreak" #N " has wrong type!")
  270. CHECK_BASE(1); CHECK_BASE(2); CHECK_BASE(3); CHECK_BASE(4); CHECK_BASE(5); CHECK_BASE(6); CHECK_BASE(7); CHECK_BASE(8);
  271. #define CHECK_ALIAS(N) static_assert(DoesntBreak##N::has_alias && std::is_same<typename DoesntBreak##N::type_alias, BreaksTramp<N>>::value, \
  272. "DoesntBreak" #N " has wrong type_alias!")
  273. #define CHECK_NOALIAS(N) static_assert(!DoesntBreak##N::has_alias && std::is_void<typename DoesntBreak##N::type_alias>::value, \
  274. "DoesntBreak" #N " has type alias, but shouldn't!")
  275. CHECK_ALIAS(1); CHECK_ALIAS(2); CHECK_NOALIAS(3); CHECK_ALIAS(4); CHECK_NOALIAS(5); CHECK_ALIAS(6); CHECK_ALIAS(7); CHECK_NOALIAS(8);
  276. #define CHECK_HOLDER(N, TYPE) static_assert(std::is_same<typename DoesntBreak##N::holder_type, std::TYPE##_ptr<BreaksBase<N>>>::value, \
  277. "DoesntBreak" #N " has wrong holder_type!")
  278. CHECK_HOLDER(1, unique); CHECK_HOLDER(2, unique); CHECK_HOLDER(3, unique); CHECK_HOLDER(4, unique); CHECK_HOLDER(5, unique);
  279. CHECK_HOLDER(6, shared); CHECK_HOLDER(7, shared); CHECK_HOLDER(8, shared);
  280. // There's no nice way to test that these fail because they fail to compile; leave them here,
  281. // though, so that they can be manually tested by uncommenting them (and seeing that compilation
  282. // failures occurs).
  283. // We have to actually look into the type: the typedef alone isn't enough to instantiate the type:
  284. #define CHECK_BROKEN(N) static_assert(std::is_same<typename Breaks##N::type, BreaksBase<-N>>::value, \
  285. "Breaks1 has wrong type!");
  286. //// Two holder classes:
  287. //typedef py::class_<BreaksBase<-1>, std::unique_ptr<BreaksBase<-1>>, std::unique_ptr<BreaksBase<-1>>> Breaks1;
  288. //CHECK_BROKEN(1);
  289. //// Two aliases:
  290. //typedef py::class_<BreaksBase<-2>, BreaksTramp<-2>, BreaksTramp<-2>> Breaks2;
  291. //CHECK_BROKEN(2);
  292. //// Holder + 2 aliases
  293. //typedef py::class_<BreaksBase<-3>, std::unique_ptr<BreaksBase<-3>>, BreaksTramp<-3>, BreaksTramp<-3>> Breaks3;
  294. //CHECK_BROKEN(3);
  295. //// Alias + 2 holders
  296. //typedef py::class_<BreaksBase<-4>, std::unique_ptr<BreaksBase<-4>>, BreaksTramp<-4>, std::shared_ptr<BreaksBase<-4>>> Breaks4;
  297. //CHECK_BROKEN(4);
  298. //// Invalid option (not a subclass or holder)
  299. //typedef py::class_<BreaksBase<-5>, BreaksTramp<-4>> Breaks5;
  300. //CHECK_BROKEN(5);
  301. //// Invalid option: multiple inheritance not supported:
  302. //template <> struct BreaksBase<-8> : BreaksBase<-6>, BreaksBase<-7> {};
  303. //typedef py::class_<BreaksBase<-8>, BreaksBase<-6>, BreaksBase<-7>> Breaks8;
  304. //CHECK_BROKEN(8);