Exposing Functions to Embedded Python
17 Oct 2005So far, instead of exposing functions to Python, we have (the reverse I guess) embedded the Python interpreter in our process using Boost::Python. So, running Python from within our process is all good and well but we want the Python code to interact with our C++ code as well.
We’ll add to the previous example:
<code>const char* greet()
{
return "Hello World from C++";
}
BOOST_PYTHON_MODULE(embed_test)
{
def("greet", greet);
}</code>
Here we have defined a python module embed_test
which we will now expose to our embedded Python interpreter. The module has one function, “greet” in the Python module calls the C++ greet
function.
Now we add to the main
function:
<code>if(PyImport_AppendInittab("embed_test", initembed_test) == -1)
throw std::runtime_error("Failed to add test module to builtins");</code>
The initembed_test
reference is the function name generated by the BOOST_PYTHON_MODULE macro. Once we have made Python aware of this built-in module, we can modify the python code we run in the example to print out the result of the greet function:
<code>handle<> ignored((PyRun_String(
"import embed_test\n"
"print embed_test.greet()"
, Py_file_input
, main_namespace.ptr()
, main_namespace.ptr())
));</code>
The techniques used here are all based around the basic functionality available in the Python C API. However, the Boost::Python library does make it easier to expose your own code to the Python interpreter. Next we’ll look at exposing classes and then move on to the use of SWIG.