local_bindings.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #pragma once
  2. #include "pybind11_tests.h"
  3. /// Simple class used to test py::local:
  4. template <int> class LocalBase {
  5. public:
  6. LocalBase(int i) : i(i) { }
  7. int i = -1;
  8. };
  9. /// Registered with py::module_local in both main and secondary modules:
  10. using LocalType = LocalBase<0>;
  11. /// Registered without py::module_local in both modules:
  12. using NonLocalType = LocalBase<1>;
  13. /// A second non-local type (for stl_bind tests):
  14. using NonLocal2 = LocalBase<2>;
  15. /// Tests within-module, different-compilation-unit local definition conflict:
  16. using LocalExternal = LocalBase<3>;
  17. /// Mixed: registered local first, then global
  18. using MixedLocalGlobal = LocalBase<4>;
  19. /// Mixed: global first, then local
  20. using MixedGlobalLocal = LocalBase<5>;
  21. /// Registered with py::module_local only in the secondary module:
  22. using ExternalType1 = LocalBase<6>;
  23. using ExternalType2 = LocalBase<7>;
  24. using LocalVec = std::vector<LocalType>;
  25. using LocalVec2 = std::vector<NonLocal2>;
  26. using LocalMap = std::unordered_map<std::string, LocalType>;
  27. using NonLocalVec = std::vector<NonLocalType>;
  28. using NonLocalVec2 = std::vector<NonLocal2>;
  29. using NonLocalMap = std::unordered_map<std::string, NonLocalType>;
  30. using NonLocalMap2 = std::unordered_map<std::string, uint8_t>;
  31. PYBIND11_MAKE_OPAQUE(LocalVec);
  32. PYBIND11_MAKE_OPAQUE(LocalVec2);
  33. PYBIND11_MAKE_OPAQUE(LocalMap);
  34. PYBIND11_MAKE_OPAQUE(NonLocalVec);
  35. //PYBIND11_MAKE_OPAQUE(NonLocalVec2); // same type as LocalVec2
  36. PYBIND11_MAKE_OPAQUE(NonLocalMap);
  37. PYBIND11_MAKE_OPAQUE(NonLocalMap2);
  38. // Simple bindings (used with the above):
  39. template <typename T, int Adjust = 0, typename... Args>
  40. py::class_<T> bind_local(Args && ...args) {
  41. return py::class_<T>(std::forward<Args>(args)...)
  42. .def(py::init<int>())
  43. .def("get", [](T &i) { return i.i + Adjust; });
  44. };
  45. // Simulate a foreign library base class (to match the example in the docs):
  46. namespace pets {
  47. class Pet {
  48. public:
  49. Pet(std::string name) : name_(name) {}
  50. std::string name_;
  51. const std::string &name() { return name_; }
  52. };
  53. }
  54. struct MixGL { int i; MixGL(int i) : i{i} {} };
  55. struct MixGL2 { int i; MixGL2(int i) : i{i} {} };