From dc546f56997bfd5ca4eb68a6bdfec189fcb38a3d Mon Sep 17 00:00:00 2001 From: ykiko Date: Sun, 22 Sep 2024 19:56:41 +0800 Subject: [PATCH] support dynamic library. --- include/pybind11/internal/module.h | 9 +++++++++ include/pybind11/tests/module.cpp | 27 +++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/include/pybind11/internal/module.h b/include/pybind11/internal/module.h index 2dd1dad4..69047341 100644 --- a/include/pybind11/internal/module.h +++ b/include/pybind11/internal/module.h @@ -50,4 +50,13 @@ using module_ = module; } \ static void _pkbind_register_##name(::pkbind::module& variable) +#define PYBIND11_MODULE(name, variable) \ + static void _pkbind_register_##name(::pkbind::module& variable); \ + extern "C" bool pybind_module_initialize() { \ + auto m = ::pkbind::module::create(#name); \ + _pkbind_register_##name(m); \ + return true; \ + } \ + static void _pkbind_register_##name(::pkbind::module& variable) + } // namespace pkbind diff --git a/include/pybind11/tests/module.cpp b/include/pybind11/tests/module.cpp index 30429828..b6af6720 100644 --- a/include/pybind11/tests/module.cpp +++ b/include/pybind11/tests/module.cpp @@ -12,6 +12,17 @@ PYBIND11_EMBEDDED_MODULE(example, m) { }); } +PYBIND11_MODULE(example3, m) { + m.def("add", [](int a, int b) { + return a + b; + }); + + auto math = m.def_submodule("math"); + math.def("sub", [](int a, int b) { + return a - b; + }); +} + namespace { TEST_F(PYBIND11_TEST, module) { @@ -52,4 +63,20 @@ TEST_F(PYBIND11_TEST, raw_module) { EXPECT_EQ(math2.attr("sub")(4, 3).cast(), 1); } +TEST_F(PYBIND11_TEST, module3) { + pybind_module_initialize(); + + py::exec("import example3"); + EXPECT_EVAL_EQ("example3.add(1, 2)", 3); + + py::exec("from example3 import math"); + EXPECT_EVAL_EQ("math.sub(1, 2)", -1); + + py::exec("from example3.math import sub"); + EXPECT_EVAL_EQ("sub(1, 2)", -1); + + auto math = py::module::import("example3.math"); + EXPECT_EQ(math.attr("sub")(4, 3).cast(), 1); +} + } // namespace