SWIG/Examples/go/variables/
Wrapping C Global Variables
When a C global variable appears in an interface file, SWIG provides
getter and setter functions for the variable. The getter function is
named Get followed by the capitalized name of the variable.
The setter variable starts with Set instead. The getter
function takes no parameters and returns the value of the variable.
The setter function takes a single parameter with the same type as the
variable, and returns nothing.
Click here to see a SWIG interface with
some variable declarations in it.
Manipulating Variables from Go
For example, if the package is called example, the global
variable
double foo;
will be accessed from Go as
example.GetFoo();
example.SetFoo(12.3);
Click here to see the example program that
updates and prints out the values of the variables using this
technique.
Key points
- The name of the variable is capitalized.
- When a global variable has the type "char *", SWIG
manages it as a character string.
- signed char and unsigned char are handled as
small 8-bit integers.
- String array variables such as 'char name[256]' are
managed as Go strings, but when setting the value, the result is
truncated to the maximum length of the array. Furthermore, the string
is assumed to be null-terminated.
- When structures and classes are used as global variables, they are
mapped into pointers. Getting the "value" returns a pointer to the
global variable. Setting the value of a structure results in a memory
copy from a pointer to the global.
Creating read-only variables
The %immutable and %mutable directives can be used
to specify a collection of read-only variables. A read only variable
will have a getter function but no setter function. For example:
%immutable;
int status;
double blah;
...
%mutable;
The %immutable directive remains in effect until it is
explicitly disabled using the %mutable directive.