Segmentation error when calling a Ruby function using C api

I am trying to call a simple ruby ​​function using the Ruby C API. When I compiled the output, I get a segmentation error, I'm not sure what the problem is, I hope you can help me, thanks.

C Code (./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; } 

Ruby Code (./func.rb)

 def func(opts) puts opts['key'] end 

Compile flags

 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 

Segmentation error at startup. / 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) 
+5
source share
1 answer

There seems to be no canonical examples of how to embed ruby ​​(at least in the official documentation). The best I can find is a free pickaxe chapter that says what you need

 ruby_sysinit(&argc, &argv); RUBY_INIT_STACK; ruby_init(); ruby_init_loadpath(); 

Setting the ruby ​​interpreter. You are missing some of them, in particular, given that your failure occurs inside require , the missing ruby_init_loadpath seems suspicious.

In this thread (in which Dave Thomas asks about changes in ruby ​​embedding) Nobu also says that you need to

 RUBY_GLOBAL_SETUP 

in front of the main one.

You may also be interested in mruby, which was designed to be easy to implement.

0
source

Source: https://habr.com/ru/post/1246341/


All Articles