Here's a tiny but complete example of passing numpy arrays to an external C function, logically
fc( int N, double* a, double* b, double* z ) # z = a + b
using cython. (This is certainly well known to those who know it well. Comments are welcome. Last modified: February 23, 2011, for Cython 0.14.)
First reading or removing Cython build and Cython with NumPy .
2 steps:
python f-setup.py build_ext --inplace
rotates f.pyx and fc.cpp f.so , the dynamic librarypython test-f.py
import f loads f.so ; f.fpy( ... ) calls C fc( ... ) .
python f-setup.py uses distutils to run cython, compile and link:
cython f.pyx -> f.cpp
compile f.cpp and fc.cpp
link fo fc.o f.so , the dynamic lib that will load python import f .
For students, I would suggest: outline these steps, view the files below, then download and run them.
( distutils is a huge, confusing package used to make Python packages for distribution and install them. Here we use only a small part to compile and link to f.so This step has nothing to do with Keaton, but it may confuse confusing; simple errors in .pyx can cause pages of obscure error messages from g ++ compilation and links. See also distutils doc and / or SO questions about distutils .)
Like make , setup.py will repeat cython f.pyx and g++ -c ... f.cpp if f.pyx newer than f.cpp .
To clean rm -r build/ .
An alternative to setup.py would be to run the steps separately in a script or Makefile:
cython --cplus f.pyx -> f.cpp # see cython -h
g++ -c ... f.cpp -> fo
g++ -c ... fc.cpp -> fc.o
cc-lib fo fc.o -> dynamic library f.so
Change the cc-lib-mac wrapper below for your platform and installation: this is not very, but not enough.
For real-world examples of Cython C packaging, look at .pyx files in almost any SciKit .
See also: Cython for NumPy and SO users questions / tagged / cython .
To unzip the following files, cut-paste the lot into one large file, say cython-numpy-c-demo , then on Unix (in a clean new directory) run sh cython-numpy-c-demo .
#-------------------------------------------------------------------------------- cat >f.pyx <<\!