为什么这段代码不适用于ruby 1.9但适用于ruby 1.8?

时间:2011-07-05 16:04:00

标签: c ruby

我从ruby website(1.9.2-p180)下载了持续稳定的ruby源代码,并在Windows上使用MinGW 4.5.2-TDM和MSYS进行了编译。为了编译,我运行了sh configuremake。我完全按预期获得了 msvcrt-ruby191.dll libmsvcrt-ruby191.dll.a 。然后我写了这段代码:

#include <ruby.h>
int main() {
  ruby_init();
  rb_funcall2(Qnil, rb_intern("p"), 1, (VALUE[]){INT2FIX(0)});
  ruby_finalize();
}

我用g++编译,链接到ruby的dll。当我运行可执行文件时,我收到此错误消息:

<main>: [BUG] Segmentation fault
ruby 1.9.2p180 (2011-02-18 revision 30909) [i386-mingw32]

-- control frame ----------
c:0002 p:---- s:0004 b:0004 l:000003 d:000003 CFUNC  :p
c:0001 p:0000 s:0002 b:0002 l:00120c d:00120c TOP
---------------------------
-- Ruby level backtrace information ----------------------------------------
ruby:0:in `p'

[NOTE]
You may have encountered a bug in the Ruby interpreter or extension libraries.
Bug reports are welcome.
For details: http://www.ruby-lang.org/bugreport.html


This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

问题是:当与ruby 1.8.7链接时,相同的代码可以正常工作。这有什么不对?

1 个答案:

答案 0 :(得分:6)

请尝试将您的init扩展到:

int main(int argc,char *argv[]) {
  ruby_sysinit(&argc, &argv);
  {
    RUBY_INIT_STACK;
    ruby_init();
    ruby_init_loadpath();
    // ... code
    ruby_finalize();
  }
  return 0; //from main()
}

初始化过程在1.8和1.9版本之间进行了更改,因此现在需要在块中添加单独的嵌套块{ .. }RUBY_INIT_STACK宏。