組み込みC言語プログラマのためのmruby入門(後編) ―― mrubyの組み込み方とJavaとの違い

邑中 雅樹

tag: 組み込み

技術解説 2012年12月14日

 mrbcに-Bオプションまたは-Cオプションのいずれかを付けるとC言語形式のバイトコードが得られます.C言語形式の場合,-oオプションを付けないと,ソース・コードの拡張子をcに替えたファイルが出力先となります.

 C言語配列形式のバイトコードを得るためには,-Bオプションを用います.

$mrbc -Bfoo mrbc_test.rb

とすると,mrbc_test.cが生成されます(リスト3).-Bオプションに与えたfooが,変数名として含まれています.

 

リスト3 C言語配列形式のバイトコード(mrbc_test.c,-Bオプションで出力)

const char foo[] = {
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,0x78,0x00,0x01,0x00,0x00,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x5b,0x94,0x00,0x00,0x00,0x3a,0x53,0x43,0x00,0x02,0x00,0x05,
0x00,0x02,0x7f,0x09,0x00,0x00,0x00,0x06,0x00,0xc0,0x00,0x03,0x01,0x00,0x00,0x06,
0x01,0x80,0x40,0x01,0x01,0x80,0x42,0xad,0x01,0x00,0x00,0xa0,0x00,0x00,0x00,0x4a,
0x82,0xe1,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x01,0x70,0x00,
0x01,0x2b,0x7a,0xc1,0x00,0x00,0x00,0x00,
};

 

 C言語の関数形式を得るためには,-Cオプションを用います.

$mrbc -Cbar mrbc_test.rb

とすると,mrbc_test.cが生成されます(リスト4).上記で-Cオプションに与えたbarが,関数名として含まれています.

 

リスト4 C言語関数形式のバイトコード(mrbc_test.c,-Cオプションで出力)

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

static mrb_code iseq_0[] = {
  0x00c00003,
  0x01000006,
  0x01804001,
  0x018042ad,
  0x010000a0,
  0x0000004a,
};

void
bar(mrb_state *mrb)
{
  int n = mrb->irep_len;
  int idx = n;
  int ai;
  mrb_irep *irep;
  
  mrb_add_irep(mrb, idx+1);
  
  ai = mrb->arena_idx;
  irep = mrb->irep[idx] = mrb_malloc(mrb, sizeof(mrb_irep));
  irep->flags = MRB_ISEQ_NO_FREE;
  irep->idx = idx++;
  irep->nlocals = 2;
  irep->nregs = 5;
  irep->ilen = 6;
  irep->iseq = iseq_0;
  irep->slen = 2;
  irep->syms = mrb_malloc(mrb, sizeof(mrb_sym)*2);
  irep->syms[0] = mrb_intern2(mrb, "p", 1);
  irep->syms[1] = mrb_intern2(mrb, "+", 1);
  irep->pool = NULL;
  mrb->irep_len = idx;
  irep->plen = 0;
  
  mrb_run(mrb, mrb_proc_new(mrb, mrb->irep[n]), mrb_top_self(mrb));
}
 

 

組み込みキャッチアップ

お知らせ 一覧を見る

電子書籍の最新刊! FPGAマガジン No.12『ARMコアFPGA×Linux初体験』好評発売中

FPGAマガジン No.11『性能UP! アルゴリズム×手仕上げHDL』好評発売中! PDF版もあります

PICK UP用語

EV(電気自動車)

関連記事

EnOcean

関連記事

Android

関連記事

ニュース 一覧を見る
Tech Villageブログ

渡辺のぼるのロボコン・プロモータ日記

2年ぶりのブログ更新w

2016年10月 9日

Hamana Project

Hamana-8最終打ち上げ報告(その2)

2012年6月26日