Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

mruby proc call example

View example.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
class Bar
def initialize(name)
@name = name
@x = 0
@y = 0
end
 
def name
@name
end
 
def x
@x
end
 
def y
@y
end
 
def move_bar
@x += 10
@y += 10
end
def execute_with(b)
b.call(@x, @y)
end
end
View example.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
#include "mruby.h"
#include "mruby/proc.h"
#include "mruby/array.h"
#include "mruby/string.h"
#include "mruby/compile.h"
#include "mruby/dump.h"
#include <stdio.h>
#include <string.h>
 
static mrb_value bar_execute_with(mrb_state *mrb, mrb_value obj)
{
fprintf(stderr, "Inside execute_with block\n");
mrb_value x, y;
mrb_get_args(mrb, "oo", &x, &y);
fprintf(stderr, "Values: x=%d, y=%d\n", x.value.i, y.value.i);
mrb_value count_value;
count_value.tt = MRB_TT_FIXNUM;
count_value.value.i = x.value.i + y.value.i;
 
// If raise gets called here no segfault
// mrb_raise(mrb, E_TYPE_ERROR, "Testing...");
 
return mrb_Integer(mrb, count_value);
}
 
int main(int argc, char **argv)
{
FILE *fp = fopen("example.mrb", "rb");
 
mrb_state *mrb = mrb_open();
int n = mrb_load_irep(mrb, fp);
 
mrb_run(mrb, mrb_proc_new(mrb, mrb->irep[n]), mrb_top_self(mrb));
 
mrb_value args[1];
args[0] = mrb_str_new2(mrb, "Bar1");
mrb_value barInstance = mrb_class_new_instance(mrb, 1, args, mrb_class_get(mrb, "Bar"));
 
mrb_value bar_name = mrb_funcall_argv(mrb, barInstance, mrb_intern(mrb, "name"), 0, NULL);
mrb_value bar_x = mrb_funcall_argv(mrb, barInstance, mrb_intern(mrb, "x"), 0, NULL);
mrb_value bar_y = mrb_funcall_argv(mrb, barInstance, mrb_intern(mrb, "y"), 0, NULL);
fprintf(stderr, "Bar update location before => %s, %d, %d\n", mrb_str_ptr(bar_name)->ptr, bar_x.value.i, bar_x.value.i);
mrb_funcall_argv(mrb, barInstance, mrb_intern(mrb, "move_bar"), 0, NULL);
bar_x = mrb_funcall_argv(mrb, barInstance, mrb_intern(mrb, "x"), 0, NULL);
bar_y = mrb_funcall_argv(mrb, barInstance, mrb_intern(mrb, "y"), 0, NULL);
fprintf(stderr, "Bar update location after => %s, %d, %d\n", mrb_str_ptr(bar_name)->ptr, bar_x.value.i, bar_x.value.i);
 
struct RProc *b = mrb_proc_new_cfunc(mrb, bar_execute_with);
mrb_value proc = mrb_obj_value(b);
mrb_value ewret = mrb_funcall_argv(mrb, barInstance, mrb_intern(mrb, "execute_with"), 1, &proc);
fprintf(stderr, "Output: %d\n", ewret.value.i);
 
fclose(fp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.