軽量Rubyのコンパイラ・オプション

軽量Rubyコンパイラのオプション-Bの正体を追っかけました。

mrubyのソースコードを読んでみたところ、このオプションはどうやらmrubyプログラムのインタープリタ内部表現を、バイナリ文字列としてC言語の配列で表し出力するようです。大雑把に言うと*.mrbをC言語の文字列配列に変換したモノのだと言えます。

さて、このバイナリをどうやって利用するかと言うと、次のようなコード(C言語)で利用すれば良さそうです。

#include "mruby.h"
#include "irep.h"
#include "mruby/string.h"
#include "mruby/proc.h"
#include "dump.h"

/* mbrc -Bhello hello.rb の出力 */
const char hello[] = {
0x52,0x49,0x54,0x45,0x30,0x30,0x30,0x39,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x39,
0x30,0x30,0x30,0x30,0x4d,0x41,0x54,0x5a,0x20,0x20,0x20,0x20,0x30,0x30,0x30,0x39,
0x30,0x30,0x30,0x30,0x00,0x00,0x00,0x83,0x00,0x01,0x00,0x00,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0xb3,0xd8,0x00,0x00,0x00,0x45,0x53,0x43,0x00,0x02,0x00,0x04,
0x00,0x02,0x6f,0x28,0x00,0x00,0x00,0x05,0x01,0x00,0x00,0x06,0x01,0x80,0x00,0x3d,
0x02,0x00,0x00,0x05,0x01,0x00,0x00,0xa0,0x00,0x00,0x00,0x4a,0xf5,0x07,0x00,0x00,
0x00,0x01,0x0f,0x00,0x0c,0x68,0x65,0x6c,0x6c,0x6f,0x20,0x77,0x6f,0x72,0x6c,0x64,
0x21,0x2b,0xac,0x00,0x00,0x00,0x01,0x00,0x04,0x70,0x75,0x74,0x73,0x24,0x89,0x00,
0x00,0x00,0x00,
};
/* ここまで */

int
main(int argc, char **argv)
{
  mrb_state *mrb = mrb_open();
  int n = -1;

  n = mrb_read_irep(mrb, (char*)hello);
  if (n >= 0) {
    mrb_run(mrb, mrb_proc_new(mrb, mrb->irep[n]), mrb_nil_value());
  }

  return n;
}