SWIG:Examples:perl5:variables

`SWIG/Examples/perl5/variables/`

## Wrapping C Global Variables

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 Perl 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 Perl

Accessing a C global variable from Perl is easy---just reference it like a normal Perl variable. Click here to see a script that updates and prints some global variables.

## 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.

## Notes:

- 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 Perl, 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 Perl 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.
- Variables are linked using Perl's magic mechanism. Take a look at the Advanced Perl Programming book to find out more about this feature.