すごくメモ帳

すごくほぼメモ帳ぐらいなブログ

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

参考サイト

https://docs.ruby-lang.org/en/2.7.0/extension_ja_rdoc.html