mruby/c 組込みの素振り
mruby/c 組み込みの練習がてら、新規のプロジェクトから mruby/c のVMを呼び出してみる。手順は以下の通り。
my_mruby ディレクトリを作成、mrubycからコピーしてきたhalとsrcを配置する
VMを起動する src/main.c を用意する
ビルドが通るようにMakefileを修正
code:files
my_mrubyc/
├── hal
│ └── posix
│ ├── hal.c
│ └── hal.h
└── src
├── Makefile (既存のMakefileを修正)
├── main.c (ここからVMを起動)
...
└── (オリジナルのファイルをコピーしてくる)
src/main.c からVMを起動する。sample_c/sample_include.c をベースにちょっと修正したもの。
code:src/main.c
// mrbc -E -Bary sample_include_bytecode.rb
// while true
// puts "sample"
// sleep 1
// end
const uint8_t mrbbuf[] = {
0x52,0x49,0x54,0x45,0x30,0x33,0x30,0x30,0x00,0x00,0x00,0x6a,0x4d,0x41,0x54,0x5a,
0x30,0x30,0x30,0x30,0x49,0x52,0x45,0x50,0x00,0x00,0x00,0x4e,0x30,0x33,0x30,0x30,
0x00,0x00,0x00,0x42,0x00,0x01,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x15,
0x51,0x02,0x00,0x2d,0x01,0x00,0x01,0x07,0x02,0x2d,0x01,0x01,0x01,0x25,0xff,0xf0,
0x11,0x01,0x38,0x01,0x69,0x00,0x01,0x00,0x00,0x06,0x73,0x61,0x6d,0x70,0x6c,0x65,
0x00,0x00,0x02,0x00,0x04,0x70,0x75,0x74,0x73,0x00,0x00,0x05,0x73,0x6c,0x65,0x65,
0x70,0x00,0x45,0x4e,0x44,0x00,0x00,0x00,0x00,0x08,
};
#if !defined(MRBC_MEMORY_SIZE) int main(void)
{
mrbc_init(memory_pool, MRBC_MEMORY_SIZE);
if( mrbc_create_task(mrbbuf, 0) != NULL ){
mrbc_run();
}
return 0;
}
既存のMakefileをちょっと修正。
code:src/Makefile
include hal_selector.mk
LIBMRUBYC = $(BUILD_DIR)/libmrubyc.a
MRUBYC_BIN = $(BUILD_DIR)/my_mrubyc
TARGETS = $(MRUBYC_BIN) $(LIBMRUBYC)
CFLAGS += -Wall -g #-std=c99 -pedantic -pedantic-errors SRCS = alloc.c c_array.c c_hash.c c_math.c c_numeric.c \
c_object.c c_range.c c_string.c class.c console.c error.c global.c \
keyvalue.c load.c mrblib.c rrt0.c symbol.c value.c vm.c hal.c
OBJS = $(addprefix $(BUILD_DIR)/, $(SRCS:.c=.o))
BUILD_DIR = ../build
.PHONY: all
all: $(TARGETS)
$(LIBMRUBYC): $(OBJS)
$(AR) $(ARFLAGS) $@ $?
$(BUILD_DIR)/%.o: %.c
@-mkdir -p $(BUILD_DIR)
$(CC) -c $(CFLAGS) -o $@ $<
$(MRUBYC_BIN): main.c $(LIBMRUBYC)
$(CC) $(CFLAGS) -o $@ $< $(LIBMRUBYC)
.PHONY: clean
clean:
@rm -f $(TARGETS) $(OBJS) *~
# File dependencies.
$(BUILD_DIR)/hal.o: $(HAL_DIR)/hal.c $(HAL_DIR)/hal.h
$(CC) -c $(CFLAGS) -o $(BUILD_DIR)/hal.o $<
ビルドと実行手順
code:sh
$ cd my_mrubyc/src
$ make
$ ../build/my_mrubyc
sample
sample
sample
...
https://gyazo.com/b52c6587daaa7152f2073af91d0a4e7b