`SWIG/Examples/java/variables/`

## Wrapping C Global Variables

`$Header$`

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 Java variable 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 Java

C variables are accessed through getters and setters from Java. Unfortunately this is the only way to get current values from variables because it is not possible to overload the dot operator in Java. All global variables are accessible from the module class. For example if the module class is called 'example', the global variable

>     double foo;

will be accessed in the Java module as

>     example.get_foo();
>     example.set_foo(12.3);

Click here to see the example program that updates and prints out the values of the variables using this technique.

## Key points

- When a global variable has the type "`char *`", SWIG manages it as a character string. However, whenever the value of such a variable is set from Java, the old value is destroyed using `free()` or `delete` (the choice of which depends on whether or not SWIG was run with the -c++ option).
- `signed char` and `unsigned char` are handled as small 8-bit integers.
- String array variables such as '`char name[256]`' are managed as Java 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. For example:

>     %immutable;
>     int    status;
>     double blah;
>     ...
>     %mutable;

The `%immutable` directive remains in effect until it is explicitly disabled using the `%mutable` directive.

## Comments

- Management of global variables is one of the most problematic aspects of C/C++ wrapping because the Java interface and resulting memory management is much trickier than simply creating a wrapper function.