Exposing Functions to Embedded Python

So 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:

const char* greet()
{
	return "Hello World from C++";
}

BOOST_PYTHON_MODULE(embed_test)
{
	def("greet", greet);
}

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:

if(PyImport_AppendInittab("embed_test", initembed_test) == -1)
		throw std::runtime_error("Failed to add test module to builtins");

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:

handle<> ignored((PyRun_String(
	"import embed_test\n"
	"print embed_test.greet()"

	, Py_file_input
	, main_namespace.ptr()
	, main_namespace.ptr())
));

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.

Comments are closed.