Although you could maintain a C version of some variable along with a
separate Ruby version of that variable, and struggle to keep the two
in sync,[A clear violation of the DRY--Don't
Repeat Yourself---principle described in our book The Pragmatic
it would be much better to
share a variable directly between Ruby and C.
You can share global
variables by creating a Ruby object on the C side and then binding
its address to a Ruby global variable. In this case, the $ prefix is
optional, but it helps clarify that this is a global variable.
hardware_list = rb_ary_new();
The Ruby side can then access the C variable
["DVD", "CDPlayer1", "CDPlayer2"]
You can also create hooked
variables that will call a specified function when the variable is
accessed, and virtual
variables that only call the hooks---no
actual variable is involved. See the API section that begins
on page 189 for details.
If you create a Ruby object from C and store it in a C global
exporting it to Ruby, you must at least tell the
garbage collector about it, lest ye be reaped inadvertently:
obj = rb_ary_new();