昨日の内容をcythonで拡張モジュール

http://d.hatena.ne.jp/podhmo/20101129/1291038575の内容をcythonで

cython

sudo pip install cython

必要なもの

  • setup.py
    • .soファイルの作成に利用
  • xyzzy.pyx
    • pyx -> cにcythonが変換してくれる
setup.py

cythonのbuild_extを使うことに注意

from distutils.core import setup, Extension
from Cython.Distutils import build_ext # use cython's buld_ext

setup(
  name = 'xyzzy',
  versioin = '1.0',
  cmdclass = {'build_ext': build_ext},
  ext_modules = [Extension("xyzzy", sources = ["xyzzy.pyx"])]
  )
xyzzy.pyx

python風のsyntaxで書ける。

  • cdefはC内だけの関数
  • defはC,pythonどちらから呼べる関数
    • 引数の解析などするのでcdefより重い
  • classも定義できる
    • atributeが存在
      • readonly,public
def foo():
    return 42

compile

python setup.py build_ext # xyzzy.soが生成される