Created
November 9, 2012 03:06
-
-
Save aphistic/4043455 to your computer and use it in GitHub Desktop.
mruby playing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SomeClass | |
def do_stuff | |
print "This is SomeClass.do_stuff\n" | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What is we want to define the function in mruby and call it from C?