It is often easier to program in Python than C. But we have to realise that everything cannot be done in Python alone. Even Python itself is made from C. We can create our own program in C and can be extended to Python. We can use those code as if it is a builtin facility of Python. This can be made possible using a tool called Simplified Wrapper and Interface Generator(SWIG).
Here I’m going to import the avl tree(self balancing tree) into Python which I have implemented in C. Click here to download the source code.
The first step is to install SWIG. In most of the machines SWIG is not a default tool.
The next step is to create a interface file ‘avl.i’. Interface file consists of declarations of all the functions and global variables in ‘avl.c’ and allso all those variables prefixed by ‘extern’.
The above image is a small part of avl.i.
SWIG uses these two files(avl.c and avl.i) to extend avl tree to Python.
will produce two more file avl.py and avl_wrap.c. avl_wrap.c is the wrapper file created for the purpose of extension.
creates two object files, ‘avl.o’ and ‘avl_wrap.o’.
This is the last step. This will create the shared object file ‘_avl.so’.
If we create a make file, we don’t have to reapeat all these steps, if we make small changes in any of the codes(avl.c or avl.i). Instead we just have to call ‘make’. It will do all the above steps for us.
Now the python module corresponding to avl.c is made and can be used as normal modules in Python.