module.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. // TODO: resolve package
  17. //auto package = this->package()._as<pkpy::Str>() + "." + this->name()._as<pkpy::Str>();
  18. auto fname = this->name()._as<pkpy::Str>() + "." + name;
  19. auto m = vm->new_module(fname, "");
  20. setattr(*this, name, m);
  21. return m;
  22. }
  23. template <typename Fn, typename... Extras>
  24. module_& def(const char* name, Fn&& fn, const Extras... extras) {
  25. impl::bind_function<false>(*this, name, std::forward<Fn>(fn), pkpy::BindType::DEFAULT, extras...);
  26. return *this;
  27. }
  28. };
  29. #define PYBIND11_EMBEDDED_MODULE(name, variable) \
  30. static void _pybind11_register_##name(pybind11::module_& variable); \
  31. namespace pybind11::impl { \
  32. auto _module_##name = [] { \
  33. interpreter::register_init([] { \
  34. pybind11::module_ m = vm->new_module(#name, ""); \
  35. _pybind11_register_##name(m); \
  36. }); \
  37. return 1; \
  38. }(); \
  39. } \
  40. static void _pybind11_register_##name(pybind11::module_& variable)
  41. } // namespace pybind11