module.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #pragma once
  2. #include "cpp_function.h"
  3. namespace pybind11 {
  4. class module_ : public object {
  5. public:
  6. using object::object;
  7. static module_ __main__() { return vm->_main; }
  8. static module_ import(const char* name) {
  9. if(name == std::string_view{"__main__"}) {
  10. return vm->_main;
  11. } else {
  12. return vm->py_import(name, false);
  13. }
  14. }
  15. module_ def_submodule(const char* name, const char* doc = nullptr) {
  16. auto package = this->package()._as<pkpy::Str>() + "." + this->name()._as<pkpy::Str>();
  17. auto m = vm->new_module(name, package);
  18. setattr(*this, name, m);
  19. return m;
  20. }
  21. template <typename Fn, typename... Extras>
  22. module_& def(const char* name, Fn&& fn, const Extras... extras) {
  23. impl::bind_function(*this, name, std::forward<Fn>(fn), pkpy::BindType::DEFAULT, extras...);
  24. return *this;
  25. }
  26. };
  27. #define PYBIND11_EMBEDDED_MODULE(name, variable) \
  28. static void _pybind11_register_##name(pybind11::module_& variable); \
  29. namespace pybind11::impl { \
  30. auto _module_##name = [] { \
  31. interpreter::register_init([] { \
  32. pybind11::module_ m = vm->new_module(#name, ""); \
  33. _pybind11_register_##name(m); \
  34. }); \
  35. return 1; \
  36. }(); \
  37. } \
  38. static void _pybind11_register_##name(pybind11::module_& variable)
  39. } // namespace pybind11