crubyapiobjectspacefuncall

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


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 :


Solution

  • 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).