Interfacing with C code using Cython
In this section, we're going to look at a third-party tool called Cython, which is another tool for bridging the gap between Python and the software that has been compiled into machine code.
If we have a situation where we want to implement part of our project in compiled code, we could do this by creating a dynamic library containing the code and calling to it with ctypes
; however, that's a roundabout way to get where we want to go. We'd end up writing a lot of code twice: once for the sake of our compiler and then again to tell ctypes
about details such as function signatures and data structures.
Now this is inefficient and violates one of the most important principles of programmingâdon't repeat yourself. There's a tool that's better suited to this situation, as you may have surely guessed, and that tool is Cython.
Working with Cython
What Cython does is it translates a Python source code file into a C source code file containing equivalent calls to...