Rubyの拡張ライブラリー入門シリーズ② (クラスの作成と定義と継承: rb_define_class, メソッドの定義: rb_define_method)
クラスを作る
// hoge.c #include <stdio.h> #include <ruby.h> VALUE cHoge; static VALUE hoge_func(VALUE obj){ puts("Hello, world"); return Qtrue; } void Init_hoge(void){ cHoge = rb_define_class("Hoge", rb_cObject); rb_define_method(cHoge, "func", hoge_func, 0); }
extconf.rb & make
extconfの作成
# extconf.rb require 'mkmf' create_makefile "hoge"
makefileの作成とmake
ruby extconf.rb make
少し説明
rb_define_class()
でクラスを定義しています。
Hoge
がクラスでObject
がスーパークラス。
irbで試してみると分かりますが、Hoge.superclass #=> Object
となります。
rb_define_method()
ではメソッドとクラスの紐づけをしています。
rb_define_method(クラスを示すVALUE, メソッド名, 紐付ける関数, 引数の数)
irbで試してみると次のようになります。
Hoge.new.methods - Object.new.methods #=> [:func]
static VALUE hoge_func(VALUE obj)
の部分は、Hoge#func
の中身です。
Qtrue
は最後にtrue
を返すという意味です。
h = Hoge.new h.func # Hello, world! #=> true