1
0

module.h 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #pragma once
  2. #include "function.h"
  3. namespace pkbind {
  4. class module_ : public object {
  5. PKBIND_TYPE_IMPL(object, module_, tp_module)
  6. static module_ __main__() { return module_(py_getmodule("__main__"), object::ref_t{}); }
  7. static module_ import(const char* name) {
  8. raise_call<py_import>(name);
  9. return borrow<module_>(py_retval());
  10. }
  11. static module_ create(const char* name) {
  12. auto m = py_newmodule(name);
  13. return steal<module_>(m);
  14. }
  15. void reload() {
  16. bool ok = py_importlib_reload(ptr());
  17. if(!ok) { throw error_already_set(); }
  18. }
  19. module_ def_submodule(const char* name, const char* doc = nullptr) {
  20. // auto package = (attr("__package__").cast<std::string>() += ".") +=
  21. // attr("__name__").cast<std::string_view>();
  22. auto fname = (attr("__name__").cast<std::string>() += ".") += name;
  23. auto m = py_newmodule(fname.c_str());
  24. setattr(*this, name, m);
  25. return module_(m, object::ref_t{});
  26. }
  27. template <typename Fn, typename... Extras>
  28. module_& def(const char* name, Fn&& fn, const Extras... extras) {
  29. impl::bind_function<false, false>(*this, name, std::forward<Fn>(fn), extras...);
  30. return *this;
  31. }
  32. };
  33. using module = module_;
  34. #define PYBIND11_EMBEDDED_MODULE(name, variable) \
  35. static void _pkbind_register_##name(::pkbind::module_& variable); \
  36. namespace pkbind::impl { \
  37. auto _module_##name = [] { \
  38. ::pkbind::action::register_start([] { \
  39. auto m = ::pkbind::module_::create(#name); \
  40. _pkbind_register_##name(m); \
  41. }); \
  42. return 1; \
  43. }(); \
  44. } \
  45. static void _pkbind_register_##name(::pkbind::module_& variable)
  46. #define PYBIND11_MODULE(name, variable) \
  47. static void _pkbind_register_##name(::pkbind::module_& variable); \
  48. extern "C" PK_EXPORT bool py_module_initialize() { \
  49. auto m = ::pkbind::module_::create(#name); \
  50. _pkbind_register_##name(m); \
  51. py_assign(py_retval(), m.ptr()); \
  52. return true; \
  53. } \
  54. static void _pkbind_register_##name(::pkbind::module_& variable)
  55. } // namespace pkbind