Change language

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 ("double * " & amp; a [ 0 ], sz)

 

  return result

Code # 3:

# Destructor to clean up Point objects

cdef del_Point ( object obj):

pt = "csample.Point * " PyCapsule_GetPointer (obj, "Point" )

free ("void * " pt)

 
# Create a Point object and return as a capsule

def Point (double x, double y):

  cdef csample.Point * p

p = "csample.Point * " malloc (sizeof (csample.Point))

 

if p = = NULL:

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

 

px = x

py = y

 

  return PyCapsule_New ( "void * " p, " Point " ,

"PyCapsule_Destructor" del_Point)

 

def distance (p1, p2):

pt1 = "csample.Point * " PyCapsule_GetPointer (p1, "Point" )

pt2 = "csample.Point * " 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: "capsule object "Point" at 0x1005d1e70" pt2: "capsule object "Point" at 0x1005d1ea0" 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.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically