Skip to content

Instantly share code, notes, and snippets.

@jonforums
Created June 3, 2012 23:17
Show Gist options
  • Save jonforums/2865384 to your computer and use it in GitHub Desktop.
Save jonforums/2865384 to your computer and use it in GitHub Desktop.
embedded mruby Hello World
/* Copyright (c) 2012 Jon Maken
* License: 3-clause BSD
* Revision: 2012-06-04 14:35:54 -0600
*
* typical Clang/MinGW build recipe:
* set CPATH=C:/devlibs/mruby/include
* set LIBRARY_PATH=C:/devlibs/mruby/lib
*
* clang -Wall -O3 -march=native -o mruby_hello.exe mruby_hello.c -lmruby
*
* typical WinSDK 7.1 cmd line build recipe:
* set INCLUDE=C:\devlibs\mruby-vc1600\include;%INCLUDE%
* set LIB=C:\devlibs\mruby-vc1600\lib;%LIB%
*
* cl /Wall /O2 /Femruby_hello.exe /MD mruby_hello.c mruby.lib
*/
#include <stdlib.h>
#include "mruby.h"
#include "mruby/compile.h"
#include "mruby/class.h"
#include "mruby/proc.h"
// Foo module implementation
static mrb_value
mrb_foo_now(mrb_state *mrb, mrb_value self)
{
puts("Wake up, the foo is now...");
return mrb_nil_value();
}
static void
mrb_init_foo(mrb_state *mrb)
{
struct RClass *fc;
fc = mrb_define_module(mrb, "Foo");
mrb_define_class_method(mrb, fc, "now", mrb_foo_now, ARGS_NONE());
}
// TODO discover why mruby doesn't have a similar utility fcn
// that makes client code nicer.
static int
mrb_run_string(mrb_state *mrb, char *str)
{
int n = 0;
//struct mrb_parser_state *p;
//p = mrb_parse_string(mrb, str);
//n = mrb_generate_code(mrb, p->tree);
n = mrb_compile_string(mrb, str);
mrb_run(mrb, mrb_proc_new(mrb, mrb->irep[n]), mrb_top_self(mrb));
return mrb->exc ? 0 : 1;
}
int
main(int argc, char *argv[])
{
int rv = EXIT_SUCCESS;
char *rb_code = "require 'foo'\n"
"\n"
"10.times do |i|\n"
" puts %Q{[#{i}] Hello mruby!}\n"
"end"
"\n"
"# and now for something completely useless\n"
"Foo.now\n"
"\n"
"module Foo\n"
" class Bar\n"
" def say_baz; puts %Q{#{self.class} says baz...}; end\n"
" end\n"
"end\n"
"\n"
"Foo::Bar.new.say_baz\n";
// get an mruby VM instance
mrb_state *mrb = mrb_open();
if (mrb == NULL) return EXIT_FAILURE;
// register Foo module with the mruby VM instance
mrb_init_foo(mrb);
// persuade the mruby VM to run the ruby source code string
if (!mrb_run_string(mrb, rb_code)) {
mrb_p(mrb, mrb_obj_value(mrb->exc));
rv = EXIT_FAILURE;
}
mrb_close(mrb);
return rv;
}
/* vim: set ts=2 sw=2 sts=2 et: */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment