Skip to content

Instantly share code, notes, and snippets.

@kjunichi
Last active December 5, 2022 14:29
Show Gist options
  • Save kjunichi/089a062f3dc432e8daa1 to your computer and use it in GitHub Desktop.
Save kjunichi/089a062f3dc432e8daa1 to your computer and use it in GitHub Desktop.
mrubyでC言語でブロックを扱うには

C言語側でブロックを定義するには

関数をmrubyのブロックとして扱える。

mrb_value myfunc(mrb_state *mrb, mrb_value obj) {
  printf("myfunc: start\n");
  
  printf("myfunc: end\n");

  return mrb_nil_value(); // プログラムに応じて返す
}

C言語側からブロックを引数に取るメソッドを呼び出すには

blk = mrb_proc_new_cfunc(mrb, myfunc);
proc = mrb_obj_value(blk);
val = mrb_funcall_with_block(mrb, mrb_top_self(mrb), mrb_intern_cstr(mrb, "mymethod"), 0, NULL, proc);
// mrb_funcall(mrb,mrb_top_self(mrb),"p",1,proc);
def mymethod(&blk)
  p "Hello, this is mymethod."
  yield
end

ブロックを受け取るには

mrb_value block;

mrb_get_args(mrb, "&", &block);

与えられたブロックを実行するには

mrb_value block;
mrb_value val;
mrb_yield(mrb, block, val);

Link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment