Reading the "return" value of mruby program through C

I am having a problem calling mruby VM in C. I can call mruby vm and execute ruby ​​code from C. I could also run methods defined in ruby ​​code. But I ran into a problem while trying to read the return value of a ruby ​​method. Below is a sample script below.

CODE:

#include <stdlib.h>
#include <stdio.h>

#include <mruby.h>
#include <mruby/compile.h>

int main(void)
{
  mrb_state *mrb = mrb_open();
  char code[] = "def helloworld() return'OK' end";
  printf("Executing Ruby code from C!\n");

  mrb_load_string(mrb, code);
  mrb_load_string(mrb, "helloworld()");
  // How to read the return value?
  return 0;
}

      

I'm not sure if this is the correct way to call ruby ​​methods? I couldn't find any documentation or examples on the internet. Anyone who tried to call ruby ​​code via c (using mruby) can you help me?

Hello,

+3


source to share


1 answer


The return value mrb_load_string()

is the value of the last expression evaluated. But this is also a mrb_undef_value()

crash that happened during parsing or code generation, like a syntax error. In general, the member is exc

mrb_state

not null if an uncaught exception exists:

mrb_value rv = mrb_load_string(mrb, "helloworld()");
if (mrb->exc) {            // if uncaught exception …
   if (!mrb_undef_p(rv)) { // … during execution/run-time
     mrb_print_error(mrb); // write backtrace and other details to stderr
   }
}
else {
  mrb_p(mrb, rv); // similar to Kernel#p
}

      

If you only want to call a method, you can use the family of functions mrb_funcall()

:

mrb_value rv = mrb_funcall(mrb, mrb_top_self(mrb), "helloworld", 0);

      



Or:

mrb_value rv = mrb_funcall_argv(mrb, mrb_top_self(mrb), mrb_intern_cstr(mrb, "helloworld"), 0, NULL);

      

Then the parser and code generator will not be used, so it will be faster and, if not used elsewhere, the executable or (shared) library will be much smaller. Plus is mrb_undef_value()

not a possible return value, otherwise checking for an uncaught exception and getting the return value can be done in a similar way.

+2


source







All Articles