SwigによるPython拡張モジュール
配列処理の例。
// hoge.h class MyError {}; class MyArray { int num; int* vals; public: MyArray(int num); int __getitem__(int idx) throw(MyError); };
// hoge.cpp #include "hoge.h" MyArray::MyArray(int num) { this->vals = new int[num]; this->num = num; for (int i=0; i < num; i++) this->vals[i] = i; } int MyArray::__getitem__(int idx) throw(MyError) { if (idx < 0 || this->num <= idx) throw MyError(); return this->vals[idx]; }
// hoge.i %module hoge %{ #include "hoge.h" %} %include "hoge.h"
C:\temp\python>swig -c++ -python hoge.i C:\temp\python>g++ -c hoge.cpp -c hoge_wrap.cxx -IC:\Python25\include C:\temp\python>g++ -shared -o _hoge.pyd hoge.o hoge_wrap.o C:\Python25\libs\python25.lib C:\Python25\libs\libpython25.a
>>> import hoge >>> a = hoge.MyArray(100) >>> a[99] 99 >>> a[100] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "hoge.py", line 94, in __getitem__ def __getitem__(self, *args): return _hoge.MyArray___getitem__(self, *args) hoge.MyError