Hello everyone,
I was trying to embed Ruby (3.1.3) into a C++ app using the Ruby C-API.
To get started I tested how to load a Ruby script from a file using the rb_load function like the following
main.cpp:
#include <iostream>
#include <ruby.h>
using namespace std;
int main(int argc, char *argv[])
{
ruby_init();
VALUE s = rb_str_new_cstr("./test.rb");
rb_load(s, 0);
ruby_finalize();
return 0;
}
test.rb (in the same directory as main.cpp):
puts "test"
It compiles runs and executes successfully. Then I tried the same with the rb_load_file_str and ruby_exec_node function
main.cpp (just the main function, everything else is the same):
int main(int argc, char *argv[])
{
ruby_init();
VALUE s = rb_str_new_cstr("./test.rb");
void *n = rb_load_file_str(s);
int status;
cout << ruby_executable_node(n, &status) << endl;
cout << ruby_exec_node(n) << endl;
ruby_finalize();
return 0;
}
I thought that this should do the same (load the Ruby script from the test.rb file, check if its valid using the ruby_executable_node function, build the AST and execute it in the ruby_exec_node function).
For some reason I get the following output:
1
6
How I understood it is that the 1 is the return value for the ruby_executable_node and means that the script is valid Ruby. But what is the 6? I tried to find it in the Ruby source code but for some reason there is no mention of it (or I haven’t found it).
I also tried the ruby_run_node function instead of the ruby_exec_node function:
int main(int argc, char *argv[])
{
ruby_init();
VALUE s = rb_str_new_cstr("./test.rb");
void *n = rb_load_file_str(s);
int status;
cout << ruby_executable_node(n, &status) << endl;
cout << ruby_run_node(n) << endl;
ruby_finalize();
return 0;
}
This ends in a Segmentation fault:
1
Segmentation fault (core dumped)
Can someone explain me what is happening here or if i missed something?
Glad for any answers
If needed I can give more details
Thanks in advance