It is a tool used to quickly generate Python extension module (extension module) tool
its syntax is a mixture of python language syntax and c language syntax
him It is easier to write python extension modules than swig
Maybe you will say that swig can generate extension modules directly through c header files, but swig's support for callback functions is not very good,
In addition, if you use swig, in many cases, you have to write additional code to convert the input parameters into python objects and convert the output into python objects, for example, if you encapsulate a C function If the parameters are input and output, and if there is a callback function in the parameters of the C function,
and in Cython, the types in C, such as int, float, long, char*, etc. will all Automatically convert to python objects when necessary, or convert from python objects to C types. When the conversion fails, an exception will be thrown . This is the most amazing thing about Cython
In addition, Cython also has good support for callback functions.
In short, if you have the need to write python extension modules, then Cython is really a good tool
cython Installation under linux:
[blueelwang@pythontab ~]$ wget https://pypi.python.org/packages/b7/67/7e2a817f9e9c773ee3995c1e15204f5d01c8da71882016cac10342ef031b/Cython-0.25.2.tar.gz [blueelwang@pythontab ~]$ tar xzvf Cython-0.25.2.tar.gz [blueelwang@pythontab ~]$ cd Cython-0.25.2 [blueelwang@pythontab ~]$ python setup.py install
[blueelwang@pythontab ~]$ sudo pip install Cython --install-option="--no-cython-compile"
[blueelwang@pythontab ~]$ sudo apt-get install cython
After installation, enter cython to verify whether the installation is successful
def say_hello_to(name): print("Hello %s!" % name)
The purpose is to convert the hello.pyx program into hello.c and compile it into an so file
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext ext_modules = [Extension("hello", ["hello.pyx"])] setup( name = 'Hello world app', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules )
[blueelwang@pythontab ~]$ python setup.py build_ext --inplace
The execution result will generate two files: hello.c and hello.so (files encapsulated with PyObject*)
import hello hello.say_hello_to("hi,cython!!")
The main purpose of cython is to: Simplify the cumbersome encapsulation process of python calling c language programs, and improve the execution speed of python code (C The execution speed of the language is faster than python)
The above is the detailed content of Share Cython installation and usage experience. For more information, please follow other related articles on the PHP Chinese website!