Advertisement
dan-masek

Solution to https://stackoverflow.com/q/78378063/3962537

Apr 25th, 2024
568
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.76 KB | None | 0 0
  1. #include <pybind11/pybind11.h>
  2. #include <pybind11/embed.h>
  3. #include <iostream>
  4.  
  5. namespace py = pybind11;
  6.  
  7. PYBIND11_EMBEDDED_MODULE(testmodule, m)
  8. {
  9.     m.def("start", [](py::module& mod) {
  10.         using namespace pybind11::literals;
  11.         auto import_fn = py::globals()["__builtins__"].attr("__import__");
  12.        
  13.         auto bar = import_fn(mod.attr("__name__")
  14.             , "fromlist"_a=py::make_tuple("bar")
  15.             ).attr("bar");
  16.        
  17.         py::print(bar.attr("test"));
  18.     });
  19. }
  20.  
  21. int main()
  22. {
  23.     py::scoped_interpreter guard{};
  24.  
  25.     try {
  26.         py::exec(R"(\
  27. import testmodule
  28. import foo
  29.  
  30. testmodule.start(foo)
  31. )");
  32.     } catch (py::error_already_set& e) {
  33.         std::cerr << e.what() << '\n';
  34.     }
  35.  
  36.     return 0;
  37. }
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement