Reputation: 30445
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!
Upvotes: 3
Views: 340
Reputation: 84114
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).
Upvotes: 5