SWIG Library Reference Version 1.1p4 January, 1998 Copyright (C) 1996-1998 Dave Beazley (This file was automatically generated by SWIG) 1. Introduction ================= This file describes all of the functions in the generic SWIG library. The SWIG library is a collection of generally useful functions that can be used to supplement an interface file. These include functions to manipulate arrays, functions from the C library, and interesting modules. This document is automatically generated by SWIG from the file "swig_lib/autodoc.i". Some modules may supply additional documentation for a particular target language. To recreate the documentation for a particular target language, simply run SWIG on the file 'autodoc.i' with the appropriate target language option. This document has been generated for Tcl. 1.1. Call for contributions ---------------------------- My long-term goal is for the SWIG library to be a collection of useful modules that can be used to quickly put together interesting programs. To contribute new modules send e-mail to beazley@cs.utah.edu and I will include them here. 2. Constraint Library ====================== %include constraints.i This library provides support for applying constraints to function arguments. Using a constraint, you can restrict arguments to be positive numbers, non-NULL pointers, and so on. The following constraints are available : Number POSITIVE - Positive number (not zero) Number NEGATIVE - Negative number (not zero) Number NONZERO - Nonzero number Number NONNEGATIVE - Positive number (including zero) Number NONPOSITIVE - Negative number (including zero) Pointer NONNULL - Non-NULL pointer Pointer ALIGN8 - 8-byte aligned pointer Pointer ALIGN4 - 4-byte aligned pointer Pointer ALIGN2 - 2-byte aligned pointer To use the constraints, you need to "apply" them to specific function arguments in your code. This is done using the %apply directive. For example : %apply Number NONNEGATIVE { double nonneg }; double sqrt(double nonneg); // Name of argument must match %apply Pointer NONNULL { void *ptr }; void *malloc(int POSITIVE); // May return a NULL pointer void free(void *ptr); // May not accept a NULL pointer Any function argument of the type you specify with the %apply directive will be checked with the appropriate constraint. Multiple types may be specified as follows : %apply Pointer NONNULL { void *, Vector *, List *, double *}; In this case, all of the types listed would be checked for non-NULL pointers. The common datatypes of int, short, long, unsigned int, unsigned long, unsigned short, unsigned char, signed char, float, and double can be checked without using the %apply directive by simply using the constraint name as the parameter name. For example : double sqrt(double NONNEGATIVE); double log(double POSITIVE); If you have used typedef to change type-names, you can also do this : %apply double { Real }; // Make everything defined for doubles // work for Reals. Real sqrt(Real NONNEGATIVE); Real log(Real POSITIVE); 3. Exception Handling Library ============================== %include exception.i This library provides language independent support for raising scripting language exceptions in SWIG generated wrapper code. Normally, this is used in conjunction with the %except directive. To raise an exception, use the following function call : SWIG_exception(int exctype, char *msg); 'exctype' is an exception type code and may be one of the following : SWIG_MemoryError SWIG_IOError SWIG_RuntimeError SWIG_IndexError SWIG_TypeError SWIG_DivisionByZero SWIG_OverflowError SWIG_SyntaxError SWIG_ValueError SWIG_SystemError SWIG_UnknownError 'msg' is an error string that should be reported to the user. The library is normally used in conjunction with the %except directive as follows : %except { try { $function } catch RangeError { SWIG_exception(SWIG_IndexError,"Array index out of bounds"); } catch(...) { SWIG_exception(SWIG_UnknownError,"Uncaught exception"); } } It is important to note that the SWIG_exception() function is only available to the C code generated by SWIG. It is not available in the scripting language interface itself. 4. Memory Allocation Module ============================ %include malloc.i This module provides access to a few basic C memory management functions. All functions return void pointers, but realloc() and free() will operate on any sort of pointer. Sizes should be specified in bytes. calloc nobj size [ returns void * ] Returns a pointer to a space for an array of nobj objects, each with size bytes. Returns NULL if the request can't be satisfied. Initializes the space to zero bytes. malloc size [ returns void * ] Returns a pointer to space for an object of size bytes. Returns NULL upon failure. realloc ptr size [ returns void * ] Changes the size of the object pointed to by ptr to size bytes. The contents will be unchanged up the minimum of the old and new sizes. Returns a pointer to the new space of NULL upon failure, in which case *ptr is unchanged. free ptr [ returns void ] Deallocates the space pointed to by ptr. Does nothing if ptr is NULL. ptr must be a space previously allocated by calloc, malloc, or realloc. 5. Memory Manipulation Module ============================== %include memory.i This module provides support for a few memory operations from the C library. These functions can be used to manipulate binary data. s and t are of type void *, cs and ct are both of type const void *. memcpy s ct n [ returns void * ] Copy n characters from ct to s, and return s memmove s ct n [ returns void * ] Same as memcpy except that it works even if the objects overlap. memcmp cs ct n [ returns int ] Compare the first n characters of cs with ct. Returns 0 if they are equal, <0 if cs < ct, and >0 if cs > ct. memchr cs c n [ returns void * ] Returns pointer to the first occurrence of character c in cs. memset s c n [ returns void * ] Place character c into first n characters of s, return s 6. Pointer Handling Library ============================ %include pointer.i The pointer.i library provides run-time support for managing and manipulating a variety of C/C++ pointer values. In particular, you can create various kinds of objects and dereference common pointer types. This is done through a common set of functions: ptrcast - Casts a pointer to a new type ptrvalue - Dereferences a pointer ptrset - Set the value of an object referenced by a pointer. ptrcreate - Create a new object and return a pointer. ptrfree - Free the memory allocated by ptrcreate. ptradd - Increment/decrement a pointer value. ptrmap - Make two datatypes equivalent to each other. (Is a runtime equivalent of typedef). When creating, dereferencing, or setting the value of pointer variable, only the common C datatypes of int, short, long, float, double, char, and char * are currently supported. Other datatypes may generate an error. One of the more interesting aspects of this library is that it operates with a wide range of datatypes. For example, the "ptrvalue" function can dereference "double *", "int *", "long *", "char *", and other datatypes. Since SWIG encodes pointers with type information, this can be done transparently and in most cases, you can dereference a pointer without ever knowing what type it actually is. This library is primarily designed for utility, not high performance (the dynamic determination of pointer types takes more work than most normal wrapper functions). As a result, you may achieve better performance by writing customized "helper" functions if you're making lots of calls to these functions in inner loops or other intensive operations. ptrcast ptr type Casts a pointer ptr to a new datatype given by the string type. type may be either the SWIG generated representation of a datatype or the C representation. For example : ptrcast $ptr double_p # Tcl representation ptrcast $ptr "double *" # C representation A new pointer value is returned. ptr may also be an integer value in which case the value will be used to set the pointer value. For example : set a [ptrcast 0 Vector_p] Will create a NULL pointer of type "Vector_p" The casting operation is sensitive to formatting. As a result, "double *" is different than "double*". As a result of thumb, there should always be exactly one space between the C datatype and any pointer specifiers (*). ptrvalue ptr ?index? ?type? Returns the value that a pointer is pointing to (ie. dereferencing). The type is automatically inferred by the pointer type--thus, an integer pointer will return an integer, a double will return a double, and so on. The index and type fields are optional parameters. When an index is specified, this function returns the value of ptr[index]. This allows array access. When a type is specified, it overrides the given pointer type. Examples : ptrvalue $a # Returns the value *a ptrvalue $a 10 # Returns the value a[10] ptrvalue $a 10 double # Returns a[10] assuming a is a double * ptrset ptr value ?index? ?type? Sets the value pointed to by a pointer. The type is automatically inferred from the pointer type so this function will work for integers, floats, doubles, etc... The index and type fields are optional. When an index is given, it provides array access. When type is specified, it overrides the given pointer type. Examples : ptrset $a 3 # Sets the value *a = 3 ptrset $a 3 10 # Sets a[10] = 3 ptrset $a 3 10 int # Sets a[10] = 3 assuming a is a int * ptrcreate type ?value? ?nitems? Creates a new object and returns a pointer to it. This function can be used to create various kinds of objects for use in C functions. type specifies the basic C datatype to create and value is an optional parameter that can be used to set the initial value of the object. nitems is an optional parameter that can be used to create an array. This function results in a memory allocation using malloc(). Examples : set a [ptrcreate "double"] # Create a new double, return pointer set a [ptrcreate int 7] # Create an integer, set value to 7 set a [ptrcreate int 0 1000] # Create an integer array with initial # values all set to zero This function only recognizes a few common C datatypes as listed below : int, short, long, float, double, char, char *, void All other datatypes will result in an error. However, other datatypes can be created by using the ptrcast function. For example: set a [ptrcast [ptrcreate int 0 100],"unsigned int *"] ptrfree ptr Destroys the memory pointed to by ptr. This function calls free() and should only be used with objects created by ptrcreate(). Since this function calls free, it may work with other objects, but this is generally discouraged unless you absolutely know what you're doing. ptradd ptr offset Adds a value to the current pointer value. For the C datatypes of int, short, long, float, double, and char, the offset value is the number of objects and works in exactly the same manner as in C. For example, the following code steps through the elements of an array set a [ptrcreate double 0 100] # Create an array double a[100] set b $a for {set i 0} {$i < 100} {incr i 1} { ptrset $b [expr{0.0025*$i}] # set *b = 0.0025*i set b [ptradd $b 1] # b++ (go to next double) } In this case, adding one to b goes to the next double. For all other datatypes (including all complex datatypes), the offset corresponds to bytes. This function does not perform any bounds checking and negative offsets are perfectly legal. ptrmap type1 type2 This is a rarely used function that performs essentially the same operation as a C typedef. To manage datatypes at run-time, SWIG modules manage an internal symbol table of type mappings. This table keeps track of which types are equivalent to each other. The ptrmap() function provides a mechanism for scripts to add symbols to this table. For example : ptrmap double_p Real_p would make the types "double_p" and "Real_p" equivalent to each other. Pointers of either type could now be used interchangably. Normally this function is not needed, but it can be used to circumvent SWIG's normal type-checking behavior or to work around weird type-handling bugs. 7. SWIG C Array Module ======================= %include array.i This module provides scripting language access to various kinds of C/C++ arrays. For each datatype, a collection of four functions are created : _array(size) : Create a new array of given size _get(array, index) : Get an element from the array _set(array, index, value) : Set an element in the array _destroy(array) : Destroy an array The functions in this library are only low-level accessor functions designed to directly access C arrays. Like C, no bounds checking is performed so use at your own peril. 7.1. Integer Arrays -------------------- The following functions provide access to integer arrays (mapped onto the C 'int' datatype. int_array nitems [ returns int * ] Creates a new array of integers. nitems specifies the number of elements. The array is created using malloc() in C and new() in C++. int_destroy array [ returns void ] Destroys the given array. int_get array index [ returns int ] Returns the value of array[index]. int_set array index value [ returns int ] Sets array[index] = value. Returns value. 7.2. Floating Point Arrays --------------------------- The following functions provide access to arrays of floats and doubles. double_array nitems [ returns double * ] Creates a new array of doubles. nitems specifies the number of elements. The array is created using malloc() in C and new() in C++. double_destroy array [ returns void ] Destroys the given array. double_get array index [ returns double ] Returns the value of array[index]. double_set array index value [ returns double ] Sets array[index] = value. Returns value. float_array nitems [ returns float * ] Creates a new array of floats. nitems specifies the number of elements. The array is created using malloc() in C and new() in C++. float_destroy array [ returns void ] Destroys the given array. float_get array index [ returns float ] Returns the value of array[index]. float_set array index value [ returns float ] Sets array[index] = value. Returns value. 7.3. String Arrays ------------------- The following functions provide support for the 'char **' datatype. This is primarily used to handle argument lists and other similar structures that need to be passed to a C/C++ function. To convert from a Tcl list into a 'char **', the following code can be used : # $list is a list set args [string_array expr {[llength $list] + 1}] set i 0 foreach a $list { string_set $args $i $a incr i 1 } string_set $i "" # $args is now a char ** type string_array nitems [ returns char ** ] Creates a new array of strings. nitems specifies the number of elements. The array is created using malloc() in C and new() in C++. Each element of the array is set to NULL upon initialization. string_destroy array [ returns void ] Destroys the given array. Each element of the array is assumed to be a NULL-terminated string allocated with malloc() or new(). All of these strings will be destroyed as well. (It is probably only safe to use this function on an array created by string_array) string_get array index [ returns char * ] Returns the value of array[index]. Returns a string of zero length if the corresponding element is NULL. string_set array index value [ returns char * ] Sets array[index] = value. value is assumed to be a NULL-terminated string. A string of zero length is mapped into a NULL value. When setting the value, the value will be copied into a new string allocated with malloc() or new(). Any previous value in the array will be destroyed. 8. SWIG Math Module ==================== %include math.i This module provides access to the C math library and contains most of the functions in . Most scripting languages already provide math support, but in certain cases, this module can provide more direct access. 8.1. Functions --------------- cos x [ returns double ] Cosine of x sin x [ returns double ] Sine of x tan x [ returns double ] Tangent of x acos x [ returns double ] Inverse cosine in range [-PI/2,PI/2], x in [-1,1]. asin x [ returns double ] Inverse sine in range [0,PI], x in [-1,1]. atan x [ returns double ] Inverse tangent in range [-PI/2,PI/2]. atan2 y x [ returns double ] Inverse tangent of y/x in range [-PI,PI]. cosh x [ returns double ] Hyperbolic cosine of x sinh x [ returns double ] Hyperbolic sine of x tanh x [ returns double ] Hyperbolic tangent of x exp x [ returns double ] Natural exponential function e^x log x [ returns double ] Natural logarithm ln(x), x > 0 log10 x [ returns double ] Base 10 logarithm, x > 0 pow x y [ returns double ] Power function x^y. sqrt x [ returns double ] Square root. x >= 0 fabs x [ returns double ] Absolute value of x ceil x [ returns double ] Smallest integer not less than x, as a double floor x [ returns double ] Largest integer not greater than x, as a double fmod x y [ returns double ] Floating-point remainder of x/y, with the same sign as x. 8.2. Mathematical constants ---------------------------- $M_E = 2.7182818284590452354 $M_LOG2E = 1.4426950408889634074 $M_LOG10E = 0.43429448190325182765 $M_LN2 = 0.69314718055994530942 $M_LN10 = 2.30258509299404568402 $M_PI = 3.14159265358979323846 $M_PI_2 = 1.57079632679489661923 $M_PI_4 = 0.78539816339744830962 $M_1_PI = 0.31830988618379067154 $M_2_PI = 0.63661977236758134308 $M_2_SQRTPI = 1.12837916709551257390 $M_SQRT2 = 1.41421356237309504880 $M_SQRT1_2 = 0.70710678118654752440 9. Tcl Library Files ===================== The following library modules are available when using the Tcl language module. 9.1. Hash Constants -------------------- %include consthash.i This module changes SWIG so that constant values are placed into a Tcl hash table in addition to normal Tcl variables. When working with systems involving large numbers of constants, the use of a hash table simplifies use because it is no longer necessary to declare constants using the 'global' statement. This module should generally be included at the top of an interface file before any declarations appear. Furthermore, this module changes the default handling of basic datatypes including integers, floats, and character strings. When this module is used, constants are simply accessed by name without the associated dollar sign. For example : #define FOO 42 would be accessed as 'FOO' in Tcl, not '$FOO'. Note : This module only affects integer, float, and character constants. Pointer constants are not currently affected. This module should not break existing Tcl scripts that rely on the normal SWIG constant mechanism. 9.2. Array Constants --------------------- %include constarray.i This module changes SWIG so that constant values are placed into a Tcl array instead of global variables. The array is given the same name as the SWIG module (specified with the %module directive). This module should generally be included at the top of an interface file before any declarations appear. Furthermore, this module changes the default handling of basic datatypes including integers, floats, and character strings. When this module is used, constants are simply accessed through the module name. For example : %module example ... #define FOO 42 would be accessed as '$example(FOO)' Note : This module replaces the existing mechanism for creating constants. The method used by this module is based on a set of typemaps supplied by Tim Medley. 9.3. tclsh.i ------------- This module provides the Tcl_AppInit() function needed to build a new version of the tclsh executable. This file should not be used when using dynamic loading. To make an interface file work with both static and dynamic loading, put something like this in your interface file : #ifdef STATIC %include tclsh.i #endif 9.4. wish.i ------------ This module provides the Tk_AppInit() function needed to build a new version of the wish executable. Like tclsh.i, this file should not be used with dynamic loading. To make an interface file work with both static and dynamic loading, put something like this in your interface file : #ifdef STATIC %include wish.i #endif A startup file may be specified by defining the symbol SWIG_RcFileName as follows (this should be included in a code-block) : #define SWIG_RcFileName "~/.mywishrc" 9.5. expect.i -------------- This module provides a main() function for building an extended version of Expect. It has been tested with Expect 5.19, but may need modification for newer versions. 9.6. expectk.i --------------- This module provides a main() function for building an extended version of expectk. It has been tested with Expect 5.19, but may need modification for newer versions. 9.7. blt.i ----------- This module initializes the BLT package. This is usually done in combination with the wish.i or similar module. For example : %include wish.i // Build a new wish executable %include blt.i // Initialize BLT 9.8. tix.i ----------- This module initializes the Tix extension. This is usually done in combination with the wish.i or similar module. For example : %include wish.i // Build a new wish executable %include tix.i // Initialize Tix 9.9. ish.i ----------- This module provides a main() program needed to build a new version of the [incr Tcl] 'ish' executable. It has been tested with itcl 2.1, but may need tweaking for later versions and for use with C++. 9.10. itclsh.i --------------- This module provides a main() program needed to build a new version of the [incr Tcl] 'itclsh' executable. It has been tested with itcl 2.1, but may need tweaking for later versions and for use with C++. 9.11. iwish.i -------------- This module provides a main() program needed to build a new version of the [incr Tcl] 'iwish' executable. It has been tested with itcl 2.1, but may need tweaking for later versions and for use with C++. 9.12. itkwish.i ---------------- This module provides a main() program needed to build a new version of the [incr Tcl] 'itkwish' executable. It has been tested with itcl 2.1, but may need tweaking for later versions and for use with C++. 10. Timer Functions ==================== %include timers.i This module provides a collection of timing functions designed for performance analysis and benchmarking of different code fragments. A total of 64 different timers are available. Each timer can be managed independently using four functions : timer_clear(int n) Clears timer n timer_start(int n) Start timer n timer_stop(int n) Stop timer n timer_elapsed(int n) Return elapsed time (in seconds) All timers measure CPU time. Since each timer can be accessed independently, it is possible to use groups of timers for measuring different aspects of code performance. To use a timer, simply use code like this : timer_clear 0 timer_start 0 .. a bunch of Tcl code ... timer_stop 0 puts "[timer_elapsed 0] seconds of CPU time" A single timer can be stopped and started repeatedly to provide a cummulative timing effect. As a general performance note, making frequent calls to the timing functions can severely degrade performance (due to operating system overhead). The resolution of the timers may be poor for extremely short code fragments. Therefore, the timers work best for computationally intensive operations. timer_clear n [ returns void ] Clears timer n. timer_start n [ returns void ] Starts timer n. timer_stop n [ returns void ] Stops timer n. timer_elapsed n [ returns double ] Return the elapsed time (in seconds) of timer n 11. Typemap Library (Tcl) ========================== %include typemaps.i The SWIG typemap library provides a language independent mechanism for supporting output arguments, input values, and other C function calling mechanisms. The primary use of the library is to provide a better interface to certain C function--especially those involving pointers. 11.1. Input Methods -------------------- The following methods can be applied to turn a pointer into a simple "input" value. That is, instead of passing a pointer to an object, you would use a real value instead. int *INPUT short *INPUT long *INPUT unsigned int *INPUT unsigned short *INPUT unsigned long *INPUT unsigned char *INPUT float *INPUT double *INPUT To use these, suppose you had a C function like this : double fadd(double *a, double *b) { return *a+*b; } You could wrap it with SWIG as follows : %include typemaps.i double fadd(double *INPUT, double *INPUT); or you can use the %apply directive : %include typemaps.i %apply double *INPUT { double *a, double *b }; double fadd(double *a, double *b); 11.2. Output Methods --------------------- The following methods can be applied to turn a pointer into an "output" value. When calling a function, no input value would be given for a parameter, but an output value would be returned. In the case of multiple output values, they are returned in the form of a Tcl list. int *OUTPUT short *OUTPUT long *OUTPUT unsigned int *OUTPUT unsigned short *OUTPUT unsigned long *OUTPUT unsigned char *OUTPUT float *OUTPUT double *OUTPUT For example, suppose you were trying to wrap the modf() function in the C math library which splits x into integral and fractional parts (and returns the integer part in one of its parameters).K: double modf(double x, double *ip); You could wrap it with SWIG as follows : %include typemaps.i double modf(double x, double *OUTPUT); or you can use the %apply directive : %include typemaps.i %apply double *OUTPUT { double *ip }; double modf(double x, double *ip); The Tcl output of the function would be a list containing both output values. 11.3. Input/Output Methods --------------------------- The following methods can be applied to make a function parameter both an input and output value. This combines the behavior of both the "INPUT" and "OUTPUT" methods described earlier. Output values are returned in the form of a Tcl list. int *BOTH short *BOTH long *BOTH unsigned int *BOTH unsigned short *BOTH unsigned long *BOTH unsigned char *BOTH float *BOTH double *BOTH For example, suppose you were trying to wrap the following function : void neg(double *x) { *x = -(*x); } You could wrap it with SWIG as follows : %include typemaps.i void neg(double *BOTH); or you can use the %apply directive : %include typemaps.i %apply double *BOTH { double *x }; void neg(double *x); Unlike C, this mapping does not directly modify the input value (since this makes no sense in Tcl). Rather, the modified input value shows up as the return value of the function. Thus, to apply this function to a Tcl variable you might do this : set x [neg $x] 11.4. Special Methods ---------------------- The typemaps.i library also provides the following mappings : Tcl_Interp *interp Passes the current Tcl_Interp value directly to a C function. This can be used to work with existing wrapper functions or if you just need the interp value for some reason. When used, the 'interp' parameter becomes hidden in the Tcl interface--that is, you don't specify it explicitly. SWIG fills in its value automatically. int Tcl_Result Makes the integer return code of a function the return value of a SWIG generated wrapper function. For example : int foo() { ... do stuff ... return TCL_OK; } could be wrapped as follows : %include typemaps.i %apply int Tcl_Result { int foo }; int foo();