-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
80 lines (62 loc) · 1.89 KB
/
main.cpp
File metadata and controls
80 lines (62 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <boost/python.hpp>
namespace bp = boost::python;
bp::object import(const std::string& module, const std::string& path)
{
bp::object globals = bp::import("__main__").attr("__dict__");
bp::dict locals;
locals["module_name"] = module;
locals["path"] = path;
bp::exec("import imp\n"
"new_module = imp.load_module(module_name, open(path), path, ('bp', 'U', imp.PY_SOURCE))\n",
globals,
locals);
return locals["new_module"];
}
///////////////////////////
class Runner
{
public:
void init(bp::object script)
{
// capture methods at creation time so we don't have to look them up every time we call them
_run = script.attr("run");
_result = script.attr("result");
}
void run()
{
_run(); // call the script's run method
}
void execute(int i)
{
result(i * 2);
}
private:
void result(int i)
{
_result(i); // call the script's result method
}
bp::object _run;
bp::object _result;
};
int main()
{
Py_Initialize();
// load our python script and extract the Script class
bp::object module = import("test", "test.py");
bp::object Script = module.attr("Script");
// wrap Runner and expose some functions to python
bp::object RunnerWrapper(
bp::class_<Runner>("Runner")
.def("execute", &Runner::execute)
);
// create a python wrapped instance of Runner, which we will pass to the script so it can call back through it
bp::object wrapper = RunnerWrapper();
bp::object script = Script(wrapper);
// extract the runner instance from the python wrapped instance
Runner& runner = bp::extract<Runner&>(wrapper);
// initialise with the script, so we can get handles to the script's methods we require
runner.init(script);
runner.run();
Py_Finalize();
return 0;
}