Created
October 22, 2011 02:00
-
-
Save jefftrull/1305431 to your computer and use it in GitHub Desktop.
Example of embedding Ruby interpreter into C/C++ program
This file contains 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
// very basic embedded Ruby interpreter for C++ programs | |
// thrown together by Jeff Trull <[email protected]> based on googling and asking questions on #ruby-lang | |
#include <ruby.h> | |
// access to C variables | |
static VALUE getter(VALUE ns, VALUE var) { | |
return Qfalse; | |
} | |
VALUE setter(VALUE ns, VALUE var, VALUE val) { | |
return Qfalse; | |
} | |
RUBY_GLOBAL_SETUP | |
int main(int argc, char **argv) { | |
ruby_sysinit(&argc, &argv); | |
RUBY_INIT_STACK; | |
ruby_init(); | |
// provide interactive prompt with irb (the Ruby shell) by telling ruby to execute it on startup | |
// copy arg array and add this option at the end | |
char** new_argv = (char**)malloc((argc + 2) * sizeof(char*)); | |
for (int i = 0; i < argc; i++) { | |
new_argv[i] = argv[i]; | |
} | |
new_argv[argc] = "-e"; | |
new_argv[argc+1] = "require \"irb\"; IRB.start"; | |
// create some modules | |
VALUE mymod = rb_define_module("MOD"); | |
rb_define_module_function(mymod, "setparam", setter, 3); | |
rb_define_module_function(mymod, "getparam", getter, 2); | |
return ruby_run_node(ruby_options(argc+2, new_argv)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You have to reininterpret-cast the argument you use:
rb_define_module_function(mymod, "setparam", reininterpret_cast< VALUE ( * ) ( ... ) >(setter), 3);
I do not say anything wrong, but so far as i know it's a C to C++ problem.