Cython基础--Cython入门

来源:互联网 发布:nhj提取软件 编辑:程序博客网 时间:2024/05/17 04:07

原文地址:http://blog.csdn.net/i2cbus/article/details/18181637


Cython入门

 

1 Cython是什么?

 

对你没有看错,是Cython,不是Python

当初也我也对这个名字感到很奇怪,但是了解之后,再才知这是我一直想要的工具,比起swig,这个工具要好上很多

它是一个用来快速生成Python扩展模块(extention module)的工具

它的语法是python语言语法和c语言语法的混血

他比swig更容易编写python的扩展模块

也许你会说swig可以直接通过c的头文件生成扩展模块,但是swig对回调函数的支持不是很好,

另外,如果用swig,很多情况下,你要写额外的代码将输入的参数转换成python对象以及将输出转成python对象,例如如果封装的一个C函数的参数是输入输出的话,又如如果C函数的参数中有回调函数的话

而在Cython,C里的类型,如int,float,long,char*等都会在必要的时候自动转成python对象,或者从python对象转成C类型,在转换失败时会抛出异常,这正是Cython最神奇的地方

另外,Cython对回调函数的支持也很好。

总之,如果你有写python扩展模块的需求,那么Cython真的是一个很好的工具

2 安装

2.1 Windows下安装

 先从http://cython.org下载软件包:Cython-0.19.2.zip

解压到一个目录,如D:\Cython-0.19.2

从开始菜单里打开Visual Studio Command Prompt,例如:MicroSoft Visual Studio  2010-> Visual Studio Tools -> Visual Studio Command Prompt(2010)

敲入如下命令:

D:

cd Cython-0.19.2

python setup.py install

命令执行完后就会把cython安装到python的安装目录下

2.2 Ubuntu下安装

apt-get install cython

3 第一个例子:

3.1 创建helloworld目录

创建helloworld.pyx,内容如下:

cdef extern from"stdio.h":

    extern int printf(const char *format, ...)

def SayHello():

printf("hello,world\n")

   

代码非常简单,就是调用了C函数printf打印hello,world

4 如何编译

4.1 最方便的当然是利用python的Distutils了,看下如何来实现

先在helloworld目录下创建Setup.py,内容如下:

from distutils.core import setup

from distutils.extension import Extension

from Cython.Build import cythonize

 

setup(

  name = 'helloworld',

  ext_modules=cythonize([

    Extension("helloworld", ["helloworld.pyx"]),

    ]),

)

 

 

编译:

python Setup.py build

安装:

python Setup.py install

安装后,会将在build/lib.???目录下生成的helloworld.pyd拷贝到Lib/site-packages

注:

  有时我们只是希望测试一下,并不希望安装,这时可以把build/lib.???目录下的helloworld.pyd拷贝到当前目录

  或者在importhelloworld前执行脚本:import sys;sys.path.append(pathof helloworld.pyd)

 

测试:

>>>import helloworld

>>>helloworld.SayHello()

hello,world

4.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

 

测试:

>>>import helloworld

>>>helloworld.SayHello()

hello,world

(完)

本文示例下载

0 0
原创粉丝点击