This chapter discusses SWIG's support of Tcl. SWIG currently requires Tcl 8.0 or a later release. Earlier releases of SWIG supported Tcl 7.x, but this is no longer supported.
If building a C++ extension, add the -c++ option:$ swig -tcl example.i
$ swig -c++ -tcl example.i
This creates a file example_wrap.c or example_wrap.cxx that contains all of the code needed to build a Tcl extension module. To finish building the module, you need to compile this file and link it with the rest of your program.
Be aware that some Tcl versions install this header file with a version number attached to it. If this is the case, you should probably make a symbolic link so that tcl.h points to the correct header file./usr/local/include
The exact commands for doing this vary from platform to platform. SWIG tries to guess the right options when it is installed. Therefore, you may want to start with one of the examples in the SWIG/Examples/tcl directory. If that doesn't work, you will need to read the man-pages for your compiler and linker to get the right set of options. You might also check the SWIG Wiki for additional information.$ swig -tcl example.i $ gcc -c example.c $ gcc -c example_wrap.c -I/usr/local/include $ gcc -shared example.o example_wrap.o -o example.so
When linking the module, the name of the output file has to match the name of the module. If the name of your SWIG module is "example", the name of the corresponding object file should be "example.so". The name of the module is specified using the %module directive or the -module command line option.
The usual procedure for adding a new module to Tcl involves writing a special function Tcl_AppInit() and using it to initialize the interpreter and your module. With SWIG, the tclsh.i and wish.i library files can be used to rebuild the tclsh and wish interpreters respectively. For example:
The tclsh.i library file includes supporting code that contains everything needed to rebuild tclsh. To rebuild the interpreter, you simply do something like this:%module example extern int fact(int); extern int mod(int, int); extern double My_variable; %include tclsh.i // Include code for rebuilding tclsh
You will need to supply the same libraries that were used to build Tcl the first time. This may include system libraries such as -lsocket, -lnsl, and -lpthread. If this actually works, the new version of Tcl should be identical to the default version except that your extension module will be a built-in part of the interpreter.$ swig -tcl example.i $ gcc example.c example_wrap.c \ -Xlinker -export-dynamic \ -DHAVE_CONFIG_H -I/usr/local/include/ \ -L/usr/local/lib -ltcl -lm -ldl \ -o mytclsh
Comment: In practice, you should probably try to avoid static linking if possible. Some programmers may be inclined to use static linking in the interest of getting better performance. However, the performance gained by static linking tends to be rather minimal in most situations (and quite frankly not worth the extra hassle in the opinion of this author).
A common error received by first-time users is the following:$ tclsh % load ./example.so % fact 4 24 %
This error is almost always caused when the name of the shared object file doesn't match the name of the module supplied using the SWIG %module directive. Double-check the interface to make sure the module name and the shared object file match. Another possible cause of this error is forgetting to link the SWIG-generated wrapper code with the rest of your application when creating the extension module.% load ./example.so couldn't find procedure Example_Init %
Another common error is something similar to the following:
This error usually indicates that you forgot to include some object files or libraries in the linking of the shared library file. Make sure you compile both the SWIG wrapper file and your original program into a shared library file. Make sure you pass all of the required libraries to the linker.% load ./example.so couldn't load file "./example.so": ./example.so: undefined symbol: fact %
Sometimes unresolved symbols occur because a wrapper has been created for a function that doesn't actually exist in a library. This usually occurs when a header file includes a declaration for a function that was never actually implemented or it was removed from a library without updating the header file. To fix this, you can either edit the SWIG input file to remove the offending declaration or you can use the %ignore directive to ignore the declaration.
Finally, suppose that your extension module is linked with another library like this:
If the foo library is compiled as a shared library, you might get the following problem when you try to use your module:$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \ -o example.so
This error is generated because the dynamic linker can't locate the libfoo.so library. When shared libraries are loaded, the system normally only checks a few standard locations such as /usr/lib and /usr/local/lib. To fix this problem, there are several things you can do. First, you can recompile your extension module with extra path information. For example, on Linux you can do this:% load ./example.so couldn't load file "./example.so": libfoo.so: cannot open shared object file: No such file or directory %
Alternatively, you can set the LD_LIBRARY_PATH environment variable to include the directory with your shared libraries. If setting LD_LIBRARY_PATH, be aware that setting this variable can introduce a noticeable performance impact on all other applications that you run. To set it only for Tcl, you might want to do this instead:$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \ -Xlinker -rpath /home/beazley/projects/lib \ -o example.so
Finally, you can use a command such as ldconfig to add additional search paths to the default system configuration (this requires root access and you will need to read the man pages).$ env LD_LIBRARY_PATH=/home/beazley/projects/lib tclsh
On most machines, C++ extension modules should be linked using the C++ compiler. For example:
In addition to this, you may need to include additional library files to make it work. For example, if you are using the Sun C++ compiler on Solaris, you often need to add an extra library -lCrun like this:% swig -c++ -tcl example.i % g++ -c example.cxx % g++ -c example_wrap.cxx -I/usr/local/include % g++ -shared example.o example_wrap.o -o example.so
Of course, the extra libraries to use are completely non-portable---you will probably need to do some experimentation.% swig -c++ -tcl example.i % CC -c example.cxx % CC -c example_wrap.cxx -I/usr/local/include % CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o example.so -lCrun
Sometimes people have suggested that it is necessary to relink the Tcl interpreter using the C++ compiler to make C++ extension modules work. In the experience of this author, this has never actually appeared to be necessary. Relinking the interpreter with C++ really only includes the special run-time libraries described above---as long as you link your extension modules with these libraries, it should not be necessary to rebuild Tcl.
If you aren't entirely sure about the linking of a C++ extension, you might look at an existing C++ program. On many Unix machines, the ldd command will list library dependencies. This should give you some clues about what you might have to include when you link your extension module. For example:
$ ldd swig libstdc++-libc6.1-1.so.2 => /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000) libm.so.6 => /lib/libm.so.6 (0x4005b000) libc.so.6 => /lib/libc.so.6 (0x40077000) /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000) $
As a final complication, a major weakness of C++ is that it does not define any sort of standard for binary linking of libraries. This means that C++ code compiled by different compilers will not link together properly as libraries nor is the memory layout of classes and data structures implemented in any kind of portable manner. In a monolithic C++ program, this problem may be unnoticed. However, in Tcl, it is possible for different extension modules to be compiled with different C++ compilers. As long as these modules are self-contained, this probably won't matter. However, if these modules start sharing data, you will need to take steps to avoid segmentation faults and other erratic program behavior. If working with lots of software components, you might want to investigate using a more formal standard such as COM.
To utilize 64-bits, the Tcl executable will need to be recompiled as a 64-bit application. In addition, all libraries, wrapper code, and every other part of your application will need to be compiled for 64-bits. If you plan to use other third-party extension modules, they will also have to be recompiled as 64-bit extensions.
If you are wrapping commercial software for which you have no source code, you will be forced to use the same linking standard as used by that software. This may prevent the use of 64-bit extensions. It may also introduce problems on platforms that support more than one linking standard (e.g., -o32 and -n32 on Irix).
If you have a function "bar" in the SWIG file, the prefix option will append the prefix to the name when creating a command and call it "Foo_bar".swig -tcl -prefix Foo example.i
By default, the name of the namespace will be the same as the module name, but you can override it using the -prefix option.swig -tcl -namespace example.i
When the -namespace option is used, objects in the module are always accessed with the namespace name such as Foo::bar.
Now, assuming all went well, SWIG will be automatically invoked when you build your project. Any changes made to the interface file will result in SWIG being automatically invoked to produce a new version of the wrapper file. To run your new Tcl extension, simply run tclsh or wish and use the load command. For example :
MSDOS > tclsh80 % load example.dll % fact 4 24 %
To build the extension, run NMAKE (you may need to run vcvars32 first). This is a pretty minimal Makefile, but hopefully its enough to get you started. With a little practice, you'll be making lots of Tcl extensions.# Makefile for building various SWIG generated extensions SRCS = example.c IFILE = example INTERFACE = $(IFILE).i WRAPFILE = $(IFILE)_wrap.c # Location of the Visual C++ tools (32 bit assumed) TOOLS = c:\msdev TARGET = example.dll CC = $(TOOLS)\bin\cl.exe LINK = $(TOOLS)\bin\link.exe INCLUDE32 = -I$(TOOLS)\include MACHINE = IX86 # C Library needed to build a DLL DLLIBC = msvcrt.lib oldnames.lib # Windows libraries that are apparently needed WINLIB = kernel32.lib advapi32.lib user32.lib gdi32.lib comdlg32.lib winspool.lib # Libraries common to all DLLs LIBS = $(DLLIBC) $(WINLIB) # Linker options LOPT = -debug:full -debugtype:cv /NODEFAULTLIB /RELEASE /NOLOGO / MACHINE:$(MACHINE) -entry:_DllMainCRTStartup@12 -dll # C compiler flags CFLAGS = /Z7 /Od /c /nologo TCL_INCLUDES = -Id:\tcl8.0a2\generic -Id:\tcl8.0a2\win TCLLIB = d:\tcl8.0a2\win\tcl80.lib tcl:: ..\..\swig -tcl -o $(WRAPFILE) $(INTERFACE) $(CC) $(CFLAGS) $(TCL_INCLUDES) $(SRCS) $(WRAPFILE) set LIB=$(TOOLS)\lib $(LINK) $(LOPT) -out:example.dll $(LIBS) $(TCLLIB) example.obj example_wrap.obj
Will be used in Tcl like this :%module example int foo(int a); double bar (double, double b = 3.0); ...
There isn't much more to say...this is pretty straightforward.set a [foo 2] set b [bar 3.5 -1.5] set b [bar 3.5] # Note : default argument is used
Compatibility Note: Variable tracing is currently supported for all C/C++ datatypes. In older versions of SWIG, only variables of type int, double, and char * could be linked. All other types were accessed using special function calls.// example.i %module example ... double My_variable; ... # Tcl script puts $My_variable # Output value of C global variable set My_variable 5.5 # Change the value
is accessed as follows:%module example #define FOO 42
No attempt is made to enforce the read-only nature of a constant. Therefore, a user could reassign the value if they wanted. You will just have to be careful.% puts $FOO 42 %
A peculiarity of installing constants as variables is that it is necessary to use the Tcl global statement to access constants in procedure bodies. For example:
If a program relies on a lot of constants, this can be extremely annoying. To fix the problem, consider using the following typemap rule:proc blah {} { global FOO bar $FOO }
When applied to an input argument, the CONSTANT rule allows a constant to be passed to a function using its actual value or a symbolic identifier name. For example:%apply int CONSTANT { int x }; #define FOO 42 ... void bar(int x);
When an identifier name is given, it is used to perform an implicit hash-table lookup of the value during argument conversion. This allows the global statement to be ommitted.proc blah {} { bar FOO }
A NULL pointer is represented by the string "NULL". NULL pointers can also be explicitly created as follows :_100f8e2_p_Vector
As much as you might be inclined to modify a pointer value directly from Tcl, don't. The hexadecimal encoding is not necessarily the same as the logical memory address of the underlying object. Instead it is the raw byte encoding of the pointer value. The encoding will vary depending on the native byte-ordering of the platform (i.e., big-endian vs. little-endian). Similarly, don't try to manually cast a pointer to a new type by simply replacing the type-string. This is may not work like you expect and it is particularly dangerous when casting C++ objects. If you need to cast a pointer or change its value, consider writing some helper functions instead. For example:_0_p_Vector
If you need to type-cast a lot of objects, it may indicate a serious weakness in your design. Also, if working with C++, you should always try to use the new C++ style casts. For example, in the above code, the C-style cast may return a bogus result whereas as the C++-style cast will return NULL if the conversion can't be performed.%inline %{ /* C-style cast */ Bar *FooToBar(Foo *f) { return (Bar *) f; } /* C++-style cast */ Foo *BarToFoo(Bar *b) { return dynamic_cast<Foo*>(b); } Foo *IncrFoo(Foo *f, int i) { return f+i; } %}
gets mapped into the following collection of C functions :struct Vector { double x,y,z; };
These functions are then used in the resulting Tcl interface. For example :double Vector_x_get(Vector *obj) double Vector_x_set(Vector *obj, double x) double Vector_y_get(Vector *obj) double Vector_y_set(Vector *obj, double y) double Vector_z_get(Vector *obj) double Vector_z_set(Vector *obj, double z)
# v is a Vector that got created somehow % Vector_x_get $v 3.5 % Vector_x_set $v 7.8 # Change x component
Similar access is provided for unions and the data members of C++ classes.
class List { public: List(); ~List(); int search(char *item); void insert(char *item); void remove(char *item); char *get(int n); int length; static void print(List *l); };
When wrapped by SWIG, the following functions are created :
Within Tcl, we can use the functions as follows :List *new_List(); void delete_List(List *l); int List_search(List *l, char *item); void List_insert(List *l, char *item); void List_remove(List *l, char *item); char *List_get(List *l, int n); int List_length_get(List *l); int List_length_set(List *l, int n); void List_print(List *l);
C++ objects are really just pointers (which are represented as strings). Member functions and data are accessed by simply passing a pointer into a collection of accessor functions that take the pointer as the first argument.% set l [new_List] % List_insert $l Ale % List_insert $l Stout % List_insert $l Lager % List_print $l Lager Stout Ale % puts [List_length_get $l] 3 % puts $l _1008560_p_List %
While somewhat primitive, the low-level SWIG interface provides direct and flexible access to almost any C++ object. As it turns out, it is possible to do some rather amazing things with this interface as will be shown in some of the later examples. SWIG also generates an object-based interface that can be used in addition to the basic interface just described here.
Using the object oriented interface requires no additional modifications or recompilation of the SWIG module (the functions are just used differently).class List { public: List(); ~List(); int search(char *item); void insert(char *item); void remove(char *item); char *get(int n); int length; static void print(List *l); };
MyObject o # Creates a new object named `o' MyObject o -this $objptr # Turn a pointer to an existing C++ object into a # Tcl object named `o' MyObject -this $objptr # Turn the pointer $objptr into a Tcl "object" MyObject -args args # Create a new object and pick a name for it. A handle # will be returned and is the same as the pointer value. MyObject # The same as MyObject -args, but for constructors that # take no arguments.
Thus, for our List class, you can create new List objects as follows :
List l # Create a new list l set listptr [new_List] # Create a new List using low level interface List l2 -this $listptr # Turn it into a List object named `l2' set l3 [List] # Create a new list. The name of the list is in $l3 List -this $listptr # Turn $listptr into a Tcl object of the same name
Assuming you're not completely confused at this point, the best way to think of this is that there are really two different ways of representing an object. One approach is to simply use the pointer value as the name of an object. For example :
The second approach is to allow you to pick a name for an object such as "foo". The different types of constructors are really just a mechanism for using either approach._100e8f8_p_List
Or if you let SWIG generate the name of the object, it works like this:% List l % l insert "Bob" % l insert "Mary" % l search "Dave" 0 % ...
% set l [List] % $l insert "Bob" # Note $l contains the name of the object % $l insert "Mary" % $l search "Dave" 0 %
It is also possible to explicitly delete the object using the delete method. For example:% rename l "" # Destroy list object `l'
If applicable, SWIG will automatically call the corresponding C/C++ destructor when the object is destroyed.% l -delete
The cget method currently only allows retrieval of one member at a time. Extracting multiple members will require repeated calls.% l cget -length # Get the length of the list 13
The member -this contains the pointer to the object that is compatible with other SWIG functions. Thus, the following call would be legal
% List l # Create a new list object % l insert Mike % List_print [l cget -this] # Print it out using low-level function
In a structure such as the following :% l configure -length 10 # Change length to 10 (probably not a good idea, but # possible).
you can change the value of all or some of the members as follows :struct Vector { double x, y, z; };
% v configure -x 3.5 -y 2 -z -1.0
The order of attributes does not matter.
To handle object ownership, two object methods are available:
When Tcl owns an object, it is released when the Tcl variable is destroyed. Otherwise, the Tcl variable is destroyed without calling the corresponding C/C++ destructor.% obj -disown # Release ownership % obj -acquire # Acquire ownership
Here is a script that illustrates how these things work :
# Example 1 : Using a named object List l # Create a new list l insert Dave # Call some methods l insert Jane l insert Pat List_print [l cget -this] # Call a static method (which requires the pointer value) # Example 2: Let SWIG pick a name set l [List] # Create a new list $l insert Dave # Call some methods $l insert Jane $l insert Pat List_print $l # Call static method (name of object is same as pointer) # Example 3: Already existing object set l [new_List] # Create a raw object using low-level interface List_insert $l Dave # Call some methods (using low-level functions) List -this $l # Turn it into a Tcl object instead $l insert Jane $l insert Part List_print $l # Call static method (uses pointer value as before).
SWIG is quite literal in its interpretation of double *--it is a pointer to a double. To provide access, a few helper functions can be written such as the following :// Add vector a+b -> c void vector_add(double *a, double *b, double *c, int size);
// SWIG helper functions for double arrays %inline %{ double *new_double(int size) { return (double *) malloc(size*sizeof(double)); } void delete_double(double *a) { free a; } double get_double(double *a, int index) { return a[index]; } void set_double(double *a, int index, double val) { a[index] = val; } %}
Using our C functions might work like this :
The functions get_double and set_double can be used to access individual elements of an array. To convert from Tcl lists to C arrays, one could write a few functions in Tcl such as the following :# Tcl code to create some arrays and add them set a [new_double 200] set b [new_double 200] set c [new_double 200] # Fill a and b with some values for {set i 0} {$i < 200} {incr i 1} { set_double $a $i 0.0 set_double $b $i $i } # Add them and store result in c vector_add $a $b $c 200
While not optimal, one could use these to turn a Tcl list into a C representation. The C representation could be used repeatedly in a variety of C functions without having to repeatedly convert from strings (Of course, if the Tcl list changed one would want to update the C version). Likewise, it is relatively simple to go back from C into Tcl. This is not the only way to manage arrays--typemaps can be used as well. The SWIG library file `array.i' also contains a variety of pre-written helper functions for managing different kinds of arrays.# Tcl Procedure to turn a list into a C array proc Tcl2Array {l} { set len [llength $l] set a [new_double $len] set i 0 foreach item $l { set_double $a $i $item incr i 1 } return $a } # Tcl Procedure to turn a C array into a Tcl List proc Array2Tcl {a size} { set l {} for {set i 0} {$i < size} {incr i 1} { lappend $l [get_double $a $i] } return $l }
class RangeError {}; // Used for an exception class DoubleArray { private: int n; double *ptr; public: // Create a new array of fixed size DoubleArray(int size) { ptr = new double[size]; n = size; } // Destroy an array ~DoubleArray() { delete ptr; } // Return the length of the array int length() { return n; } // Get an item from the array and perform bounds checking. double getitem(int i) { if ((i >= 0) && (i < n)) return ptr[i]; else throw RangeError(); } // Set an item in the array and perform bounds checking. void setitem(int i, double val) { if ((i >= 0) && (i < n)) ptr[i] = val; else { throw RangeError(); } } };
The functions associated with this class can throw a C++ range exception for an out-of-bounds array access. We can catch this in our Tcl extension by specifying the following in an interface file :
or in Tcl 8.0%except(tcl) { try { $function // Gets substituted by actual function call } catch (RangeError) { interp->result = "Array index out-of-bounds"; return TCL_ERROR; } }
When the C++ class throws a RangeError exception, our wrapper functions will catch it, turn it into a Tcl exception, and allow a graceful death as opposed to just having some sort of mysterious program crash. We are not limited to C++ exception handling. Please see the chapter on exception handling for more details on other possibilities, including a method for language-independent exception handling..%except(tcl8) { try { $function // Gets substituted by actual function call } catch (RangeError) { Tcl_SetStringObj(tcl_result,"Array index out-of-bounds"); return TCL_ERROR; } }
%module example %typemap(tcl,in) int { $target = (int) atoi($source); printf("Received an integer : %d\n",$target); } ... extern int fact(int n);
Typemaps require a language name, method name, datatype, and conversion code. For Tcl, "tcl" should be used as the language name. For Tcl 8.0, "tcl8" should be used if you are using the native object interface. The "in" method in this example refers to an input argument of a function. The datatype `int' tells SWIG that we are remapping integers. The supplied code is used to convert from a Tcl string to the corresponding C datatype. Within the supporting C code, the variable $source contains the source data (a string in this case) and $target contains the destination of a conversion (a C local variable).
When the example is compiled into a Tcl module, it will operate as follows :
% fact 6 Received an integer : 6 720 %
A full discussion of typemaps can be found in the main SWIG users reference. We will primarily be concerned with Tcl typemaps here.
%typemap(tcl,in) Converts a string to input function arguments
%typemap(tcl,out) Converts return value of a C function to a string
%typemap(tcl,freearg) Cleans up a function argument (if necessary)
%typemap(tcl,argout) Output argument processing
%typemap(tcl,ret) Cleanup of function return values
%typemap(tcl,const) Creation of Tcl constants
%typemap(memberin) Setting of C++ member data
%typemap(memberout) Return of C++ member data
%typemap(tcl, check) Check value of function arguments.
$source Source value of a conversion
$target Target of conversion (where the result should be stored)
$type C datatype being remapped
$mangle Mangled version of data (used for pointer type-checking)
$value Value of a constant (const typemap only)
$arg Original function argument (usually a string)
In this example, two typemaps are applied to the char ** datatype. However, the second typemap will only be applied to arguments named `argv'. A named typemap will always override an unnamed typemap.%module foo // This typemap will be applied to all char ** function arguments %typemap(tcl,in) char ** { ... } // This typemap is applied only to char ** arguments named `argv' %typemap(tcl,in) char **argv { ... }
Due to the name-based nature of typemaps, it is important to note that typemaps are independent of typedef declarations. For example :
To get around this problem, the %apply directive can be used as follows :%typemap(tcl, in) double { ... get a double ... } void foo(double); // Uses the above typemap typedef double Real; void bar(Real); // Does not use the above typemap (double != Real)
%typemap(tcl,in) double { ... get a double ... } void foo(double); typedef double Real; // Uses typemap %apply double { Real }; // Applies all "double" typemaps to Real. void bar(Real); // Now uses the same typemap.
When compiled, we can use our functions as follows :%module argv // This tells SWIG to treat char ** as a special case %typemap(tcl,in) char ** { int tempc; if (Tcl_SplitList(interp,$source,&tempc,&$target) == TCL_ERROR) return TCL_ERROR; } // This gives SWIG some cleanup code that will get called after the function call %typemap(tcl,freearg) char ** { free((char *) $source); } // Return a char ** as a Tcl list %typemap(tcl,out) char ** { int i = 0; while ($source[i]) { Tcl_AppendElement(interp,$source[i]); i++; } } // Now a few test functions %inline %{ int print_args(char **argv) { int i = 0; while (argv[i]) { printf("argv[%d] = %s\n", i,argv[i]); i++; } return i; } // Returns a char ** list char **get_args() { static char *values[] = { "Dave", "Mike", "Susan", "John", "Michelle", 0}; return &values[0]; } // A global variable char *args[] = { "123", "54", "-2", "0", "NULL", 0 }; %} %include tclsh.i
% print_args {John Guido Larry} argv[0] = John argv[1] = Guido argv[2] = Larry 3 % puts [get_args] Dave Mike Susan John Michelle % puts [args_get] 123 54 -2 0 NULL %
Perhaps the only tricky part of this example is the implicit memory allocation that is performed by the Tcl_SplitList function. To prevent a memory leak, we can use the SWIG "freearg" typemap to clean up the argument value after the function call is made. In this case, we simply free up the memory that Tcl_SplitList allocated for us.
If you have hundreds of functions however, this quickly gets annoying. Here's a fix using hash tables and SWIG typemaps :proc clearscreen { } { global GL_COLOR_BUFFER_BIT glClear $GL_COLOR_BUFFER_BIT }
In our Tcl code, we can now access constants by name without using the "global" keyword as follows :// Declare some Tcl hash table variables %{ static Tcl_HashTable constTable; /* Hash table */ static int *swigconst; /* Temporary variable */ static Tcl_HashEntry *entryPtr; /* Hash entry */ static int dummy; /* dummy value */ %} // Initialize the hash table (This goes in the initialization function) %init %{ Tcl_InitHashTable(&constTable,TCL_STRING_KEYS); %} // A Typemap for creating constant values // $source = the value of the constant // $target = the name of the constant %typemap(tcl,const) int, unsigned int, long, unsigned long { entryPtr = Tcl_CreateHashEntry(&constTable,"$target",&dummy); swigconst = (int *) malloc(sizeof(int)); *swigconst = $source; Tcl_SetHashValue(entryPtr, swigconst); /* Make it so constants can also be used as variables */ Tcl_LinkVar(interp,"$target", (char *) swigconst, TCL_LINK_INT | TCL_LINK_READ_ONLY); }; // Now change integer handling to look for names in addition to values %typemap(tcl,in) int, unsigned int, long, unsigned long { Tcl_HashEntry *entryPtr; entryPtr = Tcl_FindHashEntry(&constTable,$source); if (entryPtr) { $target = ($type) (*((int *) Tcl_GetHashValue(entryPtr))); } else { $target = ($type) atoi($source); } }
proc clearscreen { } { glClear GL_COLOR_BUFFER_BIT }
When wrapped, SWIG matches the argout typemap to the "double *outvalue" argument. The "ignore" typemap tells SWIG to simply ignore this argument when generating wrapper code. As a result, a Tcl function using these typemaps will work like this :// A typemap defining how to return an argument by appending it to the result %typemap(tcl,argout) double *outvalue { char dtemp[TCL_DOUBLE_SPACE]; Tcl_PrintDouble(interp,*($source),dtemp); Tcl_AppendElement(interp, dtemp); } // A typemap telling SWIG to ignore an argument for input // However, we still need to pass a pointer to the C function %typemap(tcl,ignore) double *outvalue { static double temp; /* A temporary holding place */ $target = &temp; } // Now a function returning two values int mypow(double a, double b, double *outvalue) { if ((a < 0) || (b < 0)) return -1; *outvalue = pow(a,b); return 0; };
% mypow 2 3 # Returns two values, a status value and the result 0 8 %
An alternative approach to this is to return values in a Tcl variable as follows :
Our Tcl script can now do the following :%typemap(tcl,argout) double *outvalue { char temp[TCL_DOUBLE_SPACE]; Tcl_PrintDouble(interp,*($source),dtemp); Tcl_SetVar(interp,$arg,temp,0); } %typemap(tcl,in) double *outvalue { static double temp; $target = &temp; }
Here, we have passed the name of a Tcl variable to our C wrapper function which then places the return value in that variable. This is now very close to the way in which a C function calling this function would work.% set status [mypow 2 3 a] % puts $status 0 % puts $a 8.0 %
By default, SWIG will simply treat all occurrences of "User" as a pointer. Thus, functions like this :typedef struct { char login[16]; /* Login ID */ int uid; /* User ID */ int gid; /* Group ID */ char name[32]; /* User name */ char home[256]; /* Home directory */ } User;
will work, but they will be weird. In fact, they may not work at all unless you write helper functions to create users and extract data. A typemap can be used to fix this problem however. For example :extern void add_user(User u); extern User *lookup_user(char *name);
// This works for both "User" and "User *" %typemap(tcl,in) User * { int tempc; char **tempa; static User temp; if (Tcl_SplitList(interp,$source,&tempc,&tempa) == TCL_ERROR) return TCL_ERROR; if (tempc != 5) { free((char *) tempa); interp->result = "Not a valid User record"; return TCL_ERROR; } /* Split out the different fields */ strncpy(temp.login,tempa[0],16); temp.uid = atoi(tempa[1]); temp.gid = atoi(tempa[2]); strncpy(temp.name,tempa[3],32); strncpy(temp.home,tempa[4],256); $target = &temp; free((char *) tempa); } // Describe how we want to return a user record %typemap(tcl,out) User * { char temp[20]; if ($source) { Tcl_AppendElement(interp,$source->login); sprintf(temp,"%d",$source->uid); Tcl_AppendElement(interp,temp); sprintf(temp,"%d",$source->gid); Tcl_AppendElement(interp,temp); Tcl_AppendElement(interp,$source->name); Tcl_AppendElement(interp,$source->home); } }
These function marshall Tcl lists to and from our User data structure. This allows a more natural implementation that we can use as follows :
This is a much cleaner interface (although at the cost of some performance). The only caution I offer is that the pointer view of the world is pervasive throughout SWIG. Remapping complex datatypes like this will usually work, but every now and then you might find that it breaks. For example, if we needed to manipulate arrays of Users (also mapped as a "User *"), the typemaps defined here would break down and something else would be needed. Changing the representation in this manner may also break the object-oriented interface.% add_user {beazley 500 500 "Dave Beazley" "/home/beazley"} % lookup_user beazley beazley 500 500 {Dave Beazley} /home/beazley
Integers
Floating PointTcl_Obj *Tcl_NewIntObj(int Value); void Tcl_SetIntObj(Tcl_Obj *obj, int Value); int Tcl_GetIntFromObj(Tcl_Interp *, Tcl_Obj *obj, int *ip);
StringsTcl_Obj *Tcl_NewDoubleObj(double Value); void Tcl_SetDoubleObj(Tcl_Obj *obj, double value); int Tcl_GetDoubleFromObj(Tcl_Interp *, Tcl_Obj *o, double *dp);
ListsTcl_Obj *Tcl_NewStringObj(char *str, int len); void Tcl_SetStringObj(Tcl_Obj *obj, char *str, int len); char *Tcl_GetStringFromObj(Tcl_Obj *obj, int *len); void Tcl_AppendToObj(Tcl_Obj *obj, char *str, int len);
ObjectsTcl_Obj *Tcl_NewListObj(int objc, Tcl_Obj *objv); int Tcl_ListObjAppendList(Tcl_Interp *, Tcl_Obj *listPtr, Tcl_Obj *elemListPtr); int Tcl_ListObjAppendElement(Tcl_Interp *, Tcl_Obj *listPtr, Tcl_Obj *element); int Tcl_ListObjGetElements(Tcl_Interp *, Tcl_Obj *listPtr, int *objcPtr, Tcl_Obj ***objvPtr); int Tcl_ListObjLength(Tcl_Interp *, Tcl_Obj *listPtr, int *intPtr); int Tcl_ListObjIndex(Tcl_Interp *, Tcl_Obj *listPtr, int index, Tcl_Obj_Obj **objptr); int Tcl_ListObjReplace(Tcl_Interp *, Tcl_Obj *listPtr, int first, int count, int objc, Tcl_Obj *objv);
Tcl_Obj *Tcl_DuplicateObj(Tcl_Obj *obj); void Tcl_IncrRefCount(Tcl_Obj *obj); void Tcl_DecrRefCount(Tcl_Obj *obj); int Tcl_IsShared(Tcl_Obj *obj);
Integer conversion
%typemap(in) int, short, long { int temp; if (Tcl_GetIntFromObj(interp, $input, &temp) == TCL_ERROR) return TCL_ERROR; $1 = ($1_ltype) temp; }
Floating point conversion%typemap(out) int, short, long { Tcl_SetIntObj($result,(int) $1); }
%typemap(in) float, double { double temp; if (Tcl_GetDoubleFromObj(interp, $input, &temp) == TCL_ERROR) return TCL_ERROR; $1 = ($1_ltype) temp; }
String Conversion%typemap(out) float, double { Tcl_SetDoubleObj($result, $1); }
%typemap(in) char * { int len; $1 = Tcl_GetStringFromObj(interp, &len); } }
%typemap(out) char * { Tcl_SetStringObj($result,$1); }
SWIG pointers are mapped into Python strings containing the hexadecimal value and type. The following functions can be used to create and read pointer values.
These functions can be used in typemaps as well. For example, the following typemap makes an argument of "char *buffer" accept a pointer instead of a NULL-terminated ASCII string.
Note that the $mangle variable generates the type string associated with the datatype used in the typemap.%typemap(tcl,in) char *buffer { if (SWIG_GetPtr($source, (void **) &$target, "$mangle")) { Tcl_SetResult(interp,"Type error. Not a pointer", TCL_STATIC); return TCL_ERROR; } }
By now you hopefully have the idea that typemaps are a powerful mechanism for building more specialized applications. While writing typemaps can be technical, many have already been written for you. See the SWIG library reference for more information.
While SWIG is certainly not a magical solution to the configuration management problem, it can help out alot in a number of key areas :
While relatively simple to write, there are tons of problems with doing this. First, each extension that you use typically has their own Tcl_AppInit() function. This forces you to write a special one to initialize everything by hand. Secondly, the process of writing a main program and initializing the interpreter varies between different versions of Tcl and different platforms. For example, in Tcl 7.4, the variable "tcl_RcFileName" is a C variable while in Tcl7.5 and newer versions its a Tcl variable instead. Similarly, the Tcl_AppInit function written for a Unix machine might not compile correctly on a Mac or Windows machine./* main.c */ #include <tcl.h> main(int argc, char *argv[]) { Tcl_Main(argc,argv); exit(0); } int Tcl_AppInit(Tcl_Interp *interp) { if (Tcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } /* Initialize your extension */ if (Your_Init(interp) == TCL_ERROR) { return TCL_ERROR; } tcl_RcFileName = "~/.myapp.tcl"; return TCL_OK; }
In SWIG, it is almost never necessary to write a Tcl_AppInit() function because this is now done by SWIG library files such as tclsh.i or wish.i. To give a better idea of what these files do, here's the code from the SWIG tclsh.i file which is roughly comparable to the above code
// tclsh.i : SWIG library file for rebuilding tclsh %{ /* A TCL_AppInit() function that lets you build a new copy * of tclsh. * * The macro SWIG_init contains the name of the initialization * function in the wrapper file. */ #ifndef SWIG_RcFileName char *SWIG_RcFileName = "~/.myapprc"; #endif int Tcl_AppInit(Tcl_Interp *interp){ if (Tcl_Init(interp) == TCL_ERROR) return TCL_ERROR; /* Now initialize our functions */ if (SWIG_init(interp) == TCL_ERROR) return TCL_ERROR; #if TCL_MAJOR_VERSION > 7 || TCL_MAJOR_VERSION == 7 && TCL_MINOR_VERSION >= 5 Tcl_SetVar(interp,"tcl_rcFileName",SWIG_RcFileName,TCL_GLOBAL_ONLY); #else tcl_RcFileName = SWIG_RcFileName; #endif return TCL_OK; } #if TCL_MAJOR_VERSION > 7 || TCL_MAJOR_VERSION == 7 && TCL_MINOR_VERSION >= 4 int main(int argc, char **argv) { Tcl_Main(argc, argv, Tcl_AppInit); return(0); } #else extern int main(); #endif %}
This file is essentially the same as a normal Tcl_AppInit() function except that it supports a variety of Tcl versions. When included into an interface file, the symbol SWIG_init contains the actual name of the initialization function (This symbol is defined by SWIG when it creates the wrapper code). Similarly, a startup file can be defined by simply defining the symbol SWIG_RcFileName. Thus, a typical interface file might look like this :
By including the tclsh.i, you automatically get a Tcl_AppInit() function. A variety of library files are also available. wish.i can be used to build a new wish executable, expect.i contains the main program for Expect, and ish.i, itclsh.i, iwish.i, and itkwish.i contain initializations for various incarnations of [incr Tcl].%module graph %{ #include "graph.h" #define SWIG_RcFileName "graph.tcl" %} %include tclsh.i ... declarations ...
// expect.i : SWIG Library file for Expect %{ /* main.c - main() and some logging routines for expect Written by: Don Libes, NIST, 2/6/90 Design and implementation of this program was paid for by U.S. tax dollars. Therefore it is public domain. However, the author and NIST would appreciate credit if this program or parts of it are used. */ #include "expect_cf.h" #include <stdio.h> #include INCLUDE_TCL #include "expect_tcl.h" void main(argc, argv) int argc; char *argv[]; { int rc = 0; Tcl_Interp *interp = Tcl_CreateInterp(); int SWIG_init(Tcl_Interp *); if (Tcl_Init(interp) == TCL_ERROR) { fprintf(stderr,"Tcl_Init failed: %s\n",interp->result); exit(1); } if (Exp_Init(interp) == TCL_ERROR) { fprintf(stderr,"Exp_Init failed: %s\n",interp->result); exit(1); } /* SWIG initialization. --- 2/11/96 */ if (SWIG_init(interp) == TCL_ERROR) { fprintf(stderr,"SWIG initialization failed: %s\n", interp->result); exit(1); } exp_parse_argv(interp,argc,argv); /* become interactive if requested or "nothing to do" */ if (exp_interactive) (void) exp_interpreter(interp); else if (exp_cmdfile) rc = exp_interpret_cmdfile(interp,exp_cmdfile); else if (exp_cmdfilename) rc = exp_interpret_cmdfilename(interp,exp_cmdfilename); /* assert(exp_cmdlinecmds != 0) */ exp_exit(interp,rc); /*NOTREACHED*/ } %}
In the event that you need to write a new library file such as this, the process usually isn't too difficult. Start by grabbing the original Tcl_AppInit() function for the package. Enclose it in a %{,%} block. Now add a line that makes a call to SWIG_init(). This will automatically resolve to the real initialization function when compiled.
Both files declare the proper initialization function (to be C++ friendly, this should be done using extern "C"). A call to the initialization function is then placed inside a %init %{ ... %} block.// blt.i : SWIG library file for initializing the BLT extension %{ #ifdef __cplusplus extern "C" { #endif extern int Blt_Init(Tcl_Interp *); #ifdef __cplusplus } #endif %} %init %{ if (Blt_Init(interp) == TCL_ERROR) { return TCL_ERROR; } %} // tix.i : SWIG library file for initializing the Tix extension %{ #ifdef __cplusplus extern "C" { #endif extern int Tix_Init(Tcl_Interp *); #ifdef __cplusplus } #endif %} %init %{ if (Tix_Init(interp) == TCL_ERROR) { return TCL_ERROR; } %}
To use our library files and build a new version of wish, we might now do the following :
Of course, the really cool part about all of this is that the file `mywish.i' can itself, serve as a library file. Thus, when building various versions of Tcl, we can place everything we want to use a special file and use it in all of our other interface files :// mywish.i : wish with a bunch of stuff added to it %include wish.i %include blt.i %include tix.i ... additional declarations ...
or we can grab it on the command line :// interface.i %module mymodule %include mywish.i // Build our version of Tcl with extensions ... C declarations ...
unix > swig -tcl -lmywish.i interface.i
%init %{ Tcl_PkgProvide(interp,"example","0.0"); %}
Where "example" is the name of the package and "0.0" is the version of the package.
Next, after building the SWIG generated module, you need to execute the "pkg_mkIndex" command inside tclsh. For example :
This creates a file "pkgIndex.tcl" with information about the package. To use yourunix > tclsh % pkg_mkIndex . example.so % exit
package, you now need to move it to its own subdirectory which has the same name as the package. For example :
./example/ pkgIndex.tcl # The file created by pkg_mkIndex example.so # The SWIG generated module
Finally, assuming that you're not entirely confused at this point, make sure that the example subdirectory is visible from the directories contained in either the tcl_library or auto_path variables. At this point you're ready to use the package as follows :
unix > tclsh % package require example % fact 4 24 %
If you're working with an example in the current directory and this doesn't work, do this instead :
unix > tclsh % lappend auto_path . % package require example % fact 4 24
As a final note, most SWIG examples do not yet use the package commands. For simple extensions it may be easier just to use the load command instead.
While these could be called directly, we could also write a Tcl script like this :/* File : array.i */ %module array %inline %{ double *new_double(int size) { return (double *) malloc(size*sizeof(double)); } void delete_double(double *a) { free(a); } double get_double(double *a, int index) { return a[index]; } void set_double(double *a, int index, double val) { a[index] = val; } int *new_int(int size) { return (int *) malloc(size*sizeof(int)); } void delete_int(int *a) { free(a); } int get_int(int *a, int index) { return a[index]; } int set_int(int *a, int index, int val) { a[index] = val; } %}
proc Array {type size} { set ptr [new_$type $size] set code { set method [lindex $args 0] set parms [concat $ptr [lrange $args 1 end]] switch $method { get {return [eval "get_$type $parms"]} set {return [eval "set_$type $parms"]} delete {eval "delete_$type $ptr; rename $ptr {}"} } } # Create a procedure uplevel "proc $ptr args {set ptr $ptr; set type $type;$code}" return $ptr }
Our script allows easy array access as follows :
set a [Array double 100] ;# Create a double [100] for {set i 0} {$i < 100} {incr i 1} { ;# Clear the array $a set $i 0.0 } $a set 3 3.1455 ;# Set an individual element set b [$a get 10] ;# Retrieve an element set ia [Array int 50] ;# Create an int[50] for {set i 0} {$i < 50} {incr i 1} { ;# Clear it $ia set $i 0 } $ia set 3 7 ;# Set an individual element set ib [$ia get 10] ;# Get an individual element $a delete ;# Destroy a $ia delete ;# Destroy ia
The cool thing about this approach is that it makes a common interface for two different types of arrays. In fact, if we were to add more C datatypes to our wrapper file, the Tcl code would work with those as well--without modification. If an unsupported datatype was requested, the Tcl code would simply return with an error so there is very little danger of blowing something up (although it is easily accomplished with an out of bounds array access).
# swig_c++.tcl # Provides a simple object oriented interface using # SWIG's low level interface. # proc new {objectType handle_r args} { # Creates a new SWIG object of the given type, # returning a handle in the variable "handle_r". # # Also creates a procedure for the object and a trace on # the handle variable that deletes the object when the # handle varibale is overwritten or unset upvar $handle_r handle # # Create the new object # eval set handle \[new_$objectType $args\] # # Set up the object procedure # proc $handle {cmd args} "eval ${objectType}_\$cmd $handle \$args" # # And the trace ... # uplevel trace variable $handle_r uw "{deleteObject $objectType $handle}" # # Return the handle so that 'new' can be used as an argument to a procedure # return $handle } proc deleteObject {objectType handle name element op} { # # Check that the object handle has a reasonable form # if {![regexp {_[0-9a-f]*_(.+)_p} $handle]} { error "deleteObject: not a valid object handle: $handle" } # # Remove the object procedure # catch {rename $handle {}} # # Delete the object # delete_$objectType $handle } proc delete {handle_r} { # # A synonym for unset that is more familiar to C++ programmers # uplevel unset $handle_r }
To use this file, we simply source it and execute commands such as "new" and "delete" to manipulate objects. For example :
// list.i %module List %{ #include "list.h" %} // Very simple C++ example class List { public: List(); // Create a new list ~List(); // Destroy a list int search(char *value); void insert(char *); // Insert a new item into the list void remove(char *); // Remove item from list char *get(int n); // Get the nth item in the list int length; // The current length of the list static void print(List *l); // Print out the contents of the list };
Now a Tcl script using the interface...
The cool thing about this example is that it works with any C++ object wrapped by SWIG and requires no special compilation. Proof that a short, but clever Tcl script can be combined with SWIG to do many interesting things.load ./list.so list ; # Load the module source swig_c++.tcl ; # Source the object file new List l $l insert Dave $l insert John $l insert Guido $l remove Dave puts $l length_get delete l