Cython - Linking C/C++ with Python

Accelerate Python Beyond Expectation!

All the contents in this note are summarized from two Cython tutorials:

  • Cython - A guide for Python programmers.

  • Learning Cython Programming second edition.

Compile

Compile by hand

1.From file.pyx to file.c (c file)

cython file.pyx

Type $cython to check all the options available for cython such as --cplus(instead of generating file.c, file.cpp is generated) --embed(embed the python interpreter) -2 -3 (compile based on python 2 or python 3 syntax and code semantic), etc.

2.From file.c to file.o (object file)

gcc -g -O2 -fpic `python-config --cflags` -c file.c -o file.o

3.From file.o to file.so (dynamic library)

gcc -shared -o file.so file.o `python-config --libs`
or 
LDFLAGS=$(python-config --ldflags)
gcc file.o -o file.so -shared ${LDFLAGS}

pyximport module (very convenient! import .pyx just like importing .py module)

Get the file.pyx ready and in python or ipython:

import pyximport
pyximport.install()
import file
file.function(para)

Calling C functions from Python

  • AddFunction.c
#include <stdio.h>
int AddFunction(int a, int b){
  printf("Look we are within your c code!!\n")
  return a + b;
}
  • AddFunction.h
#ifndef __ADDFUNCTION_H__
#define __ADDFUNCTION_H__

extern int AddFunction (int, int);

#endif //__ADDFUNCTION_H__
  • PyAddFunction.pyx
cdef extern from "AddFunction.h"
  cdef int AddFunction(int, int)

#Python entry point - calling C function
def Add(a, b)
  return AddFunction(a, b)
  • Compile
cython PyAddFunction.pyx

gcc -g -O2 -fpic -c PyAddFunction.c -o PyAddFunciton.o `python-config --includes`
gcc -g -O2 -fpic -c AddFunction.c -o AddFunction.o
gcc -g -O2 -shared -o PyAddFunction.so AddFunction.o PyAddFunction.o `python-config --libs`
  • Load function
from PyAddFunction import Add
Add(1,2)

License

Copyright 2017-present Ye Zheng.

Released under the MIT license.