module.h 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. module_ def_submodule(const char* name, const char* doc = nullptr) {
  16. // auto package = (attr("__package__").cast<std::string>() += ".") +=
  17. // attr("__name__").cast<std::string_view>();
  18. auto fname = (attr("__name__").cast<std::string>() += ".") += name;
  19. auto m = py_newmodule(fname.c_str());
  20. setattr(*this, name, m);
  21. return module_(m, object::ref_t{});
  22. }
  23. template <typename Fn, typename... Extras>
  24. module_& def(const char* name, Fn&& fn, const Extras... extras) {
  25. impl::bind_function<false, false>(*this, name, std::forward<Fn>(fn), extras...);
  26. return *this;
  27. }
  28. };
  29. using module = module_;
  30. #define PYBIND11_EMBEDDED_MODULE(name, variable) \
  31. static void _pkbind_register_##name(::pkbind::module_& variable); \
  32. namespace pkbind::impl { \
  33. auto _module_##name = [] { \
  34. ::pkbind::action::register_start([] { \
  35. auto m = ::pkbind::module_::create(#name); \
  36. _pkbind_register_##name(m); \
  37. }); \
  38. return 1; \
  39. }(); \
  40. } \
  41. static void _pkbind_register_##name(::pkbind::module_& variable)
  42. #define PYBIND11_MODULE(name, variable) \
  43. static void _pkbind_register_##name(::pkbind::module_& variable); \
  44. extern "C" PK_EXPORT bool py_module_initialize() { \
  45. auto m = ::pkbind::module_::create(#name); \
  46. _pkbind_register_##name(m); \
  47. py_assign(py_retval(), m.ptr()); \
  48. return true; \
  49. } \
  50. static void _pkbind_register_##name(::pkbind::module_& variable)
  51. } // namespace pkbind