embed.cpp 654 B

12345678910111213141516171819202122
  1. #include <pybind11/embed.h>
  2. namespace py = pybind11;
  3. PYBIND11_EMBEDDED_MODULE(test_cmake_build, m) {
  4. m.def("add", [](int i, int j) { return i + j; });
  5. }
  6. int main(int argc, char *argv[]) {
  7. if (argc != 2)
  8. throw std::runtime_error("Expected test.py file as the first argument");
  9. auto test_py_file = argv[1];
  10. py::scoped_interpreter guard{};
  11. auto m = py::module::import("test_cmake_build");
  12. if (m.attr("add")(1, 2).cast<int>() != 3)
  13. throw std::runtime_error("embed.cpp failed");
  14. py::module::import("sys").attr("argv") = py::make_tuple("test.py", "embed.cpp");
  15. py::eval_file(test_py_file, py::globals());
  16. }