1. Cython是什么?
它是一個用來快速生成Python擴展模塊(extention module)的工具,語法是Python和c的混血。在Cython,C里的類型,如int,float,long,char*等都會在必要的時候自動轉成python對象,或者從python對象轉成C類型,在轉換失敗時會拋出異常,這正是Cython最神奇的地方。另外,Cython對回調函數的支持也很好。Cython作為一個Python的編譯器,在科學計算方面很流行,用於提高Python的速度,通過OpenMPI庫還可以進行吧並行計算。
2. 安裝
Cython安裝非常方便,因為一般像Anaconda、Python(x,y)等都附帶了,如果沒有用這些,也可以自己安裝。附上安裝教程 http://docs.cython.org/src/quickstart/install.html
3. 例子
cdef extern from"stdio.h": extern int printf(const char *format, ...) def SayHello(): printf("hello,world\n")
代碼非常簡單,就是調用了C函數printf打印hello,world.
簡單解釋
(1) cdef 定義類c的函數
(2) 可以引入c庫中的模塊以及其中的函數,並且被調用
4 運行
(1) 利用python的distutils
上面的代碼被命令為hello.pyx,在同級目錄下創建一個setup.py
from distutils.core import setup from Cython.Build import cythonize from distutils.extension import Extension setup( name = 'Hello world app', ext_modules = cythonize([ Extension("hello",["hello.pyx"]), ]), )
然后
>>>python setup.py build
>>>python setup.py install
(2) 自己寫Makefile
寫Makefile的好處就是可以知道編譯的實質:
下面是用於Windows下編譯的Makefile,Makefile內容如下:
ALL :helloworld.pyd
helloworld.c : helloworld.pyx
cython -o helloworld.c helloworld.pyx
helloworld.obj :helloworld.c
cl -c -Id:\python27\include helloworld.c
helloworld.pyd :helloworld.obj
link /DLL /LIBPATH:d:\python27\libshelloworld.obj /OUT:helloworld.pyd
執行命令:
set PATH=D:\Python27\Scripts;%PATH%
nmake
進行編譯,會在根目錄下生成helloworld.pyd
linux下的Makefile和Windows下的類似,只是編譯器不同而己,另外,生成的文件名為:helloworld.so,而不是helloworld.pyd