Python で SWIG を使ってみる
前準備
Python の準備(Windows,Ubuntu 上)
- Windows での Python 3.10,関連パッケージ,Python 開発環境のインストール(winget を使用しないインストール): 別ページ »で説明
- Ubuntu では,システム Pythonを使うことができる.Python3 開発用ファイル,pip, setuptools のインストール: 別ページ »で説明
【サイト内の関連ページ】
- Python のまとめ: 別ページ »にまとめ
- Google Colaboratory の使い方など: 別ページ »で説明
【関連する外部ページ】 Python の公式ページ: https://www.python.org/
SWIG のインストール
SWIG を使ってみる
http://www.swig.org/Doc1.3/Python.html#Python_nn6 に記載のサンプルプログラム- example.i
%module example %{ #define SWIG_FILE_WITH_INIT #include "example.h" %} int fact(int n);
- example.c
#include "example.h" int fact(int n) { if (n < 0){ /* This should probably return an error, but this is simpler */ return 0; } if (n == 0) { return 1; } else { /* testing for overflow would be a good idea here */ return n * fact(n-1); } }
- example.h
int fact(int n);
- setup.py
#!/usr/bin/env python """ setup.py file for SWIG example """ from distutils.core import setup, Extension example_module = Extension('_example', sources=['example_wrap.c', 'example.c'], ) setup (name = 'example', version = '0.1', author = "SWIG Docs", description = """Simple swig example from docs""", ext_modules = [example_module], py_modules = ["example"], )
- SWIG を使ってみる
次のように操作する.
swig -python example.i python setup.py build_ext --inplace
- Python プログラムを実行してみる
import example example.fact(4)