Skip to content

Instantly share code, notes, and snippets.

@aphistic
Created November 9, 2012 03:06
Show Gist options
  • Save aphistic/4043455 to your computer and use it in GitHub Desktop.
Save aphistic/4043455 to your computer and use it in GitHub Desktop.
mruby playing
#include "mruby.h"
#include "mruby/proc.h"
#include "mruby/data.h"
#include "mruby/compile.h"
mrb_value class_func(mrb_state *mrb, mrb_value self)
{
// Ruby method params
char* strVal;
int strLen;
mrb_int intVal;
mrb_float floatVal;
// ---
int argc = mrb_get_args(mrb, "sif", &strVal, &strLen, &intVal, &floatVal);
printf("C Function Params (%i):\n", argc);
printf("1: %s (%i)\n", strVal, strLen);
printf("2: %i\n", intVal);
printf("3: %f\n", floatVal);
}
mrb_value add(mrb_state *mrb, mrb_value self)
{
mrb_int first, second;
int argc = mrb_get_args(mrb, "ii", &first, &second);
return mrb_fixnum_value(first + second);
}
int main(int argc, char** argv)
{
mrb_state *mrb = mrb_open();
// Define a ruby class
struct RClass *cclass = mrb_define_class(mrb, "CClass", mrb->object_class);
// aspec = 0 doesn't seem to be used in mrb_define_method_id (below)
mrb_define_method(mrb, cclass, "c_func", class_func, ARGS_REQ(3));
mrb_define_method(mrb, cclass, "add", add, ARGS_REQ(2));
FILE *file;
file = fopen("some_class.rb", "r");
mrb_load_file(mrb, file);
fclose(file);
file = fopen("test.rb", "r");
mrb_load_file(mrb, file);
fclose(file);
mrb_close(mrb);
}
class SomeClass
def do_stuff
print "This is SomeClass.do_stuff\n"
end
end
class Test
def foo
print "This is foo!\n"
end
end
t = Test.new
t.foo
sc = SomeClass.new
sc.do_stuff
cc = CClass.new
cc.c_func "string", 12, 43.21
print "Adding from c class: " + (cc.add(1, 1) + cc.add(2, 2)).to_s + "\n"
@mowrang
Copy link

mowrang commented Mar 11, 2015

What is we want to define the function in mruby and call it from C?

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