From "Speeding up Python by fusing with Cython C" O'Reilly I tried to trace on Ubuntu that a function written in C language can be imported and executed in Python.
First of all, since the sample of this book is on github, download it in a zip file. https://github.com/cythonbook/examples
Move to the extracted directory. examples-master/07-wrapping-c/01-wrapping-c-functions-mt-random
There is a Makefile here, so try making it. Then it seems that the necessary files have been created The example on p128 of the same book works from IPython. In [1]: import mt_random
In [2]: mt_random.init_state(42)
In [3]: mt_random.rand() Out[3]: 0.37454011439684315
Sure, you can wrap C functions in Cython as described in the book.
First, there is a C source file and a header file.
mt.pxd
cdef extern from "mt19937ar.h":
void init_genrand(unsigned long s)
double genrand_real1()
mt_random.pyx
# distutils: sources=["mt19937ar.c"]
cimport mt
def init_state(unsigned long s):
mt.init_genrand(s)
def rand():
return mt.genrand_real1()
setup.py
from distutils.core import setup, Extension
from Cython.Build import cythonize
ext = Extension("mt_random",
sources=["mt_random.pyx", "mt19937ar.c"])
setup(name="mersenne_random",
ext_modules = cythonize([ext]))
And the Makefile that runs setup.py was already included in the zip file. If you make this, you will get the result of the previous execution.
I found that I can wrap it by writing pxd file, pyx file, setup.py.
About the mt_random module implemented in this way help(mt_random) Then It is also convenient to see help as shown below.
Help on module mt_random: NAME mt_random
FILE / (Omitted) /examples-master/07-wrapping-c/01-wrapping-c-functions-mt-random/mt_random.so
FUNCTIONS init_state(...)
rand(...)
DATA test = {}
To understand more than this example, it seems to read Chapter 7 of the same book.
Even if you don't write everything in C, write only the bottleneck in C I'm happy that writing a wrapper using Cython is enough.