Ruby解释器嵌入在C代码中 [英] Ruby interpreter embed in C code
问题描述
我只是尝试一本书中的一个简单示例:
我有一个sum.rb文件:
I just try a simple example from a book: I have a sum.rb file:
class Summer
def sum(max)
raise "Invalid maximum #{max}" if max < 0
(max*max + max)/2
end
end
和embed_sum.c文件:
And a embed_sum.c file:
#include <stdio.h>
#include <ruby/ruby.h>
int main ( int argc, char ** argv)
{
VALUE result;
ruby_sysinit(&argc, &argv);
RUBY_INIT_STACK;
ruby_init();
ruby_init_loadpath();
rb_require("sum");
rb_eval_string("$summer = Summer.new");
rb_eval_string("$result = $summer.sum(10)");
result = rb_gv_get("result");
printf("Result = %d\n", NUM2INT(result));
return ruby_cleanup(0);
}
我将其编译为:
gcc -Wall -lruby -I/usr/include/ruby-1.9.1/ embed_sum.c -o embed_sum
当我启动./embed_sum时,它给我第一个rb_eval_string的分段错误。
我的ruby版本是:Archlinux上的ruby 1.9.3p125(2012-02-16修订版34643)[x86_64-linux]。
When I launch ./embed_sum it gives me a segmentation fault from the first rb_eval_string. my version of ruby is : ruby 1.9.3p125 (2012-02-16 revision 34643) [x86_64-linux] on Archlinux.
此示例可能是什么问题?
What can be the problem with this example?
推荐答案
您问题的简短答案是将 rb_require( sum);
行更改为 rb_require( ./ sum);
。这是Ruby 1.9.2中引入的更改,当前目录不再位于加载路径上。
The short answer to your problem is to change the line rb_require("sum");
to rb_require("./sum");
. This is the change introduced in Ruby 1.9.2 where the current directory is no longer on the load path.
更普遍的问题是嵌入式Ruby处理异常的方式。镐(我认为这是您正在使用的书,它使用类似的示例)的意思是:
The more general problem is the way embedded Ruby deals with exceptions. The Pickaxe book (which I think is the book you're using, it uses a similar example) has this to say:
Ruby代码引发异常,但未捕获该异常,您的C程序将终止。为了克服这个问题,您需要执行解释器的工作并保护所有可能引发异常的调用。
If the Ruby code raises an exception and it isn't caught, your C program will terminate. To overcome this, you need to do what the interpreter does and protect all calls that could raise an exception. This can get messy.
您需要研究使用 rb_protect
函数包装可能导致异常的对Ruby的调用。镐书中有一个例子。
You'll need to look into using the rb_protect
function to wrap calls to Ruby that might cause an exception. The Pickaxe book has an example of this.
这篇关于Ruby解释器嵌入在C代码中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!