Embedding the Python interpreter
Jason Furtney
@jkfurtney
Rock Mechanics
![](https://s3.amazonaws.com/media-p.slid.es/uploads/263709/images/1810811/can_aecl_underground.jpg)
Rock Mechanics
![](https://s3.amazonaws.com/media-p.slid.es/uploads/263709/images/1810837/openpit_mining.jpg)
Rock Mechanics
![](https://s3.amazonaws.com/media-p.slid.es/uploads/263709/images/1810842/Picture2.png)
Rock Mechanics
![](https://s3.amazonaws.com/media-p.slid.es/uploads/263709/images/1810870/Picture3.jpg)
Numerical Modeling
![](https://s3.amazonaws.com/media-p.slid.es/uploads/263709/images/1810863/stope_large.png)
Numerical Modeling
![](https://s3.amazonaws.com/media-p.slid.es/uploads/263709/images/1810935/Untitled.png)
Ask the experts
![](https://s3.amazonaws.com/media-p.slid.es/uploads/263709/images/1811022/so.png)
Python
My C
extension
code
Extension module
My C program
Embedding and extending
Python
My C
extension
code
def say_hello(name):
"Greet somebody."
print "Hello %s!" % name
#include <Python.h>
static PyObject*
say_hello(PyObject* self, PyObject* args)
{
const char* name;
if (!PyArg_ParseTuple(args, "s", &name))
return NULL;
printf("Hello %s!\n", name);
Py_RETURN_NONE;
}
static PyMethodDef HelloMethods[] =
{
{"say_hello", say_hello, METH_VARARGS, "Greet somebody."},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC
inithello(void)
{
(void) Py_InitModule("hello", HelloMethods);
}
Basic extending
Automatic generation of wrapper code
- SWIG
- XDress
- Cython
- cffi
- Boost::Python
We rolled our own...
#include <Python.h>
int main(int argc, char *argv[])
{
/* Pass argv[0] to the Python interpreter */
Py_SetProgramName(argv[0]);
/* Initialize the Python interpreter. Required. */
Py_Initialize();
/* Add a static module */
inithello();
...
Basic embedding
Call Python functions from C
Call C functions from Python
Not in the documentation
Redefine the sys.stdin and sys.stdout objects
Write a Python function to compile code, execute code, capture output and handle errors.
Write as much as possible in Python and call it from C.
Pitfalls
Reference counting is hard
Object life-cycle issues
Threading and GUI updates
Compiler compatibility
Python state cannot be serialized
Victories
IPython Qt console
Qt integration via PySide
NumPy, SciPy and Matplotlib integration
Our customers can use any 3rd party Python library
End product
![](https://s3.amazonaws.com/media-p.slid.es/uploads/263709/images/1811124/pfc.png)
Embedding the Python interpreter
By Jason Furtney
Embedding the Python interpreter
- 560