External modules in Python
07 Feb 2016You can extend Python relatively easily with the development libraries. Once installed, you can write a module in C, build it and start using it in your Python code.
In today’s post, I’ll create a Hello world module and use it from python.
Environment
In order to get started, you’ll need to prepare your environment with the right tools. It’s also and idea to create a bit of a project structure.
Create a directory that your code will go into. My source structure looks like this:
My Dockerfile
looks as follows. This should describe how to setup your environment:
The module
The module itself really consists of a c header and source file and a setup.py
file to build/install the module.
The header file looks as follows:
Note the Python.h
header as well as the PyObject
types being used. These are a part of the python-dev
library that we installed before. This header file then gets implemented pretty simply. Here I’ve cheated using printf
to do the printing for us:
A brief analysis of this code sees us building a PyMethodDef
array. We expose it out using Py_InitModule3' from within the initialization function (typed with
PyMODINIT_FUNC`).
To out actual function itself, we’re printing “I’m here” to the console and then bailing out with a return value of Py_None
, which is equivalent to None
.
Building
To build our module, we’ll use setup.py
. It’ll read as follows:
To invoke the build, we issue the following:
Testing it out
Now that our module is built, we can give it a test. Easiest to use the python console to do this for us:
Finishing up
I couldn’t pick a simpler example. More complex examples to come, but this is how we establish the bridge between C and python.