1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
4 <title>SWIG and Tcl</title>
5 <link rel="stylesheet" type="text/css" href="style.css">
8 <body bgcolor="#ffffff">
9 <H1><a name="Tcl"></a>33 SWIG and Tcl</H1>
11 <div class="sectiontoc">
13 <li><a href="#Tcl_nn2">Preliminaries</a>
15 <li><a href="#Tcl_nn3">Getting the right header files</a>
16 <li><a href="#Tcl_nn4">Compiling a dynamic module</a>
17 <li><a href="#Tcl_nn5">Static linking</a>
18 <li><a href="#Tcl_nn6">Using your module</a>
19 <li><a href="#Tcl_nn7">Compilation of C++ extensions</a>
20 <li><a href="#Tcl_nn8">Compiling for 64-bit platforms</a>
21 <li><a href="#Tcl_nn9">Setting a package prefix</a>
22 <li><a href="#Tcl_nn10">Using namespaces</a>
24 <li><a href="#Tcl_nn11">Building Tcl/Tk Extensions under Windows 95/NT</a>
26 <li><a href="#Tcl_nn12">Running SWIG from Developer Studio</a>
27 <li><a href="#Tcl_nn13">Using NMAKE</a>
29 <li><a href="#Tcl_nn14">A tour of basic C/C++ wrapping</a>
31 <li><a href="#Tcl_nn15">Modules</a>
32 <li><a href="#Tcl_nn16">Functions</a>
33 <li><a href="#Tcl_nn17">Global variables</a>
34 <li><a href="#Tcl_nn18">Constants and enums</a>
35 <li><a href="#Tcl_nn19">Pointers</a>
36 <li><a href="#Tcl_nn20">Structures</a>
37 <li><a href="#Tcl_nn21">C++ classes</a>
38 <li><a href="#Tcl_nn22">C++ inheritance</a>
39 <li><a href="#Tcl_nn23">Pointers, references, values, and arrays</a>
40 <li><a href="#Tcl_nn24">C++ overloaded functions</a>
41 <li><a href="#Tcl_nn25">C++ operators</a>
42 <li><a href="#Tcl_nn26">C++ namespaces</a>
43 <li><a href="#Tcl_nn27">C++ templates</a>
44 <li><a href="#Tcl_nn28">C++ Smart Pointers</a>
46 <li><a href="#Tcl_nn29">Further details on the Tcl class interface</a>
48 <li><a href="#Tcl_nn30">Proxy classes</a>
49 <li><a href="#Tcl_nn31">Memory management</a>
51 <li><a href="#Tcl_nn32">Input and output parameters</a>
52 <li><a href="#Tcl_nn33">Exception handling </a>
53 <li><a href="#Tcl_nn34">Typemaps</a>
55 <li><a href="#Tcl_nn35">What is a typemap?</a>
56 <li><a href="#Tcl_nn36">Tcl typemaps</a>
57 <li><a href="#Tcl_nn37">Typemap variables</a>
58 <li><a href="#Tcl_nn38">Converting a Tcl list to a char ** </a>
59 <li><a href="#Tcl_nn39">Returning values in arguments</a>
60 <li><a href="#Tcl_nn40">Useful functions</a>
61 <li><a href="#Tcl_nn41">Standard typemaps</a>
62 <li><a href="#Tcl_nn42">Pointer handling</a>
64 <li><a href="#Tcl_nn43">Turning a SWIG module into a Tcl Package.</a>
65 <li><a href="#Tcl_nn44">Building new kinds of Tcl interfaces (in Tcl)</a>
67 <li><a href="#Tcl_nn45">Proxy classes</a>
69 <li><a href="#Tcl_nn46">Tcl/Tk Stubs</a>
77 <b>Caution: This chapter is under repair!</b>
81 This chapter discusses SWIG's support of Tcl. SWIG currently requires
82 Tcl 8.0 or a later release. Earlier releases of SWIG supported Tcl 7.x, but
83 this is no longer supported.
86 <H2><a name="Tcl_nn2"></a>33.1 Preliminaries</H2>
90 To build a Tcl module, run SWIG using the <tt>-tcl</tt> option :
93 <div class="code"><pre>
98 If building a C++ extension, add the <tt>-c++</tt> option:
101 <div class="code"><pre>
102 $ swig -c++ -tcl example.i
106 This creates a file <tt>example_wrap.c</tt> or
107 <tt>example_wrap.cxx</tt> that contains all of the code needed to
108 build a Tcl extension module. To finish building the module, you
109 need to compile this file and link it with the rest of your program.
112 <H3><a name="Tcl_nn3"></a>33.1.1 Getting the right header files</H3>
116 In order to compile the wrapper code, the compiler needs the <tt>tcl.h</tt> header file.
117 This file is usually contained in the directory
120 <div class="code"><pre>
125 Be aware that some Tcl versions install this header file with a version number attached to it. If
126 this is the case, you should probably make a symbolic link so that <tt>tcl.h</tt> points to the correct
130 <H3><a name="Tcl_nn4"></a>33.1.2 Compiling a dynamic module</H3>
134 The preferred approach to building an extension module is to compile it into
135 a shared object file or DLL. To do this, you will need to compile your program
136 using commands like this (shown for Linux):
139 <div class="code"><pre>
140 $ swig -tcl example.i
142 $ gcc -c example_wrap.c -I/usr/local/include
143 $ gcc -shared example.o example_wrap.o -o example.so
147 The exact commands for doing this vary from platform to platform.
148 SWIG tries to guess the right options when it is installed. Therefore,
149 you may want to start with one of the examples in the <tt>SWIG/Examples/tcl</tt>
150 directory. If that doesn't work, you will need to read the man-pages for
151 your compiler and linker to get the right set of options. You might also
152 check the <a href="http://www.dabeaz.com/cgi-bin/wiki.pl">SWIG Wiki</a> for
153 additional information.
157 When linking the module, the name of the output file has to match the name
158 of the module. If the name of your SWIG module is "<tt>example</tt>", the
159 name of the corresponding object file should be
160 "<tt>example.so</tt>".
161 The name of the module is specified using the <tt>%module</tt> directive or the
162 <tt> -module</tt> command line option.
165 <H3><a name="Tcl_nn5"></a>33.1.3 Static linking</H3>
169 An alternative approach to dynamic linking is to rebuild the Tcl
170 interpreter with your extension module added to it. In the past,
171 this approach was sometimes necessary due to limitations in dynamic loading
172 support on certain machines. However, the situation has improved greatly
173 over the last few years and you should not consider this approach
174 unless there is really no other option.
178 The usual procedure for adding a new module to Tcl involves writing a
179 special function <tt>Tcl_AppInit()</tt> and using it to initialize the interpreter and
180 your module. With SWIG, the <tt>tclsh.i</tt> and <tt>wish.i</tt> library files
181 can be used to rebuild the <tt>tclsh</tt> and <tt>wish</tt> interpreters respectively.
185 <div class="code"><pre>
189 extern int fact(int);
190 extern int mod(int, int);
191 extern double My_variable;
194 %include "tclsh.i" // Include code for rebuilding tclsh
199 The <tt>tclsh.i</tt> library file includes supporting code that
200 contains everything needed to rebuild tclsh. To rebuild the interpreter,
201 you simply do something like this:
204 <div class="code"><pre>
205 $ swig -tcl example.i
206 $ gcc example.c example_wrap.c \
207 -Xlinker -export-dynamic \
208 -DHAVE_CONFIG_H -I/usr/local/include/ \
209 -L/usr/local/lib -ltcl -lm -ldl \
215 You will need to supply the same libraries that were used to build Tcl the first
216 time. This may include system libraries such as <tt>-lsocket</tt>, <tt>-lnsl</tt>,
217 and <tt>-lpthread</tt>. If this actually works, the new version of Tcl
218 should be identical to the default version except that your extension module will be
219 a built-in part of the interpreter.
223 <b>Comment:</b> In practice, you should probably try to avoid static
224 linking if possible. Some programmers may be inclined
225 to use static linking in the interest of getting better performance.
226 However, the performance gained by static linking tends to be rather
227 minimal in most situations (and quite frankly not worth the extra
228 hassle in the opinion of this author).
231 <H3><a name="Tcl_nn6"></a>33.1.4 Using your module</H3>
235 To use your module, simply use the Tcl <tt>load</tt> command. If
236 all goes well, you will be able to this:
239 <div class="code"><pre>
248 A common error received by first-time users is the following:
254 couldn't find procedure Example_Init
260 This error is almost always caused when the name of the shared object file doesn't
261 match the name of the module supplied using the SWIG <tt>%module</tt> directive.
262 Double-check the interface to make sure the module name and the shared object
263 file match. Another possible cause of this error is forgetting to link the SWIG-generated
264 wrapper code with the rest of your application when creating the extension module.
268 Another common error is something similar to the following:
274 couldn't load file "./example.so": ./example.so: undefined symbol: fact
280 This error usually indicates that you forgot to include some object
281 files or libraries in the linking of the shared library file. Make
282 sure you compile both the SWIG wrapper file and your original program
283 into a shared library file. Make sure you pass all of the required libraries
288 Sometimes unresolved symbols occur because a wrapper has been created
289 for a function that doesn't actually exist in a library. This usually
290 occurs when a header file includes a declaration for a function that
291 was never actually implemented or it was removed from a library
292 without updating the header file. To fix this, you can either edit
293 the SWIG input file to remove the offending declaration or you can use
294 the <tt>%ignore</tt> directive to ignore the declaration.
298 Finally, suppose that your extension module is linked with another library like this:
303 $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
309 If the <tt>foo</tt> library is compiled as a shared library, you might get the following
310 problem when you try to use your module:
316 couldn't load file "./example.so": libfoo.so: cannot open shared object file:
317 No such file or directory
323 This error is generated because the dynamic linker can't locate the
324 <tt>libfoo.so</tt> library. When shared libraries are loaded, the
325 system normally only checks a few standard locations such as
326 <tt>/usr/lib</tt> and <tt>/usr/local/lib</tt>. To fix this problem,
327 there are several things you can do. First, you can recompile your extension
328 module with extra path information. For example, on Linux you can do this:
333 $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
334 -Xlinker -rpath /home/beazley/projects/lib \
340 Alternatively, you can set the <tt>LD_LIBRARY_PATH</tt> environment variable to
341 include the directory with your shared libraries.
342 If setting <tt>LD_LIBRARY_PATH</tt>, be aware that setting this variable can introduce
343 a noticeable performance impact on all other applications that you run.
344 To set it only for Tcl, you might want to do this instead:
349 $ env LD_LIBRARY_PATH=/home/beazley/projects/lib tclsh
354 Finally, you can use a command such as <tt>ldconfig</tt> to add additional search paths
355 to the default system configuration (this requires root access and you will need to read
359 <H3><a name="Tcl_nn7"></a>33.1.5 Compilation of C++ extensions</H3>
363 Compilation of C++ extensions has traditionally been a tricky problem.
364 Since the Tcl interpreter is written in C, you need to take steps to
365 make sure C++ is properly initialized and that modules are compiled
370 On most machines, C++ extension modules should be linked using the C++
371 compiler. For example:
374 <div class="code"><pre>
375 % swig -c++ -tcl example.i
377 % g++ -c example_wrap.cxx -I/usr/local/include
378 % g++ -shared example.o example_wrap.o -o example.so
382 In addition to this, you may need to include additional library
383 files to make it work. For example, if you are using the Sun C++ compiler on
384 Solaris, you often need to add an extra library <tt>-lCrun</tt> like this:
387 <div class="code"><pre>
388 % swig -c++ -tcl example.i
390 % CC -c example_wrap.cxx -I/usr/local/include
391 % CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o example.so -lCrun
395 Of course, the extra libraries to use are completely non-portable---you will
396 probably need to do some experimentation.
400 Sometimes people have suggested that it is necessary to relink the
401 Tcl interpreter using the C++ compiler to make C++ extension modules work.
402 In the experience of this author, this has never actually appeared to be
403 necessary. Relinking the interpreter with C++ really only includes the
404 special run-time libraries described above---as long as you link your extension
405 modules with these libraries, it should not be necessary to rebuild Tcl.
409 If you aren't entirely sure about the linking of a C++ extension, you
410 might look at an existing C++ program. On many Unix machines, the
411 <tt>ldd</tt> command will list library dependencies. This should give
412 you some clues about what you might have to include when you link your
413 extension module. For example:
419 libstdc++-libc6.1-1.so.2 => /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
420 libm.so.6 => /lib/libm.so.6 (0x4005b000)
421 libc.so.6 => /lib/libc.so.6 (0x40077000)
422 /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
428 As a final complication, a major weakness of C++ is that it does not
429 define any sort of standard for binary linking of libraries. This
430 means that C++ code compiled by different compilers will not link
431 together properly as libraries nor is the memory layout of classes and
432 data structures implemented in any kind of portable manner. In a
433 monolithic C++ program, this problem may be unnoticed. However, in Tcl, it
434 is possible for different extension modules to be compiled with
435 different C++ compilers. As long as these modules are self-contained,
436 this probably won't matter. However, if these modules start sharing data,
437 you will need to take steps to avoid segmentation faults and other
438 erratic program behavior. If working with lots of software components, you
439 might want to investigate using a more formal standard such as COM.
442 <H3><a name="Tcl_nn8"></a>33.1.6 Compiling for 64-bit platforms</H3>
446 On platforms that support 64-bit applications (Solaris, Irix, etc.),
447 special care is required when building extension modules. On these
448 machines, 64-bit applications are compiled and linked using a different
449 set of compiler/linker options. In addition, it is not generally possible to mix
450 32-bit and 64-bit code together in the same application.
454 To utilize 64-bits, the Tcl executable will need to be recompiled
455 as a 64-bit application. In addition, all libraries, wrapper code,
456 and every other part of your application will need to be compiled for
457 64-bits. If you plan to use other third-party extension modules, they
458 will also have to be recompiled as 64-bit extensions.
462 If you are wrapping commercial software for which you have no source
463 code, you will be forced to use the same linking standard as used by
464 that software. This may prevent the use of 64-bit extensions. It may
465 also introduce problems on platforms that support more than one
466 linking standard (e.g., -o32 and -n32 on Irix).
469 <H3><a name="Tcl_nn9"></a>33.1.7 Setting a package prefix</H3>
473 To avoid namespace problems, you can instruct SWIG to append a package
474 prefix to all of your functions and variables. This is done using the
475 -prefix option as follows :
478 <div class="code"><pre>
479 swig -tcl -prefix Foo example.i
483 If you have a function "<tt>bar</tt>" in the SWIG file, the prefix
484 option will append the prefix to the name when creating a command and
485 call it "<tt>Foo_bar</tt>".
488 <H3><a name="Tcl_nn10"></a>33.1.8 Using namespaces</H3>
492 Alternatively, you can have SWIG install your module into a Tcl
493 namespace by specifying the <tt>-namespace</tt> option :
496 <div class="code"><pre>
497 swig -tcl -namespace example.i
501 By default, the name of the namespace will be the same as the module
502 name, but you can override it using the <tt>-prefix</tt> option.
506 When the<tt> -namespace</tt> option is used, objects in the module
507 are always accessed with the namespace name such as <tt>Foo::bar</tt>.
510 <H2><a name="Tcl_nn11"></a>33.2 Building Tcl/Tk Extensions under Windows 95/NT</H2>
514 Building a SWIG extension to Tcl/Tk under Windows 95/NT is roughly
515 similar to the process used with Unix. Normally, you will want to
516 produce a DLL that can be loaded into tclsh or wish. This section
517 covers the process of using SWIG with Microsoft Visual C++.
518 although the procedure may be similar with other compilers.
521 <H3><a name="Tcl_nn12"></a>33.2.1 Running SWIG from Developer Studio</H3>
525 If you are developing your application within Microsoft developer
526 studio, SWIG can be invoked as a custom build option. The process
527 roughly follows these steps :
531 <li>Open up a new workspace and use the AppWizard to select a DLL project.
533 <li>Add both the SWIG interface file (the .i file), any supporting C
534 files, and the name of the wrapper file that will be created by SWIG
535 (ie. <tt>example_wrap.c</tt>). Note : If using C++, choose a
536 different suffix for the wrapper file such as
537 <tt>example_wrap.cxx</tt>. Don't worry if the wrapper file doesn't
538 exist yet--Developer studio will keep a reference to it around.
540 <li>Select the SWIG interface file and go to the settings menu. Under
541 settings, select the "Custom Build" option.
543 <li>Enter "SWIG" in the description field.
545 <li>Enter "<tt>swig -tcl -o $(ProjDir)\$(InputName)_wrap.c
546 $(InputPath)</tt>" in the "Build command(s) field"
548 <li>Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>" in the "Output files(s) field".
550 <li>Next, select the settings for the entire project and go to
551 "C++:Preprocessor". Add the include directories for your Tcl
552 installation under "Additional include directories".
554 <li>Finally, select the settings for the entire project and go to
555 "Link Options". Add the Tcl library file to your link libraries. For
556 example "<tt>tcl80.lib</tt>". Also, set the name of the output file
557 to match the name of your Tcl module (ie. example.dll).
559 <li>Build your project.
563 Now, assuming all went well, SWIG will be automatically invoked when
564 you build your project. Any changes made to the interface file will
565 result in SWIG being automatically invoked to produce a new version of
566 the wrapper file. To run your new Tcl extension, simply run
567 <tt>tclsh</tt> or <tt>wish</tt> and use the <tt>load</tt> command.
571 <div class="code"><pre>
579 <H3><a name="Tcl_nn13"></a>33.2.2 Using NMAKE</H3>
583 Alternatively, SWIG extensions can be built by writing a Makefile for
584 NMAKE. To do this, make sure the environment variables for MSVC++ are
585 available and the MSVC++ tools are in your path. Now, just write a
586 short Makefile like this :
589 <div class="code"><pre>
590 # Makefile for building various SWIG generated extensions
594 INTERFACE = $(IFILE).i
595 WRAPFILE = $(IFILE)_wrap.c
597 # Location of the Visual C++ tools (32 bit assumed)
601 CC = $(TOOLS)\bin\cl.exe
602 LINK = $(TOOLS)\bin\link.exe
603 INCLUDE32 = -I$(TOOLS)\include
606 # C Library needed to build a DLL
608 DLLIBC = msvcrt.lib oldnames.lib
610 # Windows libraries that are apparently needed
611 WINLIB = kernel32.lib advapi32.lib user32.lib gdi32.lib comdlg32.lib
614 # Libraries common to all DLLs
615 LIBS = $(DLLIBC) $(WINLIB)
618 LOPT = -debug:full -debugtype:cv /NODEFAULTLIB /RELEASE /NOLOGO /
619 MACHINE:$(MACHINE) -entry:_DllMainCRTStartup@12 -dll
623 CFLAGS = /Z7 /Od /c /nologo
624 TCL_INCLUDES = -Id:\tcl8.0a2\generic -Id:\tcl8.0a2\win
625 TCLLIB = d:\tcl8.0a2\win\tcl80.lib
628 ..\..\swig -tcl -o $(WRAPFILE) $(INTERFACE)
629 $(CC) $(CFLAGS) $(TCL_INCLUDES) $(SRCS) $(WRAPFILE)
631 $(LINK) $(LOPT) -out:example.dll $(LIBS) $(TCLLIB) example.obj example_wrap.obj
636 To build the extension, run NMAKE (you may need to run vcvars32
637 first). This is a pretty minimal Makefile, but hopefully its enough
638 to get you started. With a little practice, you'll be making lots of
642 <H2><a name="Tcl_nn14"></a>33.3 A tour of basic C/C++ wrapping</H2>
646 By default, SWIG tries to build a very natural Tcl interface to your
647 C/C++ code. Functions are wrapped as functions, classes are wrapped
648 in an interface that mimics the style of Tk widgets and [incr Tcl]
649 classes. This section briefly covers the essential aspects of this
653 <H3><a name="Tcl_nn15"></a>33.3.1 Modules</H3>
657 The SWIG <tt>%module</tt> directive specifies the name of the Tcl
658 module. If you specify `<tt>%module example</tt>', then everything is
659 compiled into an extension module <tt>example.so</tt>. When choosing a
660 module name, make sure you don't use the same name as a built-in
665 One pitfall to watch out for is module names involving numbers. If
666 you specify a module name like <tt>%module md5</tt>, you'll find that the
667 load command no longer seems to work:
673 couldn't find procedure Md_Init
678 To fix this, supply an extra argument to <tt>load</tt> like this:
687 <H3><a name="Tcl_nn16"></a>33.3.2 Functions</H3>
691 Global functions are wrapped as new Tcl built-in commands. For example,
694 <div class="code"><pre>
700 creates a built-in function <tt>fact</tt> that works exactly
701 like you think it does:
704 <div class="code"><pre>
712 <H3><a name="Tcl_nn17"></a>33.3.3 Global variables</H3>
716 C/C++ global variables are wrapped by Tcl global variables. For example:
719 <div class="code"><pre>
720 // SWIG interface file with global variables
724 extern double density;
730 Now look at the Tcl interface:
733 <div class="code"><pre>
734 % puts $density # Output value of C global variable
736 % set density 0.95 # Change value
740 If you make an error in variable assignment, you will get an
741 error message. For example:
744 <div class="code"><pre>
745 % set density "hello"
746 can't set "density": Type error. expected a double.
751 If a variable is declared as <tt>const</tt>, it is wrapped as a
752 read-only variable. Attempts to modify its value will result in an
757 To make ordinary variables read-only, you can use the <tt>%immutable</tt> directive. For example:
772 The <tt>%immutable</tt> directive stays in effect until it is explicitly disabled or cleared using
774 See the <a href="SWIG.html#SWIG_readonly_variables">Creating read-only variables</a> section for further details.
778 If you just want to make a specific variable immutable, supply a declaration name. For example:
788 extern char *path; // Read-only (due to %immutable)
792 <H3><a name="Tcl_nn18"></a>33.3.4 Constants and enums</H3>
796 C/C++ constants are installed as global Tcl variables containing the
797 appropriate value. To create a constant, use <tt>#define</tt>, <tt>enum</tt>, or the
798 <tt>%constant</tt> directive. For example:
804 #define VERSION "1.0"
806 enum Beverage { ALE, LAGER, STOUT, PILSNER };
808 %constant int FOO = 42;
809 %constant const char *path = "/usr/local";
814 For enums, make sure that the definition of the enumeration actually appears in a header
815 file or in the wrapper file somehow---if you just stick an enum in a SWIG interface without
816 also telling the C compiler about it, the wrapper code won't compile.
820 Note: declarations declared as <tt>const</tt> are wrapped as read-only variables and
821 will be accessed using the <tt>cvar</tt> object described in the previous section. They
822 are not wrapped as constants. For further discussion about this, see the <a href="SWIG.html#SWIG">SWIG Basics</a> chapter.
826 Constants are not guaranteed to remain constant in Tcl---the value
827 of the constant could be accidentally reassigned.You will just have to be careful.
831 A peculiarity of installing constants as variables is that it is necessary to use the Tcl <tt>global</tt> statement to
832 access constants in procedure bodies. For example:
845 If a program relies on a lot of constants, this can be extremely annoying. To fix the problem, consider using the
846 following typemap rule:
851 %apply int CONSTANT { int x };
859 When applied to an input argument, the <tt>CONSTANT</tt> rule allows a constant to be passed to a function using
860 its actual value or a symbolic identifier name. For example:
872 When an identifier name is given, it is used to perform an implicit hash-table lookup of the value during argument
873 conversion. This allows the <tt>global</tt> statement to be omitted.
876 <H3><a name="Tcl_nn19"></a>33.3.5 Pointers</H3>
880 C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with
881 incomplete type information. Here is a rather simple interface:
888 FILE *fopen(const char *filename, const char *mode);
889 int fputs(const char *, FILE *);
895 When wrapped, you will be able to use the functions in a natural way from Tcl.
902 % set f [fopen junk w]
903 % fputs "Hello World\n" $f
909 If this makes you uneasy, rest assured that there is no
910 deep magic involved. Underneath the covers, pointers to C/C++ objects are
911 simply represented as opaque values--normally an encoded character
915 <div class="code"><pre>
922 This pointer value can be freely passed around to different C functions that
923 expect to receive an object of type <tt>FILE *</tt>. The only thing you can't do is
924 dereference the pointer from Tcl.
928 The NULL pointer is represented by the string <tt>NULL</tt>.
932 As much as you might be inclined to modify a pointer value directly
933 from Tcl, don't. The hexadecimal encoding is not necessarily the
934 same as the logical memory address of the underlying object. Instead
935 it is the raw byte encoding of the pointer value. The encoding will
936 vary depending on the native byte-ordering of the platform (i.e.,
937 big-endian vs. little-endian). Similarly, don't try to manually cast
938 a pointer to a new type by simply replacing the type-string. This
939 may not work like you expect and it is particularly dangerous when
940 casting C++ objects. If you need to cast a pointer or
941 change its value, consider writing some helper functions instead. For
949 Bar *FooToBar(Foo *f) {
954 Foo *BarToFoo(Bar *b) {
955 return dynamic_cast<Foo*>(b);
958 Foo *IncrFoo(Foo *f, int i) {
966 Also, if working with C++, you should always try
967 to use the new C++ style casts. For example, in the above code, the
968 C-style cast may return a bogus result whereas as the C++-style cast will return
969 <tt>None</tt> if the conversion can't be performed.
972 <H3><a name="Tcl_nn20"></a>33.3.6 Structures</H3>
976 If you wrap a C structure, it is wrapped by a Tcl interface that somewhat resembles a Tk widget.
977 This provides a very natural interface. For example,
980 <div class="code"><pre>
991 <div class="code"><pre>
993 % v configure -x 3.5 -y 7.2
994 % puts "[v cget -x] [v cget -y] [v cget -z]"
1000 Similar access is provided for unions and the data members of C++ classes.
1004 In the above example, <tt>v</tt> is a name that's used for the object. However,
1005 underneath the covers, there's a pointer to a raw C structure. This can be obtained
1006 by looking at the <tt>-this</tt> attribute. For example:
1011 % puts [v cget -this]
1017 Further details about the relationship between the Tcl and the underlying C structure
1018 are covered a little later.
1022 <tt>const</tt> members of a structure are read-only. Data members
1023 can also be forced to be read-only using the <tt>%immutable</tt> directive. For example:
1031 int x; /* Read-only members */
1040 When <tt>char *</tt> members of a structure are wrapped, the contents are assumed to be
1041 dynamically allocated using <tt>malloc</tt> or <tt>new</tt> (depending on whether or not
1042 SWIG is run with the -c++ option). When the structure member is set, the old contents will be
1043 released and a new value created. If this is not the behavior you want, you will have to use
1044 a typemap (described later).
1048 If a structure contains arrays, access to those arrays is managed through pointers. For
1049 example, consider this:
1061 If accessed in Tcl, you will see behavior like this:
1074 This pointer can be passed around to functions that expect to receive
1075 an <tt>int *</tt> (just like C). You can also set the value of an array member using
1076 another pointer. For example:
1082 % c configure -x [b cget -x] # Copy contents of b.x to c.x
1087 For array assignment, SWIG copies the entire contents of the array starting with the data pointed
1088 to by <tt>b.x</tt>. In this example, 16 integers would be copied. Like C, SWIG makes
1089 no assumptions about bounds checking---if you pass a bad pointer, you may get a segmentation
1090 fault or access violation.
1094 When a member of a structure is itself a structure, it is handled as a
1095 pointer. For example, suppose you have two structures like this:
1111 Now, suppose that you access the <tt>f</tt> attribute of <tt>Bar</tt> like this:
1122 In this case, <tt>x</tt> is a pointer that points to the <tt>Foo</tt> that is inside <tt>b</tt>.
1123 This is the same value as generated by this C code:
1129 Foo *x = &b->f; /* Points inside b */
1134 However, one peculiarity of accessing a substructure like this is that the returned
1135 value does work quite like you might expect. For example:
1143 invalid command name "x"
1148 This is because the returned value was not created in a normal way from the interpreter (x is
1149 not a command object). To make it function normally, just
1150 evaluate the variable like this:
1164 In this example, <tt>x</tt> points inside the original structure. This means that modifications
1165 work just like you would expect. For example:
1173 % $x configure -a 3 # Modifies contents of f (inside b)
1174 % [b cget -f] -configure -a 3 # Same thing
1179 In many of these structure examples, a simple name like "v" or "b" has been given
1180 to wrapped structures. If necessary, this name can be passed to functions
1181 that expect to receive an object. For example, if you have a function like this,
1191 you can call the function in Tcl as follows:
1196 % Foo x # Create a Foo object
1197 % blah x # Pass the object to a function
1202 It is also possible to call the function using the raw pointer value. For
1208 % blah [x cget -this] # Pass object to a function
1213 It is also possible to create and use objects using variables. For example:
1218 % set b [Bar] # Create a Bar
1219 % $b cget -f # Member access
1227 Finally, to destroy objects created from Tcl, you can either let the object
1228 name go out of scope or you can explicitly delete the object. For example:
1233 % Foo f # Create object f
1244 % Foo f # Create object f
1250 Note: Tcl only destroys the underlying object if it has ownership. See the
1251 memory management section that appears shortly.
1254 <H3><a name="Tcl_nn21"></a>33.3.7 C++ classes</H3>
1258 C++ classes are wrapped as an extension of structure wrapping. For example, if you have this class,
1261 <div class="code"><pre>
1266 int search(char *item);
1267 void insert(char *item);
1268 void remove(char *item);
1275 you can use it in Tcl like this:
1278 <div class="code"><pre>
1285 % puts [l cget -length]
1291 Class data members are accessed in the same manner as C structures.
1295 Static class members are accessed as global functions or variables.
1296 To illustrate, suppose you have a class like this:
1311 In Tcl, the static member is accessed as follows:
1316 % Spam_foo # Spam::foo()
1317 % puts $Spam_bar # Spam::bar
1321 <H3><a name="Tcl_nn22"></a>33.3.8 C++ inheritance</H3>
1325 SWIG is fully aware of issues related to C++ inheritance. Therefore, if you have
1335 class Bar : public Foo {
1342 An object of type <tt>Bar</tt> can be used where a <tt>Foo</tt> is expected. For
1343 example, if you have this function:
1353 then the function <tt>spam()</tt> accepts a <tt>Foo *</tt> or a pointer to any class derived from <tt>Foo</tt>.
1359 % Foo f # Create a Foo
1360 % Bar b # Create a Bar
1367 It is safe to use multiple inheritance with SWIG.
1370 <H3><a name="Tcl_nn23"></a>33.3.9 Pointers, references, values, and arrays</H3>
1374 In C++, there are many different ways a function might receive
1375 and manipulate objects. For example:
1380 void spam1(Foo *x); // Pass by pointer
1381 void spam2(Foo &x); // Pass by reference
1382 void spam3(Foo x); // Pass by value
1383 void spam4(Foo x[]); // Array of objects
1388 In Tcl, there is no detailed distinction like this.
1389 Because of this, SWIG unifies all of these types
1390 together in the wrapper code. For instance, if you actually had the
1391 above functions, it is perfectly legal to do this:
1396 % Foo f # Create a Foo
1397 % spam1 f # Ok. Pointer
1398 % spam2 f # Ok. Reference
1399 % spam3 f # Ok. Value.
1400 % spam4 f # Ok. Array (1 element)
1405 Similar behavior occurs for return values. For example, if you had
1406 functions like this,
1418 then all three functions will return a pointer to some <tt>Foo</tt> object.
1419 Since the third function (spam7) returns a value, newly allocated memory is used
1420 to hold the result and a pointer is returned (Tcl will release this memory
1421 when the return value is garbage collected).
1424 <H3><a name="Tcl_nn24"></a>33.3.10 C++ overloaded functions</H3>
1428 C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example,
1429 if you have two functions like this:
1440 You can use them in Tcl in a straightforward manner:
1446 % foo Hello # foo(char *c)
1451 Similarly, if you have a class like this,
1459 Foo(const Foo &);
1466 you can write Tcl code like this:
1471 % Foo f # Create a Foo
1477 Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG
1478 can't disambiguate. For example:
1495 void foo(Bar &b);
1500 If declarations such as these appear, you will get a warning message like this:
1505 example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)
1511 To fix this, you either need to ignore or rename one of the methods. For example:
1516 %rename(spam_short) spam(short);
1519 void spam(short); // Accessed as spam_short
1529 %ignore spam(short);
1532 void spam(short); // Ignored
1537 SWIG resolves overloaded functions and methods using a disambiguation scheme that ranks and sorts
1538 declarations according to a set of type-precedence rules. The order in which declarations appear
1539 in the input does not matter except in situations where ambiguity arises--in this case, the
1540 first declaration takes precedence.
1544 Please refer to the "SWIG and C++" chapter for more information about overloading.
1547 <H3><a name="Tcl_nn25"></a>33.3.11 C++ operators</H3>
1551 Certain C++ overloaded operators can be handled automatically by SWIG. For example,
1552 consider a class like this:
1559 double rpart, ipart;
1561 Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
1562 Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { }
1563 Complex &operator=(const Complex &c);
1564 Complex operator+(const Complex &c) const;
1565 Complex operator-(const Complex &c) const;
1566 Complex operator*(const Complex &c) const;
1567 Complex operator-() const;
1569 double re() const { return rpart; }
1570 double im() const { return ipart; }
1576 When wrapped, it works like this:
1592 It should be stressed that operators in SWIG have no relationship to operators
1593 in Tcl. In fact, the only thing that's happening here is that an operator like
1594 <tt>operator +</tt> has been renamed to a method <tt>+</tt>. Therefore, the
1595 statement <tt>[c + d]</tt> is really just invoking the <tt>+</tt> method on <tt>c</tt>.
1596 When more than operator is defined (with different arguments), the standard
1597 method overloading facilities are used. Here is a rather odd looking example:
1604 % set e [c - d] # operator-(const Complex &)
1605 % puts "[$e re] [$e im]"
1607 % set f [c -] # operator-()
1608 % puts "[$f re] [$f im]"
1615 One restriction with operator overloading support is that SWIG is not
1616 able to fully handle operators that aren't defined as part of the class.
1617 For example, if you had code like this
1624 friend Complex operator+(double, const Complex &c);
1631 then SWIG doesn't know what to do with the friend function--in fact,
1632 it simply ignores it and issues a warning. You can still wrap the operator,
1633 but you may have to encapsulate it in a special function. For example:
1638 %rename(Complex_add_dc) operator+(double, const Complex &);
1640 Complex operator+(double, const Complex &c);
1645 There are ways to make this operator appear as part of the class using the <tt>%extend</tt> directive.
1649 <H3><a name="Tcl_nn26"></a>33.3.12 C++ namespaces</H3>
1653 SWIG is aware of C++ namespaces, but namespace names do not appear in
1654 the module nor do namespaces result in a module that is broken up into
1655 submodules or packages. For example, if you have a file like this,
1672 it works in Tcl as follows:
1681 % v configure -x 3.4
1686 If your program has more than one namespace, name conflicts (if any) can be resolved using <tt>%rename</tt>
1692 %rename(Bar_spam) Bar::spam;
1705 If you have more than one namespace and your want to keep their
1706 symbols separate, consider wrapping them as separate SWIG modules.
1707 For example, make the module name the same as the namespace and create
1708 extension modules for each namespace separately. If your program
1709 utilizes thousands of small deeply nested namespaces each with
1710 identical symbol names, well, then you get what you deserve.
1713 <H3><a name="Tcl_nn27"></a>33.3.13 C++ templates</H3>
1717 C++ templates don't present a huge problem for SWIG. However, in order
1718 to create wrappers, you have to tell SWIG to create wrappers for a particular
1719 template instantiation. To do this, you use the <tt>%template</tt> directive.
1730 template<class T1, class T2>
1732 typedef T1 first_type;
1733 typedef T2 second_type;
1737 pair(const T1&, const T2&);
1741 %template(pairii) pair<int,int>;
1760 Obviously, there is more to template wrapping than shown in this example.
1761 More details can be found in the <a href="SWIGPlus.html#SWIGPlus">SWIG and C++</a> chapter. Some more complicated
1762 examples will appear later.
1765 <H3><a name="Tcl_nn28"></a>33.3.14 C++ Smart Pointers</H3>
1769 In certain C++ programs, it is common to use classes that have been wrapped by
1770 so-called "smart pointers." Generally, this involves the use of a template class
1771 that implements <tt>operator->()</tt> like this:
1776 template<class T> class SmartPtr {
1785 Then, if you have a class like this,
1799 A smart pointer would be used in C++ as follows:
1804 SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown)
1806 p->x = 3; // Foo::x
1807 int y = p->bar(); // Foo::bar
1812 To wrap this in Tcl, simply tell SWIG about the <tt>SmartPtr</tt> class and the low-level
1813 <tt>Foo</tt> object. Make sure you instantiate <tt>SmartPtr</tt> using <tt>%template</tt> if necessary.
1821 %template(SmartPtrFoo) SmartPtr<Foo>;
1827 Now, in Tcl, everything should just "work":
1832 % set p [CreateFoo] # Create a smart-pointer somehow
1833 % $p configure -x 3 # Foo::x
1839 If you ever need to access the underlying pointer returned by <tt>operator->()</tt> itself,
1840 simply use the <tt>__deref__()</tt> method. For example:
1845 % set f [$p __deref__] # Returns underlying Foo *
1849 <H2><a name="Tcl_nn29"></a>33.4 Further details on the Tcl class interface</H2>
1853 In the previous section, a high-level view of Tcl wrapping was
1854 presented. A key component of this wrapping is that structures and
1855 classes are wrapped by Tcl class-like objects. This provides a very
1856 natural Tcl interface and allows SWIG to support a number of
1857 advanced features such as operator overloading. However, a number
1858 of low-level details were omitted. This section provides a brief overview
1859 of how the proxy classes work.
1862 <H3><a name="Tcl_nn30"></a>33.4.1 Proxy classes</H3>
1866 In the <a href="SWIG.html#SWIG">"SWIG basics"</a> and <a href="SWIGPlus.html#SWIGPlus">"SWIG and C++"</a> chapters,
1867 details of low-level structure and class wrapping are described. To summarize those chapters, if you
1868 have a class like this
1882 then SWIG transforms it into a set of low-level procedural wrappers. For example:
1890 void delete_Foo(Foo *f) {
1893 int Foo_x_get(Foo *f) {
1896 void Foo_x_set(Foo *f, int value) {
1899 int Foo_spam(Foo *f, int arg1) {
1900 return f->spam(arg1);
1906 These wrappers are actually found in the Tcl extension module. For example, you can certainly do this:
1922 However, in addition to this, the classname <tt>Foo</tt> is used as an object constructor
1923 function. This allows objects to be encapsulated objects that look a lot like Tk widgets
1924 as shown in the last section.
1927 <H3><a name="Tcl_nn31"></a>33.4.2 Memory management</H3>
1931 Associated with each wrapped object, is an ownership flag <tt>thisown</tt> The value of this
1932 flag determines who is responsible for deleting the underlying C++ object. If set to 1,
1933 the Tcl interpreter destroys the C++ object when the proxy class is
1934 garbage collected. If set to 0 (or if the attribute is missing), then the destruction
1935 of the proxy class has no effect on the C++ object.
1939 When an object is created by a constructor or returned by value, Tcl automatically takes
1940 ownership of the result. For example:
1969 On the other hand, when pointers are returned to Tcl, there is often no way to know where
1970 they came from. Therefore, the ownership is set to zero. For example:
1997 This behavior is especially important for classes that act as
1998 containers. For example, if a method returns a pointer to an object
1999 that is contained inside another object, you definitely don't want
2000 Tcl to assume ownership and destroy it!
2004 Related to containers, ownership issues can arise whenever an object is assigned to a member
2005 or global variable. For example, consider this interface:
2022 When wrapped in Tcl, careful observation will reveal that ownership changes whenever an object
2023 is assigned to a global variable. For example:
2038 In this case, C is now holding a reference to the object---you probably don't want Tcl to destroy it.
2039 Similarly, this occurs for members. For example:
2050 % f configure -next g
2058 For the most part, memory management issues remain hidden. However,
2059 there are occasionally situations where you might have to manually
2060 change the ownership of an object. For instance, consider code like this:
2068 void set_value(Object *v) { value = v; }
2075 Now, consider the following Tcl code:
2080 % Object v # Create an object
2081 % Node n # Create a node
2082 % n setvalue v # Set value
2090 In this case, the object <tt>n</tt> is holding a reference to
2091 <tt>v</tt> internally. However, SWIG has no way to know that this
2092 has occurred. Therefore, Tcl still thinks that it has ownership of the
2093 object. Should the proxy object be destroyed, then the C++ destructor
2094 will be invoked and <tt>n</tt> will be holding a stale-pointer. If
2095 you're lucky, you will only get a segmentation fault.
2099 To work around this, it is always possible to flip the ownership flag. For example,
2104 % v -disown # Give ownership to C/C++
2105 % v -acquire # Acquire ownership
2110 It is also possible to deal with situations like this using
2111 typemaps--an advanced topic discussed later.
2115 <H2><a name="Tcl_nn32"></a>33.5 Input and output parameters</H2>
2119 A common problem in some C programs is handling parameters passed as simple pointers. For
2125 void add(int x, int y, int *result) {
2137 int sub(int *x, int *y) {
2144 The easiest way to handle these situations is to use the <tt>typemaps.i</tt> file. For example:
2150 %include "typemaps.i"
2152 void add(int, int, int *OUTPUT);
2153 int sub(int *INPUT, int *INPUT);
2158 In Tcl, this allows you to pass simple values instead of pointer. For example:
2170 Notice how the <tt>INPUT</tt> parameters allow integer values to be passed instead of pointers
2171 and how the <tt>OUTPUT</tt> parameter creates a return result.
2175 If you don't want to use the names <tt>INPUT</tt> or <tt>OUTPUT</tt>, use the <tt>%apply</tt>
2176 directive. For example:
2182 %include "typemaps.i"
2184 %apply int *OUTPUT { int *result };
2185 %apply int *INPUT { int *x, int *y};
2187 void add(int x, int y, int *result);
2188 int sub(int *x, int *y);
2193 If a function mutates one of its parameters like this,
2198 void negate(int *x) {
2205 you can use <tt>INOUT</tt> like this:
2210 %include "typemaps.i"
2212 void negate(int *INOUT);
2217 In Tcl, a mutated parameter shows up as a return value. For example:
2229 The most common use of these special typemap rules is to handle functions that
2230 return more than one value. For example, sometimes a function returns a result
2231 as well as a special error code:
2236 /* send message, return number of bytes sent, along with success code */
2237 int send_message(char *text, int len, int *success);
2242 To wrap such a function, simply use the <tt>OUTPUT</tt> rule above. For example:
2248 %include "typemaps.i"
2249 %apply int *OUTPUT { int *success };
2251 int send_message(char *text, int *success);
2256 When used in Tcl, the function will return multiple values as a list.
2261 set r [send_message "Hello World"]
2262 set bytes [lindex $r 0]
2263 set success [lindex $r 1]
2268 Another common use of multiple return values are in query functions. For example:
2273 void get_dimensions(Matrix *m, int *rows, int *columns);
2278 To wrap this, you might use the following:
2284 %include "typemaps.i"
2285 %apply int *OUTPUT { int *rows, int *columns };
2287 void get_dimensions(Matrix *m, int *rows, *columns);
2297 set dim [get_dimensions $m]
2298 set r [lindex $dim 0]
2299 set c [lindex $dim 1]
2303 <H2><a name="Tcl_nn33"></a>33.6 Exception handling </H2>
2307 The <tt>%exception</tt> directive can be used to create a user-definable
2308 exception handler in charge of converting exceptions in your C/C++
2309 program into Tcl exceptions. The chapter on customization features
2310 contains more details, but suppose you extended the array example into
2311 a C++ class like the following :
2314 <div class="code"><pre>
2315 class RangeError {}; // Used for an exception
2322 // Create a new array of fixed size
2323 DoubleArray(int size) {
2324 ptr = new double[size];
2331 // Return the length of the array
2336 // Get an item from the array and perform bounds checking.
2337 double getitem(int i) {
2338 if ((i >= 0) && (i < n))
2344 // Set an item in the array and perform bounds checking.
2345 void setitem(int i, double val) {
2346 if ((i >= 0) && (i < n))
2356 The functions associated with this class can throw a C++ range
2357 exception for an out-of-bounds array access. We can catch this in our
2358 Tcl extension by specifying the following in an interface file :
2361 <div class="code"><pre>
2364 $action // Gets substituted by actual function call
2366 catch (RangeError) {
2367 Tcl_SetStringObj(tcl_result,"Array index out-of-bounds");
2374 As shown, the exception handling code will be added to every wrapper function.
2375 Since this is somewhat inefficient. You might consider refining the
2376 exception handler to only apply to specific methods like this:
2381 %exception getitem {
2385 catch (RangeError) {
2386 Tcl_SetStringObj(tcl_result,"Array index out-of-bounds");
2391 %exception setitem {
2395 catch (RangeError) {
2396 Tcl_SetStringObj(tcl_result,"Array index out-of-bounds");
2404 In this case, the exception handler is only attached to methods and functions
2405 named <tt>getitem</tt> and <tt>setitem</tt>.
2409 If you had a lot of different methods, you can avoid extra typing by using a macro.
2420 catch (RangeError) {
2421 Tcl_SetStringObj(tcl_result,"Array index out-of-bounds");
2427 %exception getitem RANGE_ERROR;
2428 %exception setitem RANGE_ERROR;
2433 Since SWIG's exception handling is user-definable, you are not limited to C++ exception handling.
2434 See the chapter on "<a href="Customization.html#Customization">Customization Features</a>" for more examples.
2437 <H2><a name="Tcl_nn34"></a>33.7 Typemaps</H2>
2441 This section describes how you can modify SWIG's default wrapping behavior
2442 for various C/C++ datatypes using the <tt>%typemap</tt> directive. This
2443 is an advanced topic that assumes familiarity with the Tcl C API as well
2444 as the material in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
2448 Before proceeding, it should be stressed that typemaps are not a required
2449 part of using SWIG---the default wrapping behavior is enough in most cases.
2450 Typemaps are only used if you want to change some aspect of the primitive
2454 <H3><a name="Tcl_nn35"></a>33.7.1 What is a typemap?</H3>
2458 A typemap is nothing more than a code generation rule that is attached to
2459 a specific C datatype. For example, to convert integers from Tcl to C,
2460 you might define a typemap like this:
2463 <div class="code"><pre>
2467 if (Tcl_GetIntFromObj(interp,$input,&$1) == TCL_ERROR) return TCL_ERROR;
2468 printf("Received an integer : %d\n",$1);
2471 extern int fact(int n);
2476 Typemaps are always associated with some specific aspect of code generation.
2477 In this case, the "in" method refers to the conversion of input arguments
2478 to C/C++. The datatype <tt>int</tt> is the datatype to which the typemap
2479 will be applied. The supplied C code is used to convert values. In this
2480 code a number of special variable prefaced by a <tt>$</tt> are used. The
2481 <tt>$1</tt> variable is placeholder for a local variable of type <tt>int</tt>.
2482 The <tt>$input</tt> variable is the input object of type <tt>Tcl_Obj *</tt>.
2486 When this example is compiled into a Tcl module, it operates as follows:
2489 <div class="code"><pre>
2492 Received an integer : 6
2497 In this example, the typemap is applied to all occurrences of the <tt>int</tt> datatype.
2498 You can refine this by supplying an optional parameter name. For example:
2501 <div class="code"><pre>
2504 %typemap(in) int n {
2505 if (Tcl_GetIntFromObj(interp,$input,&$1) == TCL_ERROR) return TCL_ERROR;
2506 printf("n = %d\n",$1);
2509 extern int fact(int n);
2514 In this case, the typemap code is only attached to arguments that exactly match <tt>int n</tt>.
2518 The application of a typemap to specific datatypes and argument names involves
2519 more than simple text-matching--typemaps are fully integrated into the
2520 SWIG type-system. When you define a typemap for <tt>int</tt>, that typemap
2521 applies to <tt>int</tt> and qualified variations such as <tt>const int</tt>. In addition,
2522 the typemap system follows <tt>typedef</tt> declarations. For example:
2527 %typemap(in) int n {
2528 if (Tcl_GetIntFromObj(interp,$input,&$1) == TCL_ERROR) return TCL_ERROR;
2529 printf("n = %d\n",$1);
2532 typedef int Integer;
2533 extern int fact(Integer n); // Above typemap is applied
2539 However, the matching of <tt>typedef</tt> only occurs in one direction. If you
2540 defined a typemap for <tt>Integer</tt>, it is not applied to arguments of
2545 Typemaps can also be defined for groups of consecutive arguments. For example:
2550 %typemap(in) (char *str, int len) {
2551 $1 = Tcl_GetStringFromObj($input,&$2);
2554 int count(char c, char *str, int len);
2559 When a multi-argument typemap is defined, the arguments are always handled as a single
2560 Tcl object. This allows the function to be used like this (notice how the length
2561 parameter is omitted):
2566 % count e "Hello World"
2571 <H3><a name="Tcl_nn36"></a>33.7.2 Tcl typemaps</H3>
2575 The previous section illustrated an "in" typemap for converting Tcl objects to C.
2576 A variety of different typemap methods are defined by the Tcl module. For example,
2577 to convert a C integer back into a Tcl object, you might define an "out" typemap
2584 Tcl_SetObjResult(interp,Tcl_NewIntObj($1));
2590 The following list details all of the typemap methods that can be used by the Tcl module:
2594 <tt>%typemap(in)</tt>
2597 <div class="indent">
2598 Converts Tcl objects to input function arguments
2602 <tt>%typemap(out)</tt>
2605 <div class="indent">
2606 Converts return value of a C function to a Tcl object
2610 <tt>%typemap(varin)</tt>
2613 <div class="indent">
2614 Assigns a C global variable from a Tcl object
2618 <tt>%typemap(varout)</tt>
2621 <div class="indent">
2622 Returns a C global variable as a Tcl object
2626 <tt>%typemap(freearg)</tt>
2629 <div class="indent">
2630 Cleans up a function argument (if necessary)
2634 <tt>%typemap(argout)</tt>
2637 <div class="indent">
2638 Output argument processing
2642 <tt>%typemap(ret)</tt>
2645 <div class="indent">
2646 Cleanup of function return values
2650 <tt>%typemap(consttab)</tt>
2653 <div class="indent">
2654 Creation of Tcl constants (constant table)
2658 <tt>%typemap(constcode)</tt>
2661 <div class="indent">
2662 Creation of Tcl constants (init function)
2666 <tt>%typemap(memberin)</tt>
2669 <div class="indent">
2670 Setting of structure/class member data
2674 <tt>%typemap(globalin)</tt>
2677 <div class="indent">
2678 Setting of C global variables
2682 <tt>%typemap(check)</tt>
2685 <div class="indent">
2686 Checks function input values.
2690 <tt>%typemap(default)</tt>
2693 <div class="indent">
2694 Set a default value for an argument (making it optional).
2698 <tt>%typemap(arginit)</tt>
2701 <div class="indent">
2702 Initialize an argument to a value before any conversions occur.
2706 Examples of these methods will appear shortly.
2709 <H3><a name="Tcl_nn37"></a>33.7.3 Typemap variables</H3>
2713 Within typemap code, a number of special variables prefaced with a <tt>$</tt> may appear.
2714 A full list of variables can be found in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
2715 This is a list of the most common variables:
2722 <div class="indent">
2723 A C local variable corresponding to the actual type specified in the
2724 <tt>%typemap</tt> directive. For input values, this is a C local variable
2725 that's supposed to hold an argument value. For output values, this is
2726 the raw result that's supposed to be returned to Tcl.
2733 <div class="indent">
2734 A <tt>Tcl_Obj *</tt> holding a raw Tcl object with an argument or variable value.
2741 <div class="indent">
2742 A <tt>Tcl_Obj *</tt> that holds the result to be returned to Tcl.
2749 <div class="indent">
2750 The parameter name that was matched.
2757 <div class="indent">
2758 The actual C datatype matched by the typemap.
2765 <div class="indent">
2766 An assignable version of the datatype matched by the typemap (a type that can appear on the left-hand-side of
2767 a C assignment operation). This type is stripped of qualifiers and may be an altered version of <tt>$1_type</tt>.
2768 All arguments and local variables in wrapper functions are declared using this type so that their values can be
2776 <div class="indent">
2777 The Tcl name of the wrapper function being created.
2780 <H3><a name="Tcl_nn38"></a>33.7.4 Converting a Tcl list to a char ** </H3>
2784 A common problem in many C programs is the processing of command line
2785 arguments, which are usually passed in an array of NULL terminated
2786 strings. The following SWIG interface file allows a Tcl list to be
2787 used as a <tt>char **</tt> object.
2790 <div class="code"><pre>
2793 // This tells SWIG to treat char ** as a special case
2794 %typemap(in) char ** {
2798 if (Tcl_ListObjGetElements(interp, $input, &nitems, &listobjv) == TCL_ERROR) {
2801 $1 = (char **) malloc((nitems+1)*sizeof(char *));
2802 for (i = 0; i < nitems; i++) {
2803 $1[i] = Tcl_GetStringFromObj(listobjv[i],0);
2808 // This gives SWIG some cleanup code that will get called after the function call
2809 %typemap(freearg) char ** {
2815 // Now a test functions
2817 int print_args(char **argv) {
2820 printf("argv[%d] = %s\n", i,argv[i]);
2834 <div class="code"><pre>
2835 % print_args {John Guido Larry}
2842 <H3><a name="Tcl_nn39"></a>33.7.5 Returning values in arguments</H3>
2846 The "argout" typemap can be used to return a value originating from a
2847 function argument. For example :
2850 <div class="code"><pre>
2851 // A typemap defining how to return an argument by appending it to the result
2852 %typemap(argout) double *outvalue {
2853 Tcl_Obj *o = Tcl_NewDoubleObj($1);
2854 Tcl_ListObjAppendElement(interp,$result,o);
2857 // A typemap telling SWIG to ignore an argument for input
2858 // However, we still need to pass a pointer to the C function
2859 %typemap(in,numinputs=0) double *outvalue (double temp) {
2863 // Now a function returning two values
2864 int mypow(double a, double b, double *outvalue) {
2865 if ((a < 0) || (b < 0)) return -1;
2866 *outvalue = pow(a,b);
2872 When wrapped, SWIG matches the <tt>argout</tt> typemap to the
2873 "<tt>double *outvalue</tt>" argument. The numinputs=0 specification tells SWIG
2874 to simply ignore this argument when generating wrapper code. As a
2875 result, a Tcl function using these typemaps will work like this :
2878 <div class="code"><pre>
2879 % mypow 2 3 # Returns two values, a status value and the result
2884 <H3><a name="Tcl_nn40"></a>33.7.6 Useful functions</H3>
2888 The following tables provide some functions that may be useful in
2889 writing Tcl typemaps.
2898 Tcl_Obj *Tcl_NewIntObj(int Value);
2899 void Tcl_SetIntObj(Tcl_Obj *obj, int Value);
2900 int Tcl_GetIntFromObj(Tcl_Interp *, Tcl_Obj *obj, int *ip);
2905 <b>Floating Point</b>
2910 Tcl_Obj *Tcl_NewDoubleObj(double Value);
2911 void Tcl_SetDoubleObj(Tcl_Obj *obj, double value);
2912 int Tcl_GetDoubleFromObj(Tcl_Interp *, Tcl_Obj *o, double *dp);
2922 Tcl_Obj *Tcl_NewStringObj(char *str, int len);
2923 void Tcl_SetStringObj(Tcl_Obj *obj, char *str, int len);
2924 char *Tcl_GetStringFromObj(Tcl_Obj *obj, int *len);
2925 void Tcl_AppendToObj(Tcl_Obj *obj, char *str, int len);
2935 Tcl_Obj *Tcl_NewListObj(int objc, Tcl_Obj *objv);
2936 int Tcl_ListObjAppendList(Tcl_Interp *, Tcl_Obj *listPtr, Tcl_Obj *elemListPtr);
2937 int Tcl_ListObjAppendElement(Tcl_Interp *, Tcl_Obj *listPtr, Tcl_Obj *element);
2938 int Tcl_ListObjGetElements(Tcl_Interp *, Tcl_Obj *listPtr, int *objcPtr,
2939 Tcl_Obj ***objvPtr);
2940 int Tcl_ListObjLength(Tcl_Interp *, Tcl_Obj *listPtr, int *intPtr);
2941 int Tcl_ListObjIndex(Tcl_Interp *, Tcl_Obj *listPtr, int index,
2942 Tcl_Obj_Obj **objptr);
2943 int Tcl_ListObjReplace(Tcl_Interp *, Tcl_Obj *listPtr, int first, int count,
2944 int objc, Tcl_Obj *objv);
2954 Tcl_Obj *Tcl_DuplicateObj(Tcl_Obj *obj);
2955 void Tcl_IncrRefCount(Tcl_Obj *obj);
2956 void Tcl_DecrRefCount(Tcl_Obj *obj);
2957 int Tcl_IsShared(Tcl_Obj *obj);
2961 <H3><a name="Tcl_nn41"></a>33.7.7 Standard typemaps</H3>
2965 The following typemaps show how to convert a few common kinds of
2966 objects between Tcl and C (and to give a better idea of how typemaps
2972 <b>Integer conversion</b>
2977 %typemap(in) int, short, long {
2979 if (Tcl_GetIntFromObj(interp, $input, &temp) == TCL_ERROR)
2981 $1 = ($1_ltype) temp;
2990 %typemap(out) int, short, long {
2991 Tcl_SetIntObj($result,(int) $1);
2997 <b>Floating point conversion</b>
3002 %typemap(in) float, double {
3004 if (Tcl_GetDoubleFromObj(interp, $input, &temp) == TCL_ERROR)
3006 $1 = ($1_ltype) temp;
3015 %typemap(out) float, double {
3016 Tcl_SetDoubleObj($result, $1);
3022 <b>String Conversion</b>
3027 %typemap(in) char * {
3029 $1 = Tcl_GetStringFromObj(interp, &len);
3039 %typemap(out) char * {
3040 Tcl_SetStringObj($result,$1);
3045 <H3><a name="Tcl_nn42"></a>33.7.8 Pointer handling</H3>
3049 SWIG pointers are mapped into Tcl strings containing the
3050 hexadecimal value and type. The following functions can be used to
3051 create and read pointer values.
3056 int SWIG_ConvertPtr(Tcl_Obj *obj, void **ptr, swig_type_info *ty, int flags)</tt>
3059 <div class="indent">
3060 Converts a Tcl object <tt>obj</tt> to a C pointer. The result of the conversion is placed
3061 into the pointer located at <tt>ptr</tt>. <tt>ty</tt> is a SWIG type descriptor structure.
3062 <tt>flags</tt> is used to handle error checking and other aspects of conversion. It is currently
3063 reserved for future expansion. Returns 0 on success and -1 on error.
3068 Tcl_Obj *SWIG_NewPointerObj(void *ptr, swig_type_info *ty, int flags)</tt>
3071 <div class="indent">
3072 Creates a new Tcl pointer object. <tt>ptr</tt> is the pointer to convert, <tt>ty</tt> is the SWIG type descriptor structure that
3073 describes the type, and <tt>own</tt> is a flag reserved for future expansion.
3077 Both of these functions require the use of a special SWIG
3078 type-descriptor structure. This structure contains information about
3079 the mangled name of the datatype, type-equivalence information, as
3080 well as information about converting pointer values under C++
3081 inheritance. For a type of <tt>Foo *</tt>, the type descriptor structure
3082 is usually accessed as follows:
3085 <div class="indent">
3088 if (SWIG_ConvertPtr($input, (void **) &f, SWIGTYPE_p_Foo, 0) == -1) return NULL;
3091 obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
3096 In a typemap, the type descriptor should always be accessed using the special typemap
3097 variable <tt>$1_descriptor</tt>. For example:
3100 <div class="indent">
3102 %typemap(in) Foo * {
3103 if ((SWIG_ConvertPtr($input,(void **) &$1, $1_descriptor,0)) == -1) return NULL;
3109 If necessary, the descriptor for any type can be obtained using the <tt>$descriptor()</tt> macro in a typemap.
3113 <div class="indent">
3115 %typemap(in) Foo * {
3116 if ((SWIG_ConvertPtr($input,(void **) &$1, $descriptor(Foo *), 0)) == -1) return NULL;
3121 <H2><a name="Tcl_nn43"></a>33.8 Turning a SWIG module into a Tcl Package.</H2>
3125 Tcl 7.4 introduced the idea of an extension package. By default, SWIG
3126 generates all of the code necessary to create a package. To set the package version,
3127 simply use the <tt>-pkgversion</tt> option. For example:
3132 % swig -tcl -pkgversion 2.3 example.i
3137 After building the SWIG generated module, you need to execute
3138 the "<tt>pkg_mkIndex</tt>" command inside tclsh. For example :
3141 <div class="code"><pre>
3143 % pkg_mkIndex . example.so
3148 This creates a file "<tt>pkgIndex.tcl</tt>" with information about the
3149 package. To use your package, you now need to move it to its own
3150 subdirectory which has the same name as the package. For example :
3153 <div class="code"><pre>
3155 pkgIndex.tcl # The file created by pkg_mkIndex
3156 example.so # The SWIG generated module
3160 Finally, assuming that you're not entirely confused at this point,
3161 make sure that the example subdirectory is visible from the
3162 directories contained in either the <tt>tcl_library</tt> or
3163 <tt>auto_path</tt> variables. At this point you're ready to use the
3164 package as follows :
3167 <div class="code"><pre>
3169 % package require example
3176 If you're working with an example in the current directory and this doesn't work, do this instead :
3179 <div class="code"><pre>
3181 % lappend auto_path .
3182 % package require example
3188 As a final note, most SWIG examples do not yet use the
3189 <tt>package</tt> commands. For simple extensions it may be easier just
3190 to use the <tt>load</tt> command instead.
3193 <H2><a name="Tcl_nn44"></a>33.9 Building new kinds of Tcl interfaces (in Tcl)</H2>
3197 One of the most interesting aspects of Tcl and SWIG is that you can
3198 create entirely new kinds of Tcl interfaces in Tcl using the low-level
3199 SWIG accessor functions. For example, suppose you had a library of
3200 helper functions to access arrays :
3203 <div class="code"><pre>
3204 /* File : array.i */
3208 double *new_double(int size) {
3209 return (double *) malloc(size*sizeof(double));
3211 void delete_double(double *a) {
3214 double get_double(double *a, int index) {
3217 void set_double(double *a, int index, double val) {
3220 int *new_int(int size) {
3221 return (int *) malloc(size*sizeof(int));
3223 void delete_int(int *a) {
3226 int get_int(int *a, int index) {
3229 int set_int(int *a, int index, int val) {
3237 While these could be called directly, we could also write a Tcl script
3241 <div class="code"><pre>
3242 proc Array {type size} {
3243 set ptr [new_$type $size]
3245 set method [lindex $args 0]
3246 set parms [concat $ptr [lrange $args 1 end]]
3248 get {return [eval "get_$type $parms"]}
3249 set {return [eval "set_$type $parms"]}
3250 delete {eval "delete_$type $ptr; rename $ptr {}"}
3253 # Create a procedure
3254 uplevel "proc $ptr args {set ptr $ptr; set type $type;$code}"
3260 Our script allows easy array access as follows :
3263 <div class="code"><pre>
3264 set a [Array double 100] ;# Create a double [100]
3265 for {set i 0} {$i < 100} {incr i 1} { ;# Clear the array
3268 $a set 3 3.1455 ;# Set an individual element
3269 set b [$a get 10] ;# Retrieve an element
3271 set ia [Array int 50] ;# Create an int[50]
3272 for {set i 0} {$i < 50} {incr i 1} { ;# Clear it
3275 $ia set 3 7 ;# Set an individual element
3276 set ib [$ia get 10] ;# Get an individual element
3278 $a delete ;# Destroy a
3279 $ia delete ;# Destroy ia
3283 The cool thing about this approach is that it makes a common interface
3284 for two different types of arrays. In fact, if we were to add more C
3285 datatypes to our wrapper file, the Tcl code would work with those as
3286 well--without modification. If an unsupported datatype was requested,
3287 the Tcl code would simply return with an error so there is very little
3288 danger of blowing something up (although it is easily accomplished
3289 with an out of bounds array access).
3292 <H3><a name="Tcl_nn45"></a>33.9.1 Proxy classes</H3>
3296 A similar approach can be applied to proxy classes (also known as
3297 shadow classes). The following
3298 example is provided by Erik Bierwagen and Paul Saxe. To use it, run
3299 SWIG with the <tt>-noobject</tt> option (which disables the builtin
3300 object oriented interface). When running Tcl, simply source this
3301 file. Now, objects can be used in a more or less natural fashion.
3304 <div class="code"><pre>
3306 # Provides a simple object oriented interface using
3307 # SWIG's low level interface.
3310 proc new {objectType handle_r args} {
3311 # Creates a new SWIG object of the given type,
3312 # returning a handle in the variable "handle_r".
3314 # Also creates a procedure for the object and a trace on
3315 # the handle variable that deletes the object when the
3316 # handle variable is overwritten or unset
3317 upvar $handle_r handle
3319 # Create the new object
3321 eval set handle \[new_$objectType $args\]
3323 # Set up the object procedure
3325 proc $handle {cmd args} "eval ${objectType}_\$cmd $handle \$args"
3329 uplevel trace variable $handle_r uw "{deleteObject $objectType $handle}"
3331 # Return the handle so that 'new' can be used as an argument to a procedure
3336 proc deleteObject {objectType handle name element op} {
3338 # Check that the object handle has a reasonable form
3340 if {![regexp {_[0-9a-f]*_(.+)_p} $handle]} {
3341 error "deleteObject: not a valid object handle: $handle"
3344 # Remove the object procedure
3346 catch {rename $handle {}}
3350 delete_$objectType $handle
3353 proc delete {handle_r} {
3355 # A synonym for unset that is more familiar to C++ programmers
3357 uplevel unset $handle_r
3362 To use this file, we simply source it and execute commands such as
3363 "new" and "delete" to manipulate objects. For example :
3366 <div class="code"><pre>
3373 // Very simple C++ example
3377 List(); // Create a new list
3378 ~List(); // Destroy a list
3379 int search(char *value);
3380 void insert(char *); // Insert a new item into the list
3381 void remove(char *); // Remove item from list
3382 char *get(int n); // Get the nth item in the list
3383 int length; // The current length of the list
3384 static void print(List *l); // Print out the contents of the list
3389 Now a Tcl script using the interface...
3392 <div class="code"><pre>
3393 load ./list.so list ; # Load the module
3394 source swig_c++.tcl ; # Source the object file
3407 The cool thing about this example is that it works with any C++ object
3408 wrapped by SWIG and requires no special compilation. Proof that a
3409 short, but clever Tcl script can be combined with SWIG to do many
3413 <H2><a name="Tcl_nn46"></a>33.10 Tcl/Tk Stubs</H2>
3417 For background information about the Tcl Stubs feature, see
3418 <a href="http://www.tcl.tk/doc/howto/stubs.html">http://www.tcl.tk/doc/howto/stubs.html</a>.
3422 As of SWIG 1.3.10, the generated C/C++ wrapper will use the Tcl Stubs
3423 feature if compiled with <tt>-DUSE_TCL_STUBS</tt>.
3427 As of SWIG 1.3.40, the generated C/C++ wrapper will use the Tk Stubs
3428 feature if compiled with <tt>-DUSE_TK_STUBS</tt>. Also, you can override
3429 the minimum version to support which is passed to <tt>Tcl_InitStubs()</tt>
3430 and <tt>Tk_InitStubs()</tt> with <tt>-DSWIG_TCL_STUBS_VERSION="8.3"</tt>
3431 or the version being compiled with using
3432 <tt>-DSWIG_TCL_STUBS_VERSION=TCL_VERSION</tt>.