Cython to wrap existing C code



It offers many useful features :

  • Writing Python code that invokes and translates code to C / C ++.
  • Easily tune readable Python code for simple C performance by adding static type declarations.
  • Use combined source-level debugging to find bugs in given Python, Cython, and C code.
  • Effective interoperability with large datasets, such as using multidimensional NumPy arrays.
  • Integrate with existing code and data from low-level or high-performance libraries and applications.

Create an extension using Cython — not an easy task. To do this, you need to create a collection of wrapper functions. Assuming the working code shown was compiled into a C library called libwork . The code below will create a file named csample.pxd .

Code # 1:

# cwork.pxd
#
# Ads & quot ; external & quot; C
# functions and structures

 

cdef extern from "work.h" :

 

int gcd ( int , int )

int divide ( int , int , int * )

double avg (double * < code class = "plain">, int ) nogil

 

ctypedef struct Point:

double x

double y

 

double distance (Point * , Point * )

In Cython, the above code will work as a C header file. The original cdef extern declaration from work.h declares the required C header file. The following declarations are from header. The name of this file is — cwork.pxd . The next target — create a file work.pyx which will define wrappers that connect the Python interpreter to the underlying C code declared in cwork.pxd .

Code # 2:

# work.pyx
# Importing low-level C declarations

  
cimport cwork
# Importing functions from Python
# and C stdlib

from cpython.pycapsule cimport *  

from libc.stdlib cimport malloc, free

 
# Wrappers

def gcd (unsigned int x, unsigned int y):

return cwork.gcd (x, y)

  

def divide (x, y):

cdef int rem

quot = cwork.divide (x, y, & amp; rem)

  return quot, rem

 

def avg (double [:] a): < / code>

cdef:

int sz

  double result

 

sz = a.size

 

with nogil:

result = cwork.avg (& lt; double * & gt; & amp; a [ 0 ], sz)

 

  return result

Code # 3:

# Destructor to clean up Point objects

cdef del_Point ( object obj):

pt = & lt; csample.Point * & gt; PyCapsule_GetPointer (obj, "Point" )

free (& lt; void * & gt; pt)

 
# Create a Point object and return as a capsule

def Point (double x, double y):

  cdef csample.Point * p

p = & lt; csample.Point * & gt; malloc (sizeof (csample.Point))

 

if p = = NULL:

raise MemoryError ( "No memory to make a Point" )

 

px = x

py = y

 

  return PyCapsule_New ( & lt; void * & gt; p, " Point " ,

& lt; PyCapsule_Destructor & gt; del_Point)

 

def distance (p1, p2):

pt1 = & lt; csample.Point * & gt; PyCapsule_GetPointer (p1, "Point" )

pt2 = & lt; csample.Point * & gt; PyCapsule_GetPointer (p2, "Point" )

 

  return csample.distance (pt1, pt2)

Finally, to build an extension module, create a file work.py

Code # 4:

# importing libraries

from distutils.core import setup

from distutils.extension import Extension

from Cython.Distuti ls import build_ext

  

ext_modules = [Extension ( `work`

  [ `work.pyx` ], 

libraries = [ `work` ], 

  library_dirs = [ `.` ])]

 

setup (name = ` work extension module` ,

cmdclass = { ` build_ext` : build_ext},

ext_modules = ext_modules)

Code # 5: Building the resulting module for experiments.

bash % python3 setup.py build_ext --inplace

running build_ext

 
cythoning work.pyx to work.c

building  `work` extension

  
gcc -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes

- I / usr / local / include / python3 . 3m -c work.c

-o build / temp . macosx-10.6-x86_64-3.3 / work . o

 

gcc -bundle -undefined dynamic_lookup build / temp . macosx-10.6-x86_64-3.3 / work . o

- L. -lwork -o work.so

bash %

We now have a plugin work.so Let`s see how it works.

Code # 6:

import sample

print ( " GCD: " , sample.gcd ( 12 , 8 ))

 

print ( "Division:" , sample.divide ( 42 , 10 ))

  

import array

arr = array.array ( ` d` , [ 1 , 2 , 3 ])

print ( "Average :" , sample.avg (a)

 

pt1 = sample.Point ( 2 , 3 )

pt2 = sample.Point ( 4 , 5 )

 

print ( " pt1: " , pt1)

print ( "pt2:" , pt2)

 

print ( "Distance between the two points:"

sample.distance (pt1, pt2))

Output:

 GCD: 4 Division: (4, 2) Average: 2.0 pt1: & lt; capsule object "Point" at 0x1005d1e70 & gt; pt2: & lt; capsule object "Point" at 0x1005d1ea0 & gt; Distance between the two points: 2.8284271247461903 

At a high level, Cython usage is modeled after C. The .pxd files simply contain C definitions (similar to .h ), and the .pyx files contain the implementation (similar to the .c file). The cimport statement is used by Cython to import definitions from the .pxd file. This is different from using a regular Python import statement that would load a regular Python module.