Advertisement
dan-masek

Untitled

Apr 5th, 2020
812
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.77 KB | None | 0 0
  1. void foo(void* data)
  2. {
  3.     py::object* obj(reinterpret_cast<py::object*>(data));
  4.     py::print(obj->attr("name"));
  5. }
  6.  
  7. void bar()
  8. {
  9.     py::object mod(py::module::import("os"));
  10.     void* data = reinterpret_cast<void*>(&mod);
  11.     foo(data);
  12. }
  13.  
  14. void bar2()
  15. {
  16.     // Note: Not using a smart pointer here means you will have to be extra careful
  17.     // to avoid memory leaks.
  18.     std::unique_ptr<py::object> mod(std::make_unique<py::object>());
  19.     *mod = py::module::import("os");
  20.     void* data = reinterpret_cast<void*>(mod->ptr());
  21.     foo(data);
  22. }
  23.  
  24.  
  25. int main()
  26. {
  27.     py::scoped_interpreter guard{};
  28.  
  29.     try {
  30.  
  31.         bar();
  32.         bar2();
  33.  
  34.  
  35.     } catch (py::error_already_set& e) {
  36.         std::cerr << e.what() << "\n";
  37.     }
  38.  
  39.     return 0;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement