Saturday 15 May 2010

c++ - Embed Ruby in C and exntend -



c++ - Embed Ruby in C and exntend -

i have requirement need embed ruby code in c++ (i accomplish this) , extend functionality. when seek phone call (require) extension module, programme fails.

i have pasted jist of code below:

main.cpp #include <ruby.h> static value sum(value rb_self, value rb_param1, value rb_param2) { double val1 = num2dbl(rb_param1); double val2 = num2dbl(rb_param2); homecoming rb_float_new(val1+val2); } void init_mymod() { mymod = rb_define_module("mymod"); rb_define_module_function(mymod, "sum", sum, 2); } int main() { ... init ruby method... rb_require("myrubyfile"); init_mymod(); // need force ruby extension. rb_funcall(rb_mkernel, rb_intern("helloworld"), 0 , null); .... } myrubyfile.rb require "mymod" def helloworld() puts "hello world" #puts "sum of.. " + mymod.sum(4, 5) end

the problem if dont utilize require "mymod" code works , prints "hello world", if utilize require.., code dumps.

this requirement need embed ruby script in c, , reuse of c methods in ruby (extension).

can help me this?

you're getting segfault because ruby vm segfaults when there uncaught exception. need utilize rb_rescue or rb_protect wrap code raise exception.

require "mymod" raising exception because require used load files. don't need require because you're creating module straight in vm's memory. so... why error? well, if write module in ruby, you'd syntax error:

module mymod ... end # syntaxerror: class/module name must constant

but when utilize rb_define_module, rather raise exception, ruby tricky thing: creates module but doesn't expose ruby code. in order expose module ruby, create name valid:

// .cpp rb_define_module("mymod");

and

# .rb puts "sum of.. " + mymod.sum(4, 5).to_s

c++ c ruby embed

No comments:

Post a Comment