3

In the README.EXT documentation (which comes with the Ruby platform source), it mentions rb_define_variable, which takes a C pointer to VALUE and "connects" it to a Ruby global variable, so reading/writing the variable from Ruby-land will access the given location in memory.

But I need something a little different: from C-land, I want to access global variables which were defined and initialized from within Ruby. I don't need to list all the global variables which are defined -- I just want to access the value of a global variable given its name, and I want to do it from the C side.

If all else fails, I know I can use rb_eval_string (which is the same as eval in Ruby), but there should be a better way!

1 Answer 1

5

The method you want is rb_gv_get (itself a wrapper around some of the global variable stuff). With rubyinline you could write

require 'inline'
class Foo
  inline :C  do |builder|
    builder.c_raw_singleton <<SRC
      VALUE read_global(VALUE self, VALUE *name){
        return rb_gv_get(rb_string_value_cstr(name));
      }
SRC
  end
end

and then

$bar = 1
Foo.read_global('bar') #=> 1

(rubyinline doesn't work in irb).

Sign up to request clarification or add additional context in comments.

1 Comment

Nice! Thanks! I tried grepping for "global" and "variable" but didn't find anything...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.