Chapter 7. Wrapping C Libraries with Cython
Controlling complexity is the essence of computer programming.
— B. Kernighan
We have seen how Cython can take Python code and improve its performance with
ahead-of-time compilation. This chapter will focus on the inverse: starting
with a C library, how do we make it accessible to Python? Such a task is
typically the domain of specialized tools like SWIG, SIP, Boost.Python, ctypes,
cffi, or others. Cython, while not automating the process like some, provides
the capability to wrap external libraries in a straightforward way. Cython
also makes C-level Cython constructs available to external C code, which can be
useful when we are embedding Python in a C application, for instance.
Because Cython understands both the C and Python languages, it allows full control over all aspects during interfacing. It accomplishes this feat while remaining Python-like, making Cython interfacing code easier to understand and debug. When wrapping C libraries in Cython, we are not restricted to a domain-specific wrapping language—we can bring to bear all of the Python language, its standard library, and any third-party libraries to help us, along with all the Cython constructs we have learned about in previous chapters.
When done well, Cython-wrapped libraries have C-level performance, minimal wrapper overhead, and a Python-friendly interface. End users need never suspect they are working with wrapped code.
Declaring External C Code in Cython
To wrap a C library ...