Swig を利用して、Ruby プログラムから C++ を呼び出す
- 作成する Ruby パッケージのライブラリファイル名: MyCPP.so
* Ruby ではMyCPP.so を読み込むために 「require 'MyCPP'」のように実行する - モジュール名: MyCPP
* Ruby では、クラス名の前に「MyCPP::」を付けることになる - Ruby側からみた時のクラス名とメソッド名と、関数名の対応
C++ クラス名 C++ メソッド名 Ruby から見たメソッド名 Point2d Point2d MyCPP::Point2d.new Point2d x MyCPP::Point2d.x Point2d y MyCPP::Point2d.y - パッケージ名: MyCPP
- C++ プログラムの作成
例えば、次のように point2d.cpp を作成
# include "point2d.hpp" Point2d::Point2d() : _x( 0.0 ), _y( 0.0 ) { } Point2d::Point2d(const double x, const double y) : _x( x ), _y( y ) { } Point2d::~Point2d() { } double Point2d::x() { return this->_x; } double Point2d::y() { return this->_y; }
例えば、次のように point2d.hpp を作成
class Point2d { private: double _x; double _y; public: Point2d(); Point2d(const double x, const double y); ~Point2d(); double x(); double y(); };
- 試しにコンパイルしてみる
これは、point2d.cpp と point2d.hpp の文法チェックのため
g++ -fPIC -c -o point2d.o point2d.cpp
- point2d.i の作成
モジュール名を MyCPP に設定している.
%module MyCPP %{ #include "point2d.hpp" %} %include "point2d.hpp"
- swig の実行
rm -f point2d_wrap.* swig2.0 -ruby -c++ point2d.i
- extconf.rb の作成
「create_makefile('MyCPP')」と記述しているので、MyCPP.so が生成されることになる
require 'mkmf' dir_config('point2d') $libs += " -lstdc++ " if have_header('point2d.hpp') create_makefile('MyCPP') end
- ビルド
ruby extconf.rb make CC=g++
- インストール
sudo make site-install
- 使ってみる
irb require 'MyCPP' a = MyCPP::Point2d.new(100, 200) a.x a.y