嵌入Ruby,从C调用函数

Llo*_*ell 4 c ruby linux embedded-ruby

我正在编写一个从c调用ruby代码的应用程序.我有点困难,想知道是否有人能指出我的仪式方向.

我目前在我的C.

#include ruby.h

main()
{
  ruby_init();
  rb_require("myRubyFile");
  rb_funcall(rb_module_new(), rb_intern("RubyFunction"), 0, NULL);
}
Run Code Online (Sandbox Code Playgroud)

我的ruby文件与我的c文件位于同一目录中,名为myRubyFile.rb,包含函数RubyFunction()的定义.

这是我实际想要做的事情的减少,只是让其他人更具可读性.我只是需要一些反馈来判断这是否是从我的c文件中调用ruby代码的正确方法.

问候

pil*_*row 6

简短回答:

extern VALUE rb_vm_top_self(void); /* Assumes 1.9.  Under 1.8, use the global
                                    * VALUE ruby_top_self
                                    */
...
rb_funcall(rb_vm_top_self(),           /* irb> RubyFunction()                   */
           rb_intern("RubyFunction"),  /* irb> self.RubyFunction() # same thing */
           0,
           NULL);
Run Code Online (Sandbox Code Playgroud)

更长的回答:

第一个参数rb_funcall是方法调用的接收者.

假设你def独立非执行董事RubyFunction()的任何明确的类或模块上下文之外,那么它被添加到隐,的eigenclass 在每一个Ruby VM的的"顶级"的主要对象.

在ruby中,此对象可作为顶级访问self:

$ cat myRubyFile.rb
# file: myRubyFile.rb
def foo
  puts "foo"
end

$ irb
irb> require "myRubyFile"
=> true
irb> foo
foo
=> nil
irb> self.foo()    # same thing, more explicit
foo
=> nil
irb> self
=> main
Run Code Online (Sandbox Code Playgroud)

在C 1.9以下,如上所述可以访问.