SWIG Library Reference

  
Version 1.1p4
January, 1998

Copyright (C) 1996-1998
Dave Beazley

(This file was automatically generated by SWIG)
  

Contents


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

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
<string.h> 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");   # Python 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 :

   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 :

  a = ptrcreate("double")     # Create a new double, return pointer
  a = ptrcreate("int",7)      # Create an integer, set value to 7
  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:

 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

 a = ptrcreate("double",0,100);    # Create an array double a[100]
 b = a;
 for i in range(0,100):
     ptrset(b,0.0025*i);           # set *b = 0.0025*i
     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 "doublePtr" and "RealPtr" 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 problems.

7. Python Library Files


The following modules are available when using the Python language
module.

7.1. embed.i


This module provides support for building a new version of the
Python executable.  This will be necessary on systems that do
not support shared libraries and may be necessary with C++
extensions.  This file contains everything you need to build
a new version of Python from include files and libraries normally
installed with the Python language.

This module will automatically grab all of the Python modules
present in your current Python executable (including any special
purpose modules you have enabled such as Tkinter).   Thus, you
may need to provide additional link libraries when compiling.

This library file only works with Python 1.5.  A version 
compatible with Python 1.4 is available as embed14.i and
a Python1.3 version is available as embed13.i.    As far as
I know, this module is C++ safe.

7.2. embed.i


This module provides support for building a new version of the
Python executable.  This will be necessary on systems that do
not support shared libraries and may be necessary with C++
extensions.  This file contains everything you need to build
a new version of Python from include files and libraries normally
installed with the Python language.

This module will automatically grab all of the Python modules
present in your current Python executable (including any special
purpose modules you have enabled such as tkinter).   Thus, you
may need to provide additional link libraries when compiling.

This library file only works with Python 1.4.  A version compatible
with Python 1.3 is available as embed13.i.  A Python 1.5 version is
available as embed15.i As far as I know, this module is C++ safe
(well, it works for me).

7.3. embed13.i


This module provides support for building a new version of the
Python 1.3 executable.  This will be necessary on systems that do
not support shared libraries and may be necessary with C++
extensions.  This file contains everything you need to build
a new version of Python from include files and libraries normally
installed with the Python language.

This module is functionally equivalent to the embed.i library,
but has a number of changes needed to work with older versions
of Python.

8. 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 :

   <type>_array(size)              : Create a new array of given size
   <type>_get(array, index)        : Get an element from the array
   <type>_set(array, index, value) : Set an element in the array
   <type>_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.

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

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

8.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 Python list to a 'char **', code similar to the following
can be used :

    # 'list' is a list
    args = string_array(len(list)+1)
    for i in range(0,len(list)):
	string_set(args,i,list[i])
    string_set(args,len(list),"")

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.   

9. SWIG Math Module


%include math.i

This module provides access to the C math library and contains most
of the functions in <math.h>.  Most scripting languages already provide
math support, but in certain cases, this module can provide more
direct access.

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

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


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 Python code ...
      timer_stop(0)
      print 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 (Python)


%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 Python tuple.

         int            *OUTPUT
         short          *OUTPUT
         long           *OUTPUT
         unsigned int   *OUTPUT
         unsigned short *OUTPUT
         unsigned long  *OUTPUT
         unsigned char  *OUTPUT
         float          *OUTPUT
         double         *OUTPUT
         
A Python List can also be returned by using L_OUTPUT instead of 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 Python output of the function would be a tuple 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 Python tuple.  To return a Python list,
using L_INOUT instead.

         int            *INOUT
         short          *INOUT
         long           *INOUT
         unsigned int   *INOUT
         unsigned short *INOUT
         unsigned long  *INOUT
         unsigned char  *INOUT
         float          *INOUT
         double         *INOUT
         
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 *INOUT);

or you can use the %apply directive :

        %include typemaps.i
        %apply double *INOUT { double *x };
        void neg(double *x);

Unlike C, this mapping does not directly modify the input value (since
this makes no sense in Python).  Rather, the modified input value shows
up as the return value of the function.  Thus, to apply this function
to a Python variable you might do this :

       x = neg(x)

Note : previous versions of SWIG used the symbol 'BOTH' to mark
input/output arguments.   This is still supported, but will be slowly
phased out in future releases.

11.4. Special Methods


The typemaps.i library also provides the following mappings :

PyObject *

      When a PyObject * appears as either an input value or return
      value of a function, SWIG passes it through unmodified.  Thus,
      if you want to write a C function that operates on PyObjects,
      it is easy to write.  For example :

           %include typemaps.i
           PyObject *spam(PyObject *obj1, int n);

      Unlike normal Python wrapper functions, These functions can
      use any combination of parameters that you wish.