Wrap C with Cython for use from Python

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.

Declaration of external C code in Cython (extension .pxd)

mt.pxd


cdef extern from "mt19937ar.h":
    void init_genrand(unsigned long s)
    double genrand_real1()

C function wrap (extension .pyx)

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 file that tells you how to compile

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.

Recommended Posts

Wrap C with Cython for use from Python
Wrap C ++ with Cython for use from Python
Use C ++ functions from python with pybind11
Call C from Python with DragonFFI
Tips for calling Python from C
Use DeepL with python (for dissertation translation)
Array buffer object for use with Cython
Wrap (part of) the AtCoder Library in Cython for use in Python
Use thingsspeak from python
[Python] Use JSON with Python
Use fluentd from python
Tips for Python beginners to use the Scikit-image example for themselves 9 Use from C
Use MySQL from Python
Use logger with Python for the time being
Use mecab with Python3
Use DynamoDB with Python
~ Tips for Python beginners from Pythonista with love ① ~
Use Python 3.8 with Anaconda
Use python with docker
Use MySQL from Python
Use BigQuery from python.
~ Tips for Python beginners from Pythonista with love ② ~
Use mecab-ipadic-neologd from python
Benchmark for C, Java and Python with prime factorization
Use Python installed with pyenv for PL / Python execution environment
Programming with your smartphone anywhere! (Recommended for C / Python)
Use Trello API with python
ABC163 C problem with python3
Use TUN / TAP with Python
Use Cython with Jupyter Notebook
Use subsonic API with python3
ABC188 C problem with python3
With skype, notify with skype from python!
Use e-Stat API from Python
ABC187 C problem with python
Let's use a scripting language for a comfortable C ++ life C ++ implementation after verification with python
Execute C ++ functions from Python with Pybind11 (for Windows & Visual Studio Code people) Debugging
Use IvyFEM (Finite Element Method Library for .NET) from Python
[python] A note when trying to use numpy with Cython
Introduction to Python for VBA users-Calling Python from Excel with xlwings-
Get data from analytics API with Google API Client for python
Use a scripting language for a comfortable C ++ life-OpenCV-Port Python to C ++-
Execute C ++ functions from Python with Pybind11 (for Windows & Visual Studio Code people) Environment construction
Solve ABC163 A ~ C with Python
Python: How to use async with
Use Stanford Core NLP from Python
Use PointGrey camera with Python (PyCapture2)
Use vl53l0x with Raspberry Pi (python)
Using Rstan from Python with PypeR
Install Python from source with Ansible
Create folders from '01' to '12' with python
[Python] Use Basic/Digest authentication with Flask
Call popcount from Ruby / Python / C #
Getting Started with Python for PHPer-Classes
Use NAIF SPICE TOOLKIT with Python
Read and use Python files from Python
Next, use Python (Flask) for Heroku!
Forcibly use Google Translate from python
Python cheat sheet (for C ++ experienced)
Use rospy with virtualenv in Python3
Solve ABC168 A ~ C with Python