How to call ObjectSpace.each_object with C API without rb_string_eval?

91 Views Asked by At

I'm currently trying to get all the instances of a class and I wanted to use ObjectSpace.each_object to achieve that.

Here is my actual code in C :

ruby_init();
int ruby_state = 0;
rb_string_eval_protect("def my_func ; ObjectSpace.each_object(Klass) { |x| x.do_something } ; end", &ruby_state);
ruby_cleanup(ruby_state);

However, I don't know if it's really a good thing to do. I wanted to use rb_funcall instead, which is maybe a cleaner way to do it.

My questions are :

  • Is it better to use rb_funcall than string_eval? (I think so because of parser)
  • How can I retrieve the ObjectSpace module in C API since rb_mObjectSpace doesn't seem to exist?
1

There are 1 best solutions below

0
On BEST ANSWER

I found how to do that. It's using rb_const_get.

Here is the code now:

VALUE rb_mObjSpace = rb_const_get(rb_cObject, rb_intern("ObjectSpace"));

The module was already defined in gc.c but was not public. The only way to access to the module seems to be via rb_const_get (or to modify gc.c and build ruby, but no one wants to do that).