Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Ruby Programming
Previous Page Home Next Page

Directly Sharing Variables

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 Programmer .] 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.

VALUE hardware_list;
hardware_list = rb_ary_new();
rb_define_variable("$hardware", &hardware_list);
...
rb_ary_push(hardware_list, rb_str_new2("DVD"));
rb_ary_push(hardware_list, rb_str_new2("CDPlayer1"));
rb_ary_push(hardware_list, rb_str_new2("CDPlayer2"));

The Ruby side can then access the C variable hardware_list as $hardware:

$hardware ["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 variable without exporting it to Ruby, you must at least tell the garbage collector about it, lest ye be reaped inadvertently:

VALUE obj;
obj = rb_ary_new();
rb_global_variable(obj);
Ruby Programming
Previous Page Home Next Page

 
 
  Published under the terms of the Open Publication License Design by Interspire