LoginSignup
13
14

More than 5 years have passed since last update.

SWIGを使ってPython用のモジュールを作ってみる

Posted at

SWIGを使ってみた。前にJumanで形態素解析するときに使った覚えがありますが、ちゃんと調べたことなかったので自分用にメモ.

マニュアル
http://www.swig.org/Doc1.3/Python.html#Python_nn4

インストールはREADMEにしたがって行います。

$./configure
$make
$su
$make install

インストールが終わったらマニュアルのサンプルを参考にいじりまわす。

.iファイルの中身は
http://blog.livedoor.jp/yoshichi9/archives/21911908.html参考

module モジュール名
%{
include ヘッダファイル名
%}
関数の列挙(または.hファイル)
#define(マクロの定義など)

らしいです。

さて、次に正規分布に従う値を返す拡張モジュールを作ってみる。

まずは各種cのソースファイルを準備。

normaldist.h
double normal_distribution(double myu, double sigma, double x);
normaldist.c
#include "normaldist.h"
#include <math.h>

double normal_distribution(double myu, double sigma, double x){

  double d;
  double coefficient, in_exp;

  coefficient = sqrt(2 * M_PI * sigma); //係数
  in_exp = exp( -pow( x - myu, 2 ) / (2 * sigma ));  //expの肩にのるやつ

  d = in_exp / coefficient;

  return d;
}

次にswig用の.iファイル

normaldist.i
%module normaldist

%{
#define SWIG_FILE_WITH_INIT
#include "normaldist.h"
#include <math.h>
  %}

double normal_distribution(double myu, double sigma, double x);

最後にsetup.py

setup.py
from distutils.core import setup, Extension

module1 = Extension('_normaldist',
                    sources = ['normaldist_wrap.c', 'normaldist.c'])

setup (name = 'normaldist',
       version = '1.0',
       description = 'This is a normaldist package',
       ext_modules = [module1],
       py_modules = ["normaldist"],)

あとは順番にコマンドを打ち込むだけでokです。

$swig -python normaldist.i
$python setup.py build_ext --inplace

同ディレクトリ内に_normaldist.soができているはず.

13
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
14