【外部ページへのリンク】 https://docs.ruby-lang.org/ja/latest/library/mkmf.html
クラス名 | メソッド名 | 関数名 |
Foo | init | init |
Foo | x | x |
Foo | y | y |
例えば、次のように foo.c を作成
#include<stdio.h> #include<ruby.h> #include "foo.h" static double _x = 0.0; static double _y = 0.0; void Init_Foo(void) { VALUE k; k = rb_define_class("Foo", rb_cObject); rb_define_method(k, "init", init, /* num of params */ 2); rb_define_method(k, "x", x, /* num of params */ 0); rb_define_method(k, "y", y, /* num of params */ 0); } VALUE init(VALUE self, VALUE val_x, VALUE val_y) { _x = NUM2DBL(val_x); _y = NUM2DBL(val_y); return Qnil; } VALUE x(VALUE self) { return rb_float_new(_x); } VALUE y(VALUE self) { return rb_float_new(_y); }
例えば、次のように foo.h を作成
extern VALUE init(VALUE self, VALUE x, VALUE y); extern VALUE x(VALUE d); extern VALUE y(VALUE self);
gcc -I/usr/lib/ruby/1.8/x86_64-linux -fPIC -c -o foo.o foo.c ar -r libfoo.a foo.o
require 'mkmf' dir_config('Foo') if have_header('foo.h') create_makefile('Foo') end
ruby extconf.rb make sudo make install
require 'Foo' a = Foo.new a.init(100, 200) a.x a.y