Cython to Wrap Existing C Code
ganesh kavhar
Python | PySpark | Databricks | ETL | SQL | Unix | Big Data | Data warehouse
What is Cython ?
It is an optimizing static compiler for both the Python programming language and the extended Cython programming language. It is used to make it easy to write C extensions for Python as easy as Python itself.
It comes up with many helpful features :
- Writing a Python code that calls back and forth from and to C/C++ code.
- Easily tuning of readable Python code into plain C performance by adding static type declarations.
- Use of combined source code level debugging to find bugs in given Python, Cython and C code.
- Efficient interaction with large data sets, e.g. using multi-dimensional NumPy arrays.
- Integration with existing code and data from low-level or high-performance libraries and applications.
To make an extension with Cython is a tricky task to perform. Doing so, one needs to create a collection of wrapper functions. Assuming that the work code shown has been compiled into a C library called libwork. The code below will create a file named csample.pxd.
Code #1 :
# cwork.pxd
#
# Declarations of "external" C
# functions and structures
cdef extern from "work.h":
int gcd(int, int)
int divide(int, int, int *)
double avg(double *, int) nogil
ctypedef struct Point:
double x
double y
double distance(Point *, Point *)
In Cython, the code above will work as a C header file. The initial declaration cdef externfrom "work.h" declares the required C header file. Declarations that follow are taken from the header. The name of this file is cwork.pxd. Next target is to create a work.pyx file which will define wrappers that bridge the Python interpreter to the underlying C code declared in the cwork.pxd file.