Calling ruby function from C

I use ruby version 1.8.7.

I’ve got the ruby function in the file test.rb:

def work1(arr_name)
puts “foo1”
for name in arr_name
@i = @i+1
puts @i
puts name
end # for
end # def

I want to call it from C-code:

#include <ruby.h>

main{
ruby_init();
ruby_script(“test.rb”);
rb_load_file(“test.rb”);

VALUE query_list;
query_list = rb_ary_new();
rb_ary_push(query_list, rb_str_new2(“DVD”));
rb_ary_push(query_list, rb_str_new2(“CDPlayer1”));
rb_ary_push(query_list, rb_str_new2(“CDPlayer2”));

rb_funcall(0,rb_intern(“work1”),1,query_list);
ruby_exec();
}

When I run it I face the problem:
“undefined method ‘work1’ for false:FalseClass
Segmentation fault”

When I did like this

extern VALUE ruby_top_self;
main{

rb_funcall(rb_top_self,rb_intern(“work1”),1,query_list);
ruby_exec();
}
I’ve got another error:
“undefined method ‘work1’ for main:Object
Segmentation fault”

How to pass parameters to a ruby function from C-code?

I found the solution, but it still doesn’t work properly.

I use “rb_require” instead of “rb_load_file”:
extern VALUE ruby_top_self;
main{

rb_require(myFileName);
rb_funcall(ruby_top_self,rb_intern(“work1”),1,query_list);
ruby_exec();
}

There are 3 files: test1.rb, test2.rb, test3.rb, which have the function
“work1” in them:

def work1(arr_name)
puts “test1”
end

def work1(arr_name)
puts “test2”
end

def work1(arr_name)
puts “test3”
end

I run the program and choose:
test1.rb -> test1
test2.rb -> test2
test3.rb -> test3
test1.rb -> test3
test2.rb -> test3

Why doesn’t “rb_require” reload rb-file?

Subject: Re: Calling ruby function from C
Date: mar 18 mar 14 01:33:12 +0100

Quoting Evgenij M. ([email protected]):

Why doesn’t “rb_require” reload rb-file?

If you do not restart the virtual machine, it remembers which files
have already been required. Thus, if the same file is required in
various parts of your code, it is only parsed once.

Carlo

Sergey Avseyev wrote in post #1140276:

You can use ‘load’ if you need to evaluate file each time
I tried.
If you looked at my first post at this thread you would see it doesn’t
work.
I’ve got a segmentation fault.

On Tue, 18 Mar 2014 13:33:12 +0100
Evgenij M. [email protected] wrote:

Why doesn’t “rb_require” reload rb-file?

You can use ‘load’ if you need to evaluate file each time

I found a solution
https://groups.google.com/forum/#!topic/comp.lang.ruby/MrPJCLOzlgQ

Firstly, I called rb_load_file(“test.rb”);
Secondly, I called ruby_exec();
Finally, I defined variables and called
rb_funcall(0,rb_intern(“work1”),1,query_list);

Now it works well ^__^.

I think it might be a bug. Because the correct order is to put
“ruby_exec();” at the end.