金子邦彦研究室プログラミングRuby による Web/データベース・プログラミングSwig を利用して、Ruby プログラムから C++ を呼び出す

Swig を利用して、Ruby プログラムから C++ を呼び出す

  1. 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(); 
    };
    
  2. 試しにコンパイルしてみる

    これは、point2d.cpp と point2d.hpp の文法チェックのため

    g++ -fPIC -c -o point2d.o point2d.cpp 
    

    [image]
  3. point2d.i の作成

    モジュール名を MyCPP に設定している.

    %module MyCPP
    %{
    #include "point2d.hpp"
    %}
    %include "point2d.hpp"
    
  4. swig の実行
    rm -f point2d_wrap.*
    swig2.0 -ruby -c++ point2d.i 
    

    [image]
  5. extconf.rb の作成

    「create_makefile('MyCPP')」と記述しているので、MyCPP.so が生成されることになる

    require 'mkmf'
    
    dir_config('point2d')
    $libs += " -lstdc++ "
    if have_header('point2d.hpp') 
      create_makefile('MyCPP')
    end
    
  6. ビルド
    ruby extconf.rb
    make CC=g++
    

    [image]
  7. インストール
    sudo make site-install
    

    [image]
  8. 使ってみる
    irb
    
    require 'MyCPP'
    a = MyCPP::Point2d.new(100, 200)
    a.x
    a.y
    

    [image]