Wrapping C Global Variables$Header: /cvs/projects/SWIG/Examples/ruby/variables/index.html,v 188.8.131.52 2002/04/08 03:56:05 beazley Exp $
When a C global variable appears in an interface file, SWIG tries to wrap it using a technique known as "variable linking." The idea is pretty simple---we try to create a Ruby variable (actually module method) that magically retrieves or updates the value of the underlying C variable when it is accessed. Click here to see a SWIG interface with some variable declarations in it.
Manipulating Variables from RubyBefore going any further, it is important to understand some important differences between C and Ruby variables. In C, a variable is simply a name that refers to a specific location in memory. For example, when you declare a global variable 'double a' you know that somewhere in memory, 8 bytes have been set aside to hold a double and that a is bound to this location for the life of the program. In Ruby, variable creation is nothing more than a naming operation. For example, when you say 'a = 3', 'a' becomes a name that refers to some object '3'. Later on, if you say 'a = 7.5, the name 'a' is bound to an entirely different object containing the value '7.5' (the contents of the original object are not changed). The end result of this is that a variable in Ruby can refer to a virtually unlimited number of different objects (memory locations) over the lifetime of a program.
Because of Ruby's somewhat unusual variable assignment semantics, it is not possible to directly link a C global variable into an equivalent Ruby variable. Instead, all C global variables are accessed as attributes of the module. For example, if you had a global variable
it will be accessed in the Ruby module as Example.foo. Click here to see a script that updates and prints out the values of the variables using this technique.double foo;
Creating read-only variablesThe %immutable and %mutable directives can be used to specify a collection of read-only variables. For example:
The %immutable directive remains in effect until it is explicitly disabled using the %mutable directive.%immutable; int status; double blah; ... %mutable;