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