使用C api调用Ruby函数时出现分段错误

Kik*_*api 5 c ruby segmentation-fault

我正在尝试使用Ruby C API调用简单的ruby函数,当执行编译输出时我得到分段错误,我不确定是什么问题,我希望你能帮助我,谢谢.

C代码(./func.c)

#include <ruby.h>
int main(){
 VALUE obj;
 VALUE result;
 VALUE map;
 ruby_init();
 rb_require("./func.rb");
 obj=rb_str_new_cstr("");
 map = rb_hash_new();
 rb_hash_aset(map, rb_str_new2("key"),rb_str_new2("val"));

 result = rb_funcall(obj, rb_intern("func"), 1, map);
 return 0;
}
Run Code Online (Sandbox Code Playgroud)

Ruby代码(./func.rb)

def func(opts)
    puts opts['key']
end
Run Code Online (Sandbox Code Playgroud)

编译标志

gcc func.c -o func -I/home/wh/.rbenv/versions/2.1.6/include/ruby-2.1.0/x86_64-linux -I/home/wh/.rbenv/versions/2.1.6/include/ruby-2.1.0 -L/home/wh/.rbenv/versions/2.1.6/lib/ -lruby-static -lm -pthread -lcrypt -ldl -rdynamic
Run Code Online (Sandbox Code Playgroud)

运行./func时出现分段错误

<main>: [BUG] Segmentation fault at 0x00000000000018
ruby 2.1.6p336 (2015-04-13 revision 50298) [x86_64-linux]

-- Control frame information -----------------------------------------------
c:0001 p:0000 s:0002 E:002468 TOP    [FINISH]


-- C level backtrace information -------------------------------------------
./func() [0x581bcc] vm_dump.c:690
./func() [0x5f4893] error.c:312
./func(rb_bug+0xb3) [0x5f5a73] error.c:339
./func() [0x4f6c83] signal.c:824
/lib/x86_64-linux-gnu/libpthread.so.0(+0x10340) [0x7f805628d340] ../nptl/sysdeps/pthread/funlockfile.c:29
./func() [0x416f03] eval_intern.h:157
./func(rb_require_safe+0x63c) [0x42038c] load.c:1017
./func(main+0x18) [0x418b05]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf5) [0x7f8055ed9ec5] libc-start.c:287
./func() [0x418a23] enumerator.c:181

-- Other runtime information -----------------------------------------------

Segmentation fault (core dumped)
Run Code Online (Sandbox Code Playgroud)

Fre*_*ung 0

似乎缺乏如何嵌入 ruby​​ 的规范示例(至少在官方文档中)。我能找到的最好的东西是镐中的这个免费章节,它说你需要

ruby_sysinit(&argc, &argv);
RUBY_INIT_STACK;
ruby_init();
ruby_init_loadpath();
Run Code Online (Sandbox Code Playgroud)

设置 ruby​​ 解释器。你错过了其中的一些,特别是考虑到你的崩溃发生在里面require,失踪ruby_init_loadpath似乎很可疑。

此线程中(Dave Thomas 询问有关嵌入 ruby​​ 的更改)Nobu 还说您需要

RUBY_GLOBAL_SETUP
Run Code Online (Sandbox Code Playgroud)

在主要之前。

您可能还对 mruby 感兴趣,它被设计为易于嵌入。