Google

SWIG/Examples/tcl/variables/

Wrapping C Global Variables

$Header: /cvs/projects/SWIG/Examples/tcl/variables/index.html,v 1.2.4.1 2002/04/08 03:55:16 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 Tcl variable that works exactly like you would expect in a Tcl script, but which magically retrieves or updates the value of the underlying C variable. Click here to see a SWIG interface with some variable declarations in it.

Manipulating Variables from Tcl

Click here to see a script that updates and prints out the values of the variables defined in the above file. Notice how the C global variables work just like normal Tcl variables.

Key points

  • The set statement changes the value of the corresponding C global variable.
  • Whenever you access the value of a variable such as $ivar, the value of the C global variable is read.
  • If a C program changes a global variable independently of Tcl, this change is automatically reflected in the Tcl variable (i.e., reads will always return the most up to date value of the variable).
  • 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 Tcl, 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 Tcl 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 scripting interface and resulting memory management is much trickier than simply creating a wrapper function.

  • You may be better off hiding global variables behind a function based interface.