我正在编写一个从 c 调用 ruby 代码的应用程序。我遇到了一点困难,想知道是否有人可以指出我的仪式方向。
我目前在我的 C 中。
#include ruby.h
main()
{
ruby_init();
rb_require("myRubyFile");
rb_funcall(rb_module_new(), rb_intern("RubyFunction"), 0, NULL);
}
我的 ruby 文件与我的 c 文件位于同一目录中,名为 myRubyFile.rb 并包含函数 RubyFunction() 的定义。
这是我真正想做的事情的缩减,只是为了让其他人更容易阅读。我只需要一些关于这是否是从我的 c 文件调用 ruby 代码的正确方法的反馈。
问候
最佳答案
简答:
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);
更长的答案:
rb_funcall
的第一个参数是方法调用的接收者。
假设您在任何显式类或模块上下文之外def
ined RubyFunction()
,然后它被添加到隐式的特征类,主对象位于每个 ruby 虚拟机的“顶层”。
在 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
在 1.9 下的 C 中,它可以如上所示访问。
关于c - 嵌入 Ruby,从 C 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2801346/