ext/dl/sample/c++sample.rb


DEFINITIONS

This source file includes following functions.


   1  =begin
   2   This script shows how to deal with C++ classes using Ruby/DL.
   3   You must build a dynamic loadable library using "c++sample.C"
   4   to run this script as follows:
   5     $ g++ -o libsample.so -shared c++sample.C
   6  =end
   7  
   8  require 'dl'
   9  require 'dl/import'
  10  require 'dl/struct'
  11  
  12  # Give a name of dynamic loadable library
  13  LIBNAME = ARGV[0] || "libsample.so"
  14  
  15  class Person
  16    module Core
  17      extend DL::Importable
  18      
  19      dlload LIBNAME
  20  
  21      # mangled symbol names
  22      extern "void __6PersonPCci(void *, const char *, int)"
  23      extern "const char *get_name__6Person(void *)"
  24      extern "int get_age__6Person(void *)"
  25      extern "void set_age__6Personi(void *, int)"
  26  
  27      Data = struct [
  28        "char *name",
  29        "int age",
  30      ]
  31    end
  32  
  33    def initialize(name, age)
  34      @ptr = Core::Data.alloc
  35      Core::__6PersonPCci(@ptr, name, age)
  36    end
  37  
  38    def get_name()
  39      str = Core::get_name__6Person(@ptr)
  40      if( str )
  41        str.to_s
  42      else
  43        nil
  44      end
  45    end
  46  
  47    def get_age()
  48      Core::get_age__6Person(@ptr)
  49    end
  50  
  51    def set_age(age)
  52      Core::set_age__6Personi(@ptr, age)
  53    end
  54  end
  55  
  56  obj = Person.new("ttate", 1)
  57  p obj.get_name()
  58  p obj.get_age()
  59  obj.set_age(10)
  60  p obj.get_age()