cythonのコンパイル

Cython(pythonライクな文法のcのメタ言語)を自分でコンパイルする方法がわかりにくかったのでメモ
http://ja.wikipedia.org/wiki/Cython

  • pythonとほぼ同じ文法
  • それをcythonがc/c++言語に変換してくれる
  • 変換されて出てきたc/cppファイル(libpython2.6にのみ依存)は自由にコンパイルして使える
  • cの自動生成機としてだけではなく、pythonとのインターフェースも充実(本来的にはこっちが大事)
  • 基本的にcライブラリしかcallできないが、numpyは使える←重要
  • ただし型情報を追加しないと普通のnumpy同様遅い

http://omake.accense.com/static/doc-ja/cython/src/tutorial/numpy.html

自分でコンパイルする方法を調べた理由は、nvcc(cudaのc++コンパイラ)でコンパイルする方法がわからなかったため。
普通にpythonのライブラリを書く分にはsetup.pyでbuildするほうが話が早いです...

使い方(python2.6 ubuntuの場合)

  • .pyxファイルを作成(型情報を付与したpythonみたいな感じ)
  • cython *.pyx する
    • このときmain関数にしたかったら--embedオプションをつける
  • 任意のcコンパイラコンパイル(includeファイルは/usr/include/python2.6/)
  • 任意のcコンパイラで-lpython2.6とリンク

まだg++でしか確かめてないので、nvccなどでうまくいくかは不明。

# building by two steps                                                                                                           
## use --embed if you want to include main functin in the output c file
cython helloworld.pyx --embed
## helloworld.c is created (with main function if --embed option is given)
## compile
g++ -c helloworld.c -I/usr/include/python2.6/
## link
g++ helloworld.o -lpython2.6 -o sample1.exe
./sample1.exe

# building by one step
cython helloworld.pyx --embed
g++ helloworld.c -I/usr/include/python2.6/ -lpython2.6 -o sample2.exe
./sample2.exe