import source from 1.3.40
[external/swig.git] / Doc / Manual / Tcl.html
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <html>
3 <head>
4 <title>SWIG and Tcl</title>
5 <link rel="stylesheet" type="text/css" href="style.css">
6 </head>
7
8 <body bgcolor="#ffffff">
9 <H1><a name="Tcl"></a>33 SWIG and Tcl</H1>
10 <!-- INDEX -->
11 <div class="sectiontoc">
12 <ul>
13 <li><a href="#Tcl_nn2">Preliminaries</a>
14 <ul>
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>
23 </ul>
24 <li><a href="#Tcl_nn11">Building Tcl/Tk Extensions under Windows 95/NT</a>
25 <ul>
26 <li><a href="#Tcl_nn12">Running SWIG from Developer Studio</a>
27 <li><a href="#Tcl_nn13">Using NMAKE</a>
28 </ul>
29 <li><a href="#Tcl_nn14">A tour of basic C/C++ wrapping</a>
30 <ul>
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>
45 </ul>
46 <li><a href="#Tcl_nn29">Further details on the Tcl class interface</a>
47 <ul>
48 <li><a href="#Tcl_nn30">Proxy classes</a>
49 <li><a href="#Tcl_nn31">Memory management</a>
50 </ul>
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>
54 <ul>
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>
63 </ul>
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>
66 <ul>
67 <li><a href="#Tcl_nn45">Proxy classes</a>
68 </ul>
69 <li><a href="#Tcl_nn46">Tcl/Tk Stubs</a>
70 </ul>
71 </div>
72 <!-- INDEX -->
73
74
75
76 <p>
77 <b>Caution: This chapter is under repair!</b>
78 </p>
79
80 <p>
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.
84 </p>
85
86 <H2><a name="Tcl_nn2"></a>33.1 Preliminaries</H2>
87
88
89 <p>
90 To build a Tcl module, run SWIG using the <tt>-tcl</tt> option :
91 </p>
92
93 <div class="code"><pre>
94 $ swig -tcl example.i
95 </pre></div>
96
97 <p>
98 If building a C++ extension, add the <tt>-c++</tt> option:
99 </p>
100
101 <div class="code"><pre>
102 $ swig -c++ -tcl example.i
103 </pre></div>
104
105 <p>
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.
110 </p>
111
112 <H3><a name="Tcl_nn3"></a>33.1.1 Getting the right header files</H3>
113
114
115 <p>
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
118 </p>
119
120 <div class="code"><pre>
121 /usr/local/include
122 </pre></div>
123
124 <p>
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
127 header file.
128 </p>
129
130 <H3><a name="Tcl_nn4"></a>33.1.2 Compiling a dynamic module</H3>
131
132
133 <p>
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):
137 </p>
138
139 <div class="code"><pre>
140 $ swig -tcl example.i
141 $ gcc -c example.c
142 $ gcc -c example_wrap.c -I/usr/local/include
143 $ gcc -shared example.o example_wrap.o -o example.so
144 </pre></div>
145
146 <p>
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.
154 </p>
155
156 <p>
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.
163 </p>
164
165 <H3><a name="Tcl_nn5"></a>33.1.3 Static linking</H3>
166
167
168 <p>
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.
175 </p>
176
177 <p>
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.
182 For example:
183 </p>
184
185 <div class="code"><pre>
186 %module example
187
188 %inline %{
189 extern int fact(int);
190 extern int mod(int, int);
191 extern double My_variable;
192 %}
193
194 %include "tclsh.i"       // Include code for rebuilding tclsh
195
196 </pre></div>
197
198 <p>
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:
202 </p>
203
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 \
210         -o mytclsh
211
212 </pre></div>
213
214 <p>
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.
220 </p>
221
222 <p>
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). 
229 </p>
230
231 <H3><a name="Tcl_nn6"></a>33.1.4 Using your module</H3>
232
233
234 <p>
235 To use your module, simply use the Tcl <tt>load</tt> command.  If
236 all goes well, you will be able to this:
237 </p>
238
239 <div class="code"><pre>
240 $ tclsh
241 % load ./example.so
242 % fact 4
243 24
244 %
245 </pre></div>
246
247 <p>
248 A common error received by first-time users is the following:
249 </p>
250
251 <div class="code">
252 <pre>
253 % load ./example.so
254 couldn't find procedure Example_Init
255
256 </pre>
257 </div>
258
259 <p>
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.
265 </p>
266
267 <p>
268 Another common error is something similar to the following:
269 </p>
270
271 <div class="code">
272 <pre>
273 % load ./example.so
274 couldn't load file "./example.so": ./example.so: undefined symbol: fact
275
276 </pre>
277 </div>
278
279 <p>
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
284 to the linker.  
285 </p>
286
287 <p>
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.
295 </p>
296
297 <p>
298 Finally, suppose that your extension module is linked with another library like this:
299 </p>
300
301 <div class="code">
302 <pre>
303 $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
304       -o example.so
305 </pre>
306 </div>
307
308 <p>
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:
311 </p>
312
313 <div class="code">
314 <pre>
315 % load ./example.so
316 couldn't load file "./example.so": libfoo.so: cannot open shared object file:
317 No such file or directory
318 %        
319 </pre>
320 </div>
321
322 <p>
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:
329 </p>
330
331 <div class="code">
332 <pre>
333 $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
334       -Xlinker -rpath /home/beazley/projects/lib \
335       -o example.so
336 </pre>
337 </div>
338
339 <p>
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:
345 </p>
346
347 <div class="code">
348 <pre>
349 $ env LD_LIBRARY_PATH=/home/beazley/projects/lib tclsh
350 </pre>
351 </div>
352
353 <p>
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
356 the man pages). 
357 </p>
358
359 <H3><a name="Tcl_nn7"></a>33.1.5 Compilation of C++ extensions</H3>
360
361
362 <p>
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
366 correctly.
367 </p>
368
369 <p>
370 On most machines, C++ extension modules should be linked using the C++
371 compiler.  For example:
372 </p>
373
374 <div class="code"><pre>
375 % swig -c++ -tcl example.i
376 % g++ -c example.cxx
377 % g++ -c example_wrap.cxx -I/usr/local/include
378 % g++ -shared example.o example_wrap.o -o example.so
379 </pre></div>
380
381 <p>
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:
385 </p>
386
387 <div class="code"><pre>
388 % swig -c++ -tcl example.i
389 % CC -c example.cxx
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
392 </pre></div>
393
394 <p>
395 Of course, the extra libraries to use are completely non-portable---you will 
396 probably need to do some experimentation.
397 </p>
398
399 <p>
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.
406 </p>
407
408 <p>
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:
414 </p>
415
416 <div class="code">
417 <pre>
418 $ ldd swig
419         libstdc++-libc6.1-1.so.2 =&gt; /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
420         libm.so.6 =&gt; /lib/libm.so.6 (0x4005b000)
421         libc.so.6 =&gt; /lib/libc.so.6 (0x40077000)
422         /lib/ld-linux.so.2 =&gt; /lib/ld-linux.so.2 (0x40000000)
423 $
424 </pre>
425 </div>
426
427 <p>
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.
440 </p>
441
442 <H3><a name="Tcl_nn8"></a>33.1.6 Compiling for 64-bit platforms</H3>
443
444
445 <p>
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.
451 </p>
452
453 <p>
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.
459 </p>
460
461 <p>
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).
467 </p>
468
469 <H3><a name="Tcl_nn9"></a>33.1.7 Setting a package prefix</H3>
470
471
472 <p>
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 :
476 </p>
477
478 <div class="code"><pre>
479 swig -tcl -prefix Foo example.i
480 </pre></div>
481
482 <p>
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>".
486 </p>
487
488 <H3><a name="Tcl_nn10"></a>33.1.8 Using namespaces</H3>
489
490
491 <p>
492 Alternatively, you can have SWIG install your module into a Tcl
493 namespace by specifying the <tt>-namespace</tt> option :
494 </p>
495
496 <div class="code"><pre>
497 swig -tcl -namespace example.i
498 </pre></div>
499
500 <p>
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.
503 </p>
504
505 <p>
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>.
508 </p>
509
510 <H2><a name="Tcl_nn11"></a>33.2 Building Tcl/Tk Extensions under Windows 95/NT</H2>
511
512
513 <p>
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.
519 </p>
520
521 <H3><a name="Tcl_nn12"></a>33.2.1 Running SWIG from Developer Studio</H3>
522
523
524 <p>
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 :
528 </p>
529
530 <ul>
531 <li>Open up a new workspace and use the AppWizard to select a DLL project.
532
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.
539
540 <li>Select the SWIG interface file and go to the settings menu.  Under
541 settings, select the "Custom Build" option.
542
543 <li>Enter "SWIG" in the description field.
544
545 <li>Enter "<tt>swig -tcl -o $(ProjDir)\$(InputName)_wrap.c
546 $(InputPath)</tt>" in the "Build command(s) field"
547
548 <li>Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>" in the "Output files(s) field".
549
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".
553
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).
558
559 <li>Build your project.
560 </ul>
561
562 <p>
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.
568 For example :
569 </p>
570
571 <div class="code"><pre>
572 MSDOS &gt; tclsh80
573 % load example.dll
574 % fact 4
575 24
576 %
577 </pre></div>
578
579 <H3><a name="Tcl_nn13"></a>33.2.2 Using NMAKE</H3>
580
581
582 <p>
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 :
587 </p>
588
589 <div class="code"><pre>
590 # Makefile for building various SWIG generated extensions
591
592 SRCS          = example.c
593 IFILE         = example
594 INTERFACE     = $(IFILE).i
595 WRAPFILE      = $(IFILE)_wrap.c
596
597 # Location of the Visual C++ tools (32 bit assumed)
598
599 TOOLS         = c:\msdev
600 TARGET        = example.dll
601 CC            = $(TOOLS)\bin\cl.exe
602 LINK          = $(TOOLS)\bin\link.exe
603 INCLUDE32     = -I$(TOOLS)\include
604 MACHINE       = IX86
605
606 # C Library needed to build a DLL
607
608 DLLIBC        = msvcrt.lib oldnames.lib  
609
610 # Windows libraries that are apparently needed
611 WINLIB        = kernel32.lib advapi32.lib user32.lib gdi32.lib comdlg32.lib 
612 winspool.lib
613
614 # Libraries common to all DLLs
615 LIBS          = $(DLLIBC) $(WINLIB) 
616
617 # Linker options
618 LOPT      = -debug:full -debugtype:cv /NODEFAULTLIB /RELEASE /NOLOGO /
619 MACHINE:$(MACHINE) -entry:_DllMainCRTStartup@12 -dll
620
621 # C compiler flags
622
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
626
627 tcl::
628         ..\..\swig -tcl -o $(WRAPFILE) $(INTERFACE)
629         $(CC) $(CFLAGS) $(TCL_INCLUDES) $(SRCS) $(WRAPFILE)
630         set LIB=$(TOOLS)\lib
631         $(LINK) $(LOPT) -out:example.dll $(LIBS) $(TCLLIB) example.obj example_wrap.obj
632
633 </pre></div>
634
635 <p>
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
639 Tcl extensions.
640 </p>
641
642 <H2><a name="Tcl_nn14"></a>33.3 A tour of basic C/C++ wrapping</H2>
643
644
645 <p>
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
650 wrapping.
651 </p>
652
653 <H3><a name="Tcl_nn15"></a>33.3.1 Modules</H3>
654
655
656 <p>
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
661 Tcl command.
662 </p>
663
664 <p>
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:
668 </p>
669
670 <div class="code">
671 <pre>
672 % load ./md5.so
673 couldn't find procedure Md_Init
674 </pre>
675 </div>
676
677 <p>
678 To fix this, supply an extra argument to <tt>load</tt> like this:
679 </p>
680
681 <div class="code">
682 <pre>
683 % load ./md5.so md5
684 </pre>
685 </div>
686
687 <H3><a name="Tcl_nn16"></a>33.3.2 Functions</H3>
688
689
690 <p>
691 Global functions are wrapped as new Tcl built-in commands.  For example,
692 </p>
693
694 <div class="code"><pre>
695 %module example
696 int fact(int n);
697 </pre></div>
698
699 <p>
700 creates a built-in function <tt>fact</tt> that works exactly
701 like you think it does:
702 </p>
703
704 <div class="code"><pre>
705 % load ./example.so
706 % fact 4
707 24
708 % set x [fact 6]
709 %
710 </pre></div>
711
712 <H3><a name="Tcl_nn17"></a>33.3.3 Global variables</H3>
713
714
715 <p>
716 C/C++ global variables are wrapped by Tcl global variables.  For example:
717 </p>
718
719 <div class="code"><pre>
720 // SWIG interface file with global variables
721 %module example
722 ...
723 %inline %{
724 extern double density;
725 %}
726 ...
727 </pre></div>
728
729 <p>
730 Now look at the Tcl interface:
731 </p>
732
733 <div class="code"><pre>
734 % puts $density          # Output value of C global variable
735 1.0
736 % set density 0.95       # Change value
737 </pre></div>
738
739 <p>
740 If you make an error in variable assignment, you will get an
741 error message.  For example:
742 </p>
743
744 <div class="code"><pre>
745 % set density "hello"
746 can't set "density": Type error. expected a double.
747 %
748 </pre></div>
749
750 <p>
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
753 error.
754 </p>
755
756 <p>
757 To make ordinary variables read-only, you can use the <tt>%immutable</tt> directive. For example:
758 </p>
759
760 <div class="code">
761 <pre>
762 %{
763 extern char *path;
764 %}
765 %immutable;
766 extern char *path;
767 %mutable;
768 </pre>
769 </div>
770
771 <p>
772 The <tt>%immutable</tt> directive stays in effect until it is explicitly disabled or cleared using
773 <tt>%mutable</tt>.
774 See the <a href="SWIG.html#SWIG_readonly_variables">Creating read-only variables</a> section for further details.
775 </p>
776
777 <p>
778 If you just want to make a specific variable immutable, supply a declaration name.  For example:
779 </p>
780
781 <div class="code">
782 <pre>
783 %{
784 extern char *path;
785 %}
786 %immutable path;
787 ...
788 extern char *path;      // Read-only (due to %immutable)
789 </pre>
790 </div>
791
792 <H3><a name="Tcl_nn18"></a>33.3.4 Constants and enums</H3>
793
794
795 <p>
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:
799 </p>
800
801 <div class="code">
802 <pre>
803 #define PI 3.14159
804 #define VERSION "1.0"
805
806 enum Beverage { ALE, LAGER, STOUT, PILSNER };
807
808 %constant int FOO = 42;
809 %constant const char *path = "/usr/local";
810 </pre>
811 </div>
812
813 <p>
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.
817 </p>
818
819 <p>
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.
823 </p>
824
825 <p>
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.
828 </p>
829
830 <p>
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:
833 </p>
834
835 <div class="code">
836 <pre>
837 proc blah {} {
838    global FOO
839    bar $FOO
840 }
841 </pre>
842 </div>
843
844 <p>
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:
847 </p>
848
849 <div class="code">
850 <pre>
851 %apply int CONSTANT { int x };
852 #define FOO 42
853 ...
854 void bar(int x);
855 </pre>
856 </div>
857
858 <p>
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:
861 </p>
862
863 <div class="code">
864 <pre>
865 proc blah {} {
866    bar FOO
867 }
868 </pre>
869 </div>
870
871 <p>
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.
874 </p>
875
876 <H3><a name="Tcl_nn19"></a>33.3.5 Pointers</H3>
877
878
879 <p>
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:
882 </p>
883
884 <div class="code">
885 <pre>
886 %module example
887
888 FILE *fopen(const char *filename, const char *mode);
889 int fputs(const char *, FILE *);
890 int fclose(FILE *);
891 </pre>
892 </div>
893
894 <p>
895 When wrapped, you will be able to use the functions in a natural way from Tcl. 
896 For example:
897 </p>
898
899 <div class="code">
900 <pre>
901 % load ./example.so
902 % set f [fopen junk w]
903 % fputs "Hello World\n" $f
904 % fclose $f
905 </pre>
906 </div>
907
908 <p>
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
912 string like this:
913 </p>
914
915 <div class="code"><pre>
916 % puts $f
917 _c0671108_p_FILE
918
919 </pre></div>
920
921 <p>
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.
925 </p>
926
927 <p>
928 The NULL pointer is represented by the string <tt>NULL</tt>.
929 </p>
930
931 <p>
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
942 example:
943 </p>
944
945 <div class="code">
946 <pre>
947 %inline %{
948 /* C-style cast */
949 Bar *FooToBar(Foo *f) {
950    return (Bar *) f;
951 }
952
953 /* C++-style cast */
954 Foo *BarToFoo(Bar *b) {
955    return dynamic_cast&lt;Foo*&gt;(b);
956 }
957
958 Foo *IncrFoo(Foo *f, int i) {
959     return f+i;
960 }
961 %}
962 </pre>
963 </div>
964
965 <p>
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.
970 </p>
971
972 <H3><a name="Tcl_nn20"></a>33.3.6 Structures</H3>
973
974
975 <p>
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,
978 </p>
979
980 <div class="code"><pre>
981 struct Vector {
982         double x,y,z;
983 };
984
985 </pre></div>
986
987 <p>
988 is used as follows:
989 </p>
990
991 <div class="code"><pre>
992 % Vector v
993 % v configure -x 3.5 -y 7.2
994 % puts "[v cget -x] [v cget -y] [v cget -z]"
995 3.5 7.2 0.0
996
997 </pre></div>
998
999 <p>
1000 Similar access is provided for unions and the data members of C++ classes.
1001 </p>
1002
1003 <p>
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:
1007 </p>
1008
1009 <div class="code">
1010 <pre>
1011 % puts [v cget -this]
1012 _88e31408_p_Vector
1013 </pre>
1014 </div>
1015
1016 <p>
1017 Further details about the relationship between the Tcl and the underlying C structure
1018 are covered a little later.
1019 </p>
1020
1021 <p>
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:
1024 </p>
1025
1026 <div class="code">
1027 <pre>
1028 struct Foo {
1029    ...
1030    %immutable;
1031    int x;        /* Read-only members */
1032    char *name;
1033    %mutable;
1034    ...
1035 };
1036 </pre>
1037 </div>
1038
1039 <p>
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).
1045 </p>
1046
1047 <p>
1048 If a structure contains arrays, access to those arrays is managed through pointers.  For
1049 example, consider this:
1050 </p>
1051
1052 <div class="code">
1053 <pre>
1054 struct Bar {
1055     int  x[16];
1056 };
1057 </pre>
1058 </div>
1059
1060 <p>
1061 If accessed in Tcl, you will see behavior like this:
1062 </p>
1063
1064 <div class="code">
1065 <pre>
1066 % Bar b
1067 % puts [b cget -x]
1068 _801861a4_p_int
1069
1070 </pre>
1071 </div>
1072
1073 <p>
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:
1077 </p>
1078
1079 <div class="code">
1080 <pre>
1081 % Bar c
1082 % c configure -x [b cget -x]   # Copy contents of b.x to c.x
1083 </pre>
1084 </div>
1085
1086 <p>
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.
1091 </p>
1092
1093 <p>
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:
1096 </p>
1097
1098 <div class="code">
1099 <pre>
1100 struct Foo {
1101    int a;
1102 };
1103
1104 struct Bar {
1105    Foo f;
1106 };
1107 </pre>
1108 </div>
1109
1110 <p>
1111 Now, suppose that you access the <tt>f</tt> attribute of <tt>Bar</tt> like this:
1112 </p>
1113
1114 <div class="code">
1115 <pre>
1116 % Bar b
1117 % set x [b cget -f]
1118 </pre>
1119 </div>
1120
1121 <p>
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:
1124 </p>
1125
1126 <div class="code">
1127 <pre>
1128 Bar b;
1129 Foo *x = &amp;b-&gt;f;       /* Points inside b */
1130 </pre>
1131 </div>
1132
1133 <p>
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:
1136 </p>
1137
1138 <div class="code">
1139 <pre>
1140 % Bar b
1141 % set x [b cget -f]
1142 % x cget -a
1143 invalid command name "x"
1144 </pre>
1145 </div>
1146
1147 <p>
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:
1151 </p>
1152
1153 <div class="code">
1154 <pre>
1155 % Bar b
1156 % set x [b cget -f]
1157 % $x cget -a
1158 0
1159 %
1160 </pre>
1161 </div>
1162
1163 <p>
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:
1166 </p>
1167
1168 <div class="code">
1169 <pre>
1170
1171 % Bar b
1172 % set x [b cget -f]
1173 % $x configure -a 3            # Modifies contents of f (inside b)
1174 % [b cget -f] -configure -a 3  # Same thing
1175 </pre>
1176 </div>
1177
1178 <p>
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,
1182 </p>
1183
1184 <div class="code">
1185 <pre>
1186 void blah(Foo *f);
1187 </pre>
1188 </div>
1189
1190 <p>
1191 you can call the function in Tcl as follows:
1192 </p>
1193
1194 <div class="code">
1195 <pre>
1196 % Foo x            # Create a Foo object 
1197 % blah x           # Pass the object to a function
1198 </pre>
1199 </div>
1200
1201 <p>
1202 It is also possible to call the function using the raw pointer value. For
1203 instance:
1204 </p>
1205
1206 <div class="code">
1207 <pre>
1208 % blah [x cget -this]   # Pass object to a function
1209 </pre>
1210 </div>
1211
1212 <p>
1213 It is also possible to create and use objects using variables.  For example:
1214 </p>
1215
1216 <div class="code">
1217 <pre>
1218 % set b [Bar]            # Create a Bar
1219 % $b cget -f             # Member access
1220 % puts $b
1221 _108fea88_p_Bar
1222 %
1223 </pre>
1224 </div>
1225
1226 <p>
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:
1229 </p>
1230
1231 <div class="code">
1232 <pre>
1233 % Foo f                 # Create object f
1234 % rename f ""
1235 </pre>
1236 </div>
1237
1238 <p>
1239 or
1240 </p>
1241
1242 <div class="code">
1243 <pre>
1244 % Foo f                 # Create object f
1245 % f -delete
1246 </pre>
1247 </div>
1248
1249 <p>
1250 Note: Tcl only destroys the underlying object if it has ownership.  See the
1251 memory management section that appears shortly.
1252 </p>
1253
1254 <H3><a name="Tcl_nn21"></a>33.3.7 C++ classes</H3>
1255
1256
1257 <p>
1258 C++ classes are wrapped as an extension of structure wrapping. For example, if you have this class,
1259 </p>
1260
1261 <div class="code"><pre>
1262 class List {
1263 public:
1264   List();
1265   ~List();
1266   int  search(char *item);
1267   void insert(char *item);
1268   void remove(char *item);
1269   char *get(int n);
1270   int  length;
1271 };
1272 </pre></div>
1273
1274 <p>
1275 you can use it in Tcl like this:
1276 </p>
1277
1278 <div class="code"><pre>
1279 % List x
1280 % x insert Ale
1281 % x insert Stout
1282 % x insert Lager
1283 % x get 1
1284 Stout
1285 % puts [l cget -length]
1286 3
1287 %
1288 </pre></div>
1289
1290 <p>
1291 Class data members are accessed in the same manner as C structures.  
1292 </p>
1293
1294 <p>
1295 Static class members are accessed as global functions or variables.
1296 To illustrate, suppose you have a class like this:
1297 </p>
1298
1299 <div class="code">
1300 <pre>
1301 class Spam {
1302 public:
1303    static void foo();
1304    static int bar;
1305
1306 };
1307 </pre>
1308 </div>
1309
1310 <p>
1311 In Tcl, the static member is accessed as follows:
1312 </p>
1313
1314 <div class="code">
1315 <pre>
1316 % Spam_foo        # Spam::foo()
1317 % puts $Spam_bar  # Spam::bar
1318 </pre>
1319 </div>
1320
1321 <H3><a name="Tcl_nn22"></a>33.3.8 C++ inheritance</H3>
1322
1323
1324 <p>
1325 SWIG is fully aware of issues related to C++ inheritance.  Therefore, if you have
1326 classes like this
1327 </p>
1328
1329 <div class="code">
1330 <pre>
1331 class Foo {
1332 ...
1333 };
1334
1335 class Bar : public Foo {
1336 ...
1337 };
1338 </pre>
1339 </div>
1340
1341 <p>
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:
1344 </p>
1345
1346 <div class="code">
1347 <pre>
1348 void spam(Foo *f);
1349 </pre>
1350 </div>
1351
1352 <p>
1353 then the function <tt>spam()</tt> accepts a <tt>Foo *</tt> or a pointer to any class derived from <tt>Foo</tt>.
1354 For instance:
1355 </p>
1356
1357 <div class="code">
1358 <pre>
1359 % Foo f      # Create a Foo
1360 % Bar b      # Create a Bar
1361 % spam f     # OK
1362 % spam b     # OK
1363 </pre>
1364 </div>
1365
1366 <p>
1367 It is safe to use multiple inheritance with SWIG.
1368 </p>
1369
1370 <H3><a name="Tcl_nn23"></a>33.3.9 Pointers, references, values, and arrays</H3>
1371
1372
1373 <p>
1374 In C++, there are many different ways a function might receive
1375 and manipulate objects.  For example:
1376 </p>
1377
1378 <div class="code">
1379 <pre>
1380 void spam1(Foo *x);      // Pass by pointer
1381 void spam2(Foo &amp;x);      // Pass by reference
1382 void spam3(Foo x);       // Pass by value
1383 void spam4(Foo x[]);     // Array of objects
1384 </pre>
1385 </div>
1386
1387 <p>
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:
1392 </p>
1393
1394 <div class="code">
1395 <pre>
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)
1401 </pre>
1402 </div>
1403
1404 <p>
1405 Similar behavior occurs for return values.  For example, if you had
1406 functions like this,
1407 </p>
1408
1409 <div class="code">
1410 <pre>
1411 Foo *spam5();
1412 Foo &amp;spam6();
1413 Foo  spam7();
1414 </pre>
1415 </div>
1416
1417 <p>
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).
1422 </p>
1423
1424 <H3><a name="Tcl_nn24"></a>33.3.10 C++ overloaded functions</H3>
1425
1426
1427 <p>
1428 C++ overloaded functions, methods, and constructors are mostly supported by SWIG.  For example,
1429 if you have two functions like this:
1430 </p>
1431
1432 <div class="code">
1433 <pre>
1434 void foo(int);
1435 void foo(char *c);
1436 </pre>
1437 </div>
1438
1439 <p>
1440 You can use them in Tcl in a straightforward manner:
1441 </p>
1442
1443 <div class="code">
1444 <pre>
1445 % foo 3            # foo(int)
1446 % foo Hello        # foo(char *c)
1447 </pre>
1448 </div>
1449
1450 <p>
1451 Similarly, if you have a class like this,
1452 </p>
1453
1454 <div class="code">
1455 <pre>
1456 class Foo {
1457 public:
1458     Foo();
1459     Foo(const Foo &amp;);
1460     ...
1461 };
1462 </pre>
1463 </div>
1464
1465 <p>
1466 you can write Tcl code like this:
1467 </p>
1468
1469 <div class="code">
1470 <pre>
1471 % Foo f                # Create a Foo
1472 % Foo g f              # Copy f
1473 </pre>
1474 </div>
1475
1476 <p>
1477 Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG
1478 can't disambiguate. For example:
1479 </p>
1480
1481 <div class="code">
1482 <pre>
1483 void spam(int);
1484 void spam(short);
1485 </pre>
1486 </div>
1487
1488 <p>
1489 or
1490 </p>
1491
1492 <div class="code">
1493 <pre>
1494 void foo(Bar *b);
1495 void foo(Bar &amp;b);
1496 </pre>
1497 </div>
1498
1499 <p>
1500 If declarations such as these appear, you will get a warning message like this:
1501 </p>
1502
1503 <div class="code">
1504 <pre>
1505 example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)
1506 at example.i:11.
1507 </pre>
1508 </div>
1509
1510 <p>
1511 To fix this, you either need to ignore or rename one of the methods.  For example:
1512 </p>
1513
1514 <div class="code">
1515 <pre>
1516 %rename(spam_short) spam(short);
1517 ...
1518 void spam(int);    
1519 void spam(short);   // Accessed as spam_short
1520 </pre>
1521 </div>
1522
1523 <p>
1524 or
1525 </p>
1526
1527 <div class="code">
1528 <pre>
1529 %ignore spam(short);
1530 ...
1531 void spam(int);    
1532 void spam(short);   // Ignored
1533 </pre>
1534 </div>
1535
1536 <p>
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.
1541 </p>
1542
1543 <p>
1544 Please refer to the "SWIG and C++" chapter for more information about overloading. 
1545 </p>
1546
1547 <H3><a name="Tcl_nn25"></a>33.3.11 C++ operators</H3>
1548
1549
1550 <p>
1551 Certain C++ overloaded operators can be handled automatically by SWIG.  For example,
1552 consider a class like this:
1553 </p>
1554
1555 <div class="code">
1556 <pre>
1557 class Complex {
1558 private:
1559   double rpart, ipart;
1560 public:
1561   Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
1562   Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
1563   Complex &amp;operator=(const Complex &amp;c);
1564   Complex operator+(const Complex &amp;c) const;
1565   Complex operator-(const Complex &amp;c) const;
1566   Complex operator*(const Complex &amp;c) const;
1567   Complex operator-() const;
1568   
1569   double re() const { return rpart; }
1570   double im() const { return ipart; }
1571 };
1572 </pre>
1573 </div>
1574
1575 <p>
1576 When wrapped, it works like this:
1577 </p>
1578
1579 <div class="code">
1580 <pre>
1581 % Complex c 3 4
1582 % Complex d 7 8
1583 % set e [c + d]
1584 % $e re
1585 10.0
1586 % $e im
1587 12.0
1588 </pre>
1589 </div>
1590
1591 <p>
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:
1598 </p>
1599
1600 <div class="code">
1601 <pre>
1602 % Complex c 3 4
1603 % Complex d 7 8
1604 % set e [c - d]       # operator-(const Complex &amp;)
1605 % puts "[$e re] [$e im]"
1606 10.0 12.0
1607 % set f [c -]         # operator-()
1608 % puts "[$f re] [$f im]"
1609 -3.0 -4.0
1610 %
1611 </pre>
1612 </div>
1613
1614 <p>
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
1618 </p>
1619
1620 <div class="code">
1621 <pre>
1622 class Complex {
1623 ...
1624 friend Complex operator+(double, const Complex &amp;c);
1625 ...
1626 };
1627 </pre>
1628 </div>
1629
1630 <p>
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:
1634 </p>
1635
1636 <div class="code">
1637 <pre>
1638 %rename(Complex_add_dc) operator+(double, const Complex &amp;);
1639 ...
1640 Complex operator+(double, const Complex &amp;c);
1641 </pre>
1642 </div>
1643
1644 <p>
1645 There are ways to make this operator appear as part of the class using the <tt>%extend</tt> directive.
1646 Keep reading.
1647 </p>
1648
1649 <H3><a name="Tcl_nn26"></a>33.3.12 C++ namespaces</H3>
1650
1651
1652 <p>
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,
1656 </p>
1657
1658 <div class="code">
1659 <pre>
1660 %module example
1661
1662 namespace foo {
1663    int fact(int n);
1664    struct Vector {
1665        double x,y,z;
1666    };
1667 };
1668 </pre>
1669 </div>
1670
1671 <p>
1672 it works in Tcl as follows:
1673 </p>
1674
1675 <div class="code">
1676 <pre>
1677 % load ./example.so
1678 % fact 3
1679 6
1680 % Vector v
1681 % v configure -x 3.4
1682 </pre>
1683 </div>
1684
1685 <p>
1686 If your program has more than one namespace, name conflicts (if any) can be resolved using <tt>%rename</tt>
1687 For example:
1688 </p>
1689
1690 <div class="code">
1691 <pre>
1692 %rename(Bar_spam) Bar::spam;
1693
1694 namespace Foo {
1695     int spam();
1696 }
1697
1698 namespace Bar {
1699     int spam();
1700 }
1701 </pre>
1702 </div>
1703
1704 <p>
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.
1711 </p>
1712
1713 <H3><a name="Tcl_nn27"></a>33.3.13 C++ templates</H3>
1714
1715
1716 <p>
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.
1720 For example:
1721 </p>
1722
1723 <div class="code">
1724 <pre>
1725 %module example
1726 %{
1727 #include "pair.h"
1728 %}
1729
1730 template&lt;class T1, class T2&gt;
1731 struct pair {
1732    typedef T1 first_type;
1733    typedef T2 second_type;
1734    T1 first;
1735    T2 second;
1736    pair();
1737    pair(const T1&amp;, const T2&amp;);
1738   ~pair();
1739 };
1740
1741 %template(pairii) pair&lt;int,int&gt;;
1742 </pre>
1743 </div>
1744
1745 <p>
1746 In Tcl:
1747 </p>
1748
1749 <div class="code">
1750 <pre>
1751 % pairii p 3 4
1752 % p cget -first
1753 3
1754 % p cget -second
1755 4
1756 </pre>
1757 </div>
1758
1759 <p>
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.
1763 </p>
1764
1765 <H3><a name="Tcl_nn28"></a>33.3.14 C++ Smart Pointers</H3>
1766
1767
1768 <p>
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-&gt;()</tt> like this:
1772 </p>
1773
1774 <div class="code">
1775 <pre>
1776 template&lt;class T&gt; class SmartPtr {
1777    ...
1778    T *operator-&gt;();
1779    ...
1780 }
1781 </pre>
1782 </div>
1783
1784 <p>
1785 Then, if you have a class like this,
1786 </p>
1787
1788 <div class="code">
1789 <pre>
1790 class Foo {
1791 public:
1792      int x;
1793      int bar();
1794 };
1795 </pre>
1796 </div>
1797
1798 <p>
1799 A smart pointer would be used in C++ as follows:
1800 </p>
1801
1802 <div class="code">
1803 <pre>
1804 SmartPtr&lt;Foo&gt; p = CreateFoo();   // Created somehow (not shown)
1805 ...
1806 p-&gt;x = 3;                        // Foo::x
1807 int y = p-&gt;bar();                // Foo::bar
1808 </pre>
1809 </div>
1810
1811 <p>
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.
1814 For example:
1815 </p>
1816
1817 <div class="code">
1818 <pre>
1819 %module example
1820 ...
1821 %template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
1822 ...
1823 </pre>
1824 </div>
1825
1826 <p>
1827 Now, in Tcl, everything should just "work":
1828 </p>
1829
1830 <div class="code">
1831 <pre>
1832 % set p [CreateFoo]                  # Create a smart-pointer somehow
1833 % $p configure -x 3                  # Foo::x
1834 % $p bar                             # Foo::bar
1835 </pre>
1836 </div>
1837
1838 <p>
1839 If you ever need to access the underlying pointer returned by <tt>operator-&gt;()</tt> itself,
1840 simply use the <tt>__deref__()</tt> method.  For example:
1841 </p>
1842
1843 <div class="code">
1844 <pre>
1845 % set f [$p __deref__]    # Returns underlying Foo *
1846 </pre>
1847 </div>
1848
1849 <H2><a name="Tcl_nn29"></a>33.4 Further details on the Tcl class interface</H2>
1850
1851
1852 <p>
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.
1860 </p>
1861
1862 <H3><a name="Tcl_nn30"></a>33.4.1 Proxy classes</H3>
1863
1864
1865 <p>
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
1869 </p>
1870
1871 <div class="code">
1872 <pre>
1873 class Foo {
1874 public:
1875      int x;
1876      int spam(int);
1877      ...
1878 </pre>
1879 </div>
1880
1881 <p>
1882 then SWIG transforms it into a set of low-level procedural wrappers. For example:
1883 </p>
1884
1885 <div class="code">
1886 <pre>
1887 Foo *new_Foo() {
1888     return new Foo();
1889 }
1890 void delete_Foo(Foo *f) {
1891     delete f;
1892 }
1893 int Foo_x_get(Foo *f) {
1894     return f-&gt;x;
1895 }
1896 void Foo_x_set(Foo *f, int value) {
1897     f-&gt;x = value;
1898 }
1899 int Foo_spam(Foo *f, int arg1) {
1900     return f-&gt;spam(arg1);
1901 }
1902 </pre>
1903 </div>
1904
1905 <p>
1906 These wrappers are actually found in the Tcl extension module.  For example, you can certainly do this:
1907 </p>
1908
1909 <div class="code">
1910 <pre>
1911 % load ./example.so
1912 % set f [new_Foo]
1913 % Foo_x_get $f
1914 0
1915 % Foo_spam $f 3
1916 1
1917 %
1918 </pre>
1919 </div>
1920
1921 <p>
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.
1925 </p>
1926
1927 <H3><a name="Tcl_nn31"></a>33.4.2 Memory management</H3>
1928
1929
1930 <p>
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.
1936 </p>
1937
1938 <p>
1939 When an object is created by a constructor or returned by value, Tcl automatically takes
1940 ownership of the result.  For example:
1941 </p>
1942
1943 <div class="code">
1944 <pre>
1945 class Foo {
1946 public:
1947     Foo();
1948     Foo bar();
1949 };
1950 </pre>
1951 </div>
1952
1953 <p>
1954 In Tcl:
1955 </p>
1956
1957 <div class="code">
1958 <pre>
1959 % Foo f
1960 % f cget -thisown
1961 1
1962 % set g [f bar]
1963 % $g cget -thisown
1964 1
1965 </pre>
1966 </div>
1967
1968 <p>
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:
1971 </p>
1972
1973 <div class="code">
1974 <pre>
1975 class Foo {
1976 public:
1977     ...
1978     Foo *spam();
1979     ...
1980 };
1981 </pre>
1982 </div>
1983
1984 <br>
1985
1986 <div class="code">
1987 <pre>
1988 % Foo f
1989 % set s [f spam]
1990 % $s cget -thisown
1991 0
1992
1993 </pre>
1994 </div>
1995
1996 <p>
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!
2001 </p>
2002
2003 <p>
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:
2006 </p>
2007
2008 <div class="code">
2009 <pre>
2010 %module example
2011
2012 struct Foo {
2013     int  value;
2014     Foo  *next;
2015 };
2016
2017 Foo *head = 0;
2018 </pre>
2019 </div>
2020
2021 <p>
2022 When wrapped in Tcl, careful observation will reveal that ownership changes whenever an object
2023 is assigned to a global variable.  For example:
2024 </p>
2025
2026 <div class="code">
2027 <pre>
2028 % Foo f
2029 % f cget -thisown
2030 1
2031 % set head f
2032 % f cget -thisown
2033 0
2034 </pre>
2035 </div>
2036
2037 <p>
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:
2040 </p>
2041
2042 <div class="code">
2043 <pre>
2044 % Foo f
2045 % Foo g
2046 % f cget -thisown
2047 1
2048 % g cget -thisown
2049 1
2050 % f configure -next g
2051 % g cget -thisown 
2052 0
2053 %
2054 </pre>
2055 </div>
2056
2057 <p>
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:
2061 </p>
2062
2063 <div class="code">
2064 <pre>
2065 class Node {
2066    Object *value;
2067 public:
2068    void set_value(Object *v) { value = v; }
2069    ...
2070 };
2071 </pre>
2072 </div>
2073
2074 <p>
2075 Now, consider the following Tcl code:
2076 </p>
2077
2078 <div class="code">
2079 <pre>
2080 % Object v                 # Create an object
2081 % Node n                   # Create a node
2082 % n setvalue v             # Set value
2083 % v cget -thisown
2084 1
2085
2086 </pre>
2087 </div>
2088
2089 <p>
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.
2096 </p>
2097
2098 <p>
2099 To work around this, it is always possible to flip the ownership flag. For example,
2100 </p>
2101
2102 <div class="code">
2103 <pre>
2104 % v -disown              # Give ownership to C/C++
2105 % v -acquire             # Acquire ownership
2106 </pre>
2107 </div>
2108
2109 <p>
2110 It is also possible to deal with situations like this using
2111 typemaps--an advanced topic discussed later.
2112 </p>
2113
2114
2115 <H2><a name="Tcl_nn32"></a>33.5 Input and output parameters</H2>
2116
2117
2118 <p>
2119 A common problem in some C programs is handling parameters passed as simple pointers.  For
2120 example:
2121 </p>
2122
2123 <div class="code">
2124 <pre>
2125 void add(int x, int y, int *result) {
2126    *result = x + y;
2127 }
2128 </pre>
2129 </div>
2130
2131 <p>
2132 or perhaps
2133 </p>
2134
2135 <div class="code">
2136 <pre>
2137 int sub(int *x, int *y) {
2138    return *x+*y;
2139 }
2140 </pre>
2141 </div>
2142
2143 <p>
2144 The easiest way to handle these situations is to use the <tt>typemaps.i</tt> file.  For example:
2145 </p>
2146
2147 <div class="code">
2148 <pre>
2149 %module example
2150 %include "typemaps.i"
2151
2152 void add(int, int, int *OUTPUT);
2153 int  sub(int *INPUT, int *INPUT);
2154 </pre>
2155 </div>
2156
2157 <p>
2158 In Tcl, this allows you to pass simple values instead of pointer.  For example:
2159 </p>
2160
2161 <div class="code">
2162 <pre>
2163 set a [add 3 4]
2164 puts $a
2165 7
2166 </pre>
2167 </div>
2168
2169 <p>
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.
2172 </p>
2173
2174 <p>
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:
2177 </p>
2178
2179 <div class="code">
2180 <pre>
2181 %module example
2182 %include "typemaps.i"
2183
2184 %apply int *OUTPUT { int *result };
2185 %apply int *INPUT  { int *x, int *y};
2186
2187 void add(int x, int y, int *result);
2188 int  sub(int *x, int *y);
2189 </pre>
2190 </div>
2191
2192 <p>
2193 If a function mutates one of its parameters like this,
2194 </p>
2195
2196 <div class="code">
2197 <pre>
2198 void negate(int *x) {
2199    *x = -(*x);
2200 }
2201 </pre>
2202 </div>
2203
2204 <p>
2205 you can use <tt>INOUT</tt> like this:
2206 </p>
2207
2208 <div class="code">
2209 <pre>
2210 %include "typemaps.i"
2211 ...
2212 void negate(int *INOUT);
2213 </pre>
2214 </div>
2215
2216 <p>
2217 In Tcl, a mutated parameter shows up as a return value.  For example:
2218 </p>
2219
2220 <div class="code">
2221 <pre>
2222 set a [negate 3]
2223 puts $a
2224 -3
2225 </pre>
2226 </div>
2227
2228 <p>
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:
2232 </p>
2233
2234 <div class="code">
2235 <pre>
2236 /* send message, return number of bytes sent, along with success code */
2237 int send_message(char *text, int len, int *success);
2238 </pre>
2239 </div>
2240
2241 <p>
2242 To wrap such a function, simply use the <tt>OUTPUT</tt> rule above. For example:
2243 </p>
2244
2245 <div class="code">
2246 <pre>
2247 %module example
2248 %include "typemaps.i"
2249 %apply int *OUTPUT { int *success };
2250 ...
2251 int send_message(char *text, int *success);
2252 </pre>
2253 </div>
2254
2255 <p>
2256 When used in Tcl, the function will return multiple values as a list.  
2257 </p>
2258
2259 <div class="code">
2260 <pre>
2261 set r [send_message "Hello World"]
2262 set bytes [lindex $r 0]
2263 set success [lindex $r 1]
2264 </pre>
2265 </div>
2266
2267 <p>
2268 Another common use of multiple return values are in query functions.  For example:
2269 </p>
2270
2271 <div class="code">
2272 <pre>
2273 void get_dimensions(Matrix *m, int *rows, int *columns);
2274 </pre>
2275 </div>
2276
2277 <p>
2278 To wrap this, you might use the following:
2279 </p>
2280
2281 <div class="code">
2282 <pre>
2283 %module example
2284 %include "typemaps.i"
2285 %apply int *OUTPUT { int *rows, int *columns };
2286 ...
2287 void get_dimensions(Matrix *m, int *rows, *columns);
2288 </pre>
2289 </div>
2290
2291 <p>
2292 Now, in Perl:
2293 </p>
2294
2295 <div class="code">
2296 <pre>
2297 set dim [get_dimensions $m]
2298 set r  [lindex $dim 0]
2299 set c  [lindex $dim 1]
2300 </pre>
2301 </div>
2302
2303 <H2><a name="Tcl_nn33"></a>33.6 Exception handling </H2>
2304
2305
2306 <p>
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 :
2312 </p>
2313
2314 <div class="code"><pre>
2315 class RangeError {};   // Used for an exception
2316
2317 class DoubleArray {
2318   private:
2319     int n;
2320     double *ptr;
2321   public:
2322     // Create a new array of fixed size
2323     DoubleArray(int size) {
2324       ptr = new double[size];
2325       n = size;
2326     }
2327     // Destroy an array
2328     ~DoubleArray() {
2329        delete ptr;
2330     }
2331     // Return the length of the array
2332     int   length() {
2333       return n;
2334     }
2335
2336     // Get an item from the array and perform bounds checking.
2337     double getitem(int i) {
2338       if ((i &gt;= 0) &amp;&amp; (i &lt; n))
2339         return ptr[i];
2340       else
2341         throw RangeError();
2342     }
2343
2344     // Set an item in the array and perform bounds checking.
2345     void setitem(int i, double val) {
2346       if ((i &gt;= 0) &amp;&amp; (i &lt; n))
2347         ptr[i] = val;
2348       else {
2349         throw RangeError();
2350       }
2351     }
2352   };
2353 </pre></div>
2354
2355 <p>
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 :
2359 </p>
2360
2361 <div class="code"><pre>
2362 %exception {
2363   try {
2364     $action                // Gets substituted by actual function call
2365   }
2366   catch (RangeError) {
2367     Tcl_SetStringObj(tcl_result,"Array index out-of-bounds");
2368     return TCL_ERROR;
2369   }
2370 }
2371 </pre></div>
2372
2373 <p>
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:
2377 </p>
2378
2379 <div class="code">
2380 <pre>
2381 %exception getitem {
2382   try {
2383     $action
2384   }
2385   catch (RangeError) {
2386     Tcl_SetStringObj(tcl_result,"Array index out-of-bounds");
2387     return TCL_ERROR;
2388   }
2389 }
2390
2391 %exception setitem {
2392   try {
2393     $action
2394   }
2395   catch (RangeError) {
2396     Tcl_SetStringObj(tcl_result,"Array index out-of-bounds");
2397     return TCL_ERROR;
2398   }
2399 }
2400 </pre>
2401 </div>
2402
2403 <p>
2404 In this case, the exception handler is only attached to methods and functions
2405 named <tt>getitem</tt> and <tt>setitem</tt>.
2406 </p>
2407
2408 <p>
2409 If you had a lot of different methods, you can avoid extra typing by using a macro.
2410 For example:
2411 </p>
2412
2413 <div class="code">
2414 <pre>
2415 %define RANGE_ERROR
2416 {
2417   try {
2418     $action
2419   }
2420   catch (RangeError) {
2421     Tcl_SetStringObj(tcl_result,"Array index out-of-bounds");
2422     return TCL_ERROR;
2423   }
2424 }
2425 %enddef
2426
2427 %exception getitem RANGE_ERROR;
2428 %exception setitem RANGE_ERROR;
2429 </pre>
2430 </div>
2431
2432 <p>
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.
2435 </p>
2436
2437 <H2><a name="Tcl_nn34"></a>33.7 Typemaps</H2>
2438
2439
2440 <p>
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.
2445 </p>
2446
2447 <p>
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
2451 C-Tcl interface.
2452 </p>
2453
2454 <H3><a name="Tcl_nn35"></a>33.7.1 What is a typemap?</H3>
2455
2456
2457 <p>
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:
2461 </p>
2462
2463 <div class="code"><pre>
2464 %module example
2465
2466 %typemap(in) int {
2467         if (Tcl_GetIntFromObj(interp,$input,&amp;$1) == TCL_ERROR) return TCL_ERROR;
2468         printf("Received an integer : %d\n",$1);
2469 }
2470 %inline %{
2471 extern int fact(int n);
2472 %}
2473 </pre></div>
2474
2475 <p>
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>.
2483 </p>
2484
2485 <p>
2486 When this example is compiled into a Tcl module, it operates as follows:
2487 </p>
2488
2489 <div class="code"><pre>
2490 % load ./example.so
2491 % fact 6
2492 Received an integer : 6
2493 720
2494 </pre></div>
2495
2496 <p>
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:
2499 </p>
2500
2501 <div class="code"><pre>
2502 %module example
2503
2504 %typemap(in) int n {
2505         if (Tcl_GetIntFromObj(interp,$input,&amp;$1) == TCL_ERROR) return TCL_ERROR;
2506         printf("n = %d\n",$1);
2507 }
2508 %inline %{
2509 extern int fact(int n);
2510 %}
2511 </pre></div>
2512
2513 <p>
2514 In this case, the typemap code is only attached to arguments that exactly match <tt>int n</tt>.
2515 </p>
2516
2517 <p>
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:
2523 </p>
2524
2525 <div class="code">
2526 <pre>
2527 %typemap(in) int n {
2528         if (Tcl_GetIntFromObj(interp,$input,&amp;$1) == TCL_ERROR) return TCL_ERROR;
2529         printf("n = %d\n",$1);
2530 }
2531 %inline %{
2532 typedef int Integer;
2533 extern int fact(Integer n);    // Above typemap is applied
2534 %}
2535 </pre>
2536 </div>
2537
2538 <p>
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
2541 type <tt>int</tt>.
2542 </p>
2543
2544 <p>
2545 Typemaps can also be defined for groups of consecutive arguments.  For example:
2546 </p>
2547
2548 <div class="code">
2549 <pre>
2550 %typemap(in) (char *str, int len) {
2551     $1 = Tcl_GetStringFromObj($input,&amp;$2);
2552 };
2553
2554 int count(char c, char *str, int len);
2555 </pre>
2556 </div>
2557
2558 <p>
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):
2562 </p>
2563
2564 <div class="code">
2565 <pre>
2566 % count e "Hello World"
2567 1
2568 </pre>
2569 </div>
2570
2571 <H3><a name="Tcl_nn36"></a>33.7.2 Tcl typemaps</H3>
2572
2573
2574 <p>
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
2578 like this:
2579 </p>
2580
2581 <div class="code">
2582 <pre>
2583 %typemap(out) int {
2584     Tcl_SetObjResult(interp,Tcl_NewIntObj($1));
2585 }
2586 </pre>
2587 </div>
2588
2589 <p>
2590 The following list details all of the typemap methods that can be used by the Tcl module:
2591 </p>
2592
2593 <p>
2594 <tt>%typemap(in)</tt>
2595 </p>
2596
2597 <div class="indent">
2598 Converts Tcl objects to input function arguments
2599 </div>
2600
2601 <p>
2602 <tt>%typemap(out)</tt>
2603 </p>
2604
2605 <div class="indent">
2606 Converts return value of a C function to a Tcl object
2607 </div>
2608
2609 <p>
2610 <tt>%typemap(varin)</tt>
2611 </p>
2612
2613 <div class="indent">
2614 Assigns a C global variable from a Tcl object
2615 </div>
2616
2617 <p>
2618 <tt>%typemap(varout)</tt>
2619 </p>
2620
2621 <div class="indent">
2622 Returns a C global variable as a Tcl object
2623 </div>
2624
2625 <p>
2626 <tt>%typemap(freearg)</tt>
2627 </p>
2628
2629 <div class="indent">
2630 Cleans up a function argument (if necessary)
2631 </div>
2632
2633 <p>
2634 <tt>%typemap(argout)</tt>
2635 </p>
2636
2637 <div class="indent">
2638 Output argument processing
2639 </div>
2640
2641 <p>
2642 <tt>%typemap(ret)</tt>
2643 </p>
2644
2645 <div class="indent">
2646 Cleanup of function return values
2647 </div>
2648
2649 <p>
2650 <tt>%typemap(consttab)</tt>
2651 </p>
2652
2653 <div class="indent">
2654 Creation of Tcl constants (constant table)
2655 </div>
2656
2657 <p>
2658 <tt>%typemap(constcode)</tt> 
2659 </p>
2660
2661 <div class="indent">
2662 Creation of Tcl constants (init function)
2663 </div>
2664
2665 <p>
2666 <tt>%typemap(memberin)</tt>
2667 </p>
2668
2669 <div class="indent">
2670 Setting of structure/class member data
2671 </div>
2672
2673 <p>
2674 <tt>%typemap(globalin)</tt>
2675 </p>
2676
2677 <div class="indent">
2678 Setting of C global variables
2679 </div>
2680
2681 <p>
2682 <tt>%typemap(check)</tt>
2683 </p>
2684
2685 <div class="indent">
2686 Checks function input values.
2687 </div>
2688
2689 <p>
2690 <tt>%typemap(default)</tt>
2691 </p>
2692
2693 <div class="indent">
2694 Set a default value for an argument (making it optional).
2695 </div>
2696
2697 <p>
2698 <tt>%typemap(arginit)</tt>
2699 </p>
2700
2701 <div class="indent">
2702 Initialize an argument to a value before any conversions occur.
2703 </div>
2704
2705 <p>
2706 Examples of these methods will appear shortly.
2707 </p>
2708
2709 <H3><a name="Tcl_nn37"></a>33.7.3 Typemap variables</H3>
2710
2711
2712 <p>
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:
2716 </p>
2717
2718 <p>
2719 <tt>$1</tt>
2720 </p>
2721
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.
2727 </div>
2728
2729 <p>
2730 <tt>$input</tt>
2731 </p>
2732
2733 <div class="indent">
2734  A <tt>Tcl_Obj *</tt> holding a raw Tcl object with an argument or variable value.
2735 </div>
2736
2737 <p>
2738 <tt>$result</tt>
2739 </p>
2740
2741 <div class="indent">
2742 A <tt>Tcl_Obj *</tt> that holds the result to be returned to Tcl.
2743 </div>
2744
2745 <p>
2746 <tt>$1_name</tt>
2747 </p>
2748
2749 <div class="indent">
2750 The parameter name that was matched. 
2751 </div>
2752
2753 <p>
2754 <tt>$1_type</tt>
2755 </p>
2756
2757 <div class="indent">
2758 The actual C datatype matched by the typemap.
2759 </div>
2760
2761 <p>
2762 <tt>$1_ltype</tt>
2763 </p>
2764
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
2769 properly assigned.
2770 </div>
2771
2772 <p>
2773 <tt>$symname</tt>
2774 </p>
2775
2776 <div class="indent">
2777 The Tcl name of the wrapper function being created.
2778 </div>
2779
2780 <H3><a name="Tcl_nn38"></a>33.7.4 Converting  a Tcl list to a char ** </H3>
2781
2782
2783 <p>
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.
2788 </p>
2789
2790 <div class="code"><pre>
2791 %module argv
2792
2793 // This tells SWIG to treat char ** as a special case
2794 %typemap(in) char ** {
2795      Tcl_Obj **listobjv;
2796      int       nitems;
2797      int       i;
2798      if (Tcl_ListObjGetElements(interp, $input, &amp;nitems, &amp;listobjv) == TCL_ERROR) {
2799         return TCL_ERROR;
2800      }
2801      $1 = (char **) malloc((nitems+1)*sizeof(char *));
2802      for (i = 0; i &lt; nitems; i++) {
2803         $1[i] = Tcl_GetStringFromObj(listobjv[i],0);
2804      }
2805      $1[i] = 0;
2806 }
2807
2808 // This gives SWIG some cleanup code that will get called after the function call
2809 %typemap(freearg) char ** {
2810      if ($1) {
2811         free($1);
2812      }
2813 }
2814
2815 // Now a test functions
2816 %inline %{
2817 int print_args(char **argv) {
2818     int i = 0;
2819     while (argv[i]) {
2820          printf("argv[%d] = %s\n", i,argv[i]);
2821          i++;
2822     }
2823     return i;
2824 }
2825 %}
2826 %include "tclsh.i"
2827
2828 </pre></div>
2829
2830 <p>
2831 In Tcl:
2832 </p>
2833
2834 <div class="code"><pre>
2835 % print_args {John Guido Larry}
2836 argv[0] = John
2837 argv[1] = Guido
2838 argv[2] = Larry
2839 3
2840 </pre></div>
2841
2842 <H3><a name="Tcl_nn39"></a>33.7.5 Returning values in arguments</H3>
2843
2844
2845 <p>
2846 The "argout" typemap can be used to return a value originating from a
2847 function argument. For example :
2848 </p>
2849
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);
2855 }
2856
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) {
2860      $1 = &amp;temp;
2861 }
2862
2863 // Now a function returning two values
2864 int mypow(double a, double b, double *outvalue) {
2865         if ((a &lt; 0) || (b &lt; 0)) return -1;
2866         *outvalue = pow(a,b);
2867         return 0;
2868 };
2869 </pre></div>
2870
2871 <p>
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 :
2876 </p>
2877
2878 <div class="code"><pre>
2879 % mypow 2 3     # Returns two values, a status value and the result
2880 0 8
2881 %
2882 </pre></div>
2883
2884 <H3><a name="Tcl_nn40"></a>33.7.6 Useful functions</H3>
2885
2886
2887 <p>
2888 The following tables provide some functions that may be useful in
2889 writing Tcl typemaps. 
2890 </p>
2891
2892 <p>
2893 <b>Integers</b>
2894 </p>
2895
2896 <div class="code">
2897 <pre>
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);
2901 </pre>
2902 </div>
2903
2904 <p>
2905 <b>Floating Point</b>
2906 </p>
2907
2908 <div class="code">
2909 <pre>
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);
2913 </pre>
2914 </div>
2915
2916 <p>
2917 <b>Strings</b>
2918 </p>
2919
2920 <div class="code">
2921 <pre>
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);
2926 </pre>
2927 </div>
2928
2929 <p>
2930 <b>Lists</b>
2931 </p>
2932
2933 <div class="code">
2934 <pre>
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);
2945 </pre>
2946 </div>
2947
2948 <p>
2949 <b>Objects</b>
2950 </p>
2951
2952 <div class="code">
2953 <pre>
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);
2958 </pre>
2959 </div>
2960
2961 <H3><a name="Tcl_nn41"></a>33.7.7 Standard  typemaps</H3>
2962
2963
2964 <p>
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
2967 work)
2968 </p>
2969
2970
2971 <p>
2972 <b>Integer conversion</b>
2973 </p>
2974
2975 <div class="code">
2976 <pre>
2977 %typemap(in) int, short, long {
2978    int temp;
2979    if (Tcl_GetIntFromObj(interp, $input, &amp;temp) == TCL_ERROR)
2980       return TCL_ERROR;
2981    $1 = ($1_ltype) temp;
2982 }
2983 </pre>
2984 </div>
2985
2986 <br>
2987
2988 <div class="code">
2989 <pre>
2990 %typemap(out) int, short, long {
2991    Tcl_SetIntObj($result,(int) $1);
2992 }
2993 </pre>
2994 </div>
2995
2996 <p>
2997 <b>Floating point conversion</b>
2998 </p>
2999
3000 <div class="code">
3001 <pre>
3002 %typemap(in) float, double {
3003    double temp;
3004    if (Tcl_GetDoubleFromObj(interp, $input, &amp;temp) == TCL_ERROR)
3005        return TCL_ERROR;
3006    $1 = ($1_ltype) temp;
3007 }
3008 </pre>
3009 </div>
3010
3011 <br>
3012
3013 <div class="code">
3014 <pre>
3015 %typemap(out) float, double {
3016    Tcl_SetDoubleObj($result, $1);
3017 }
3018 </pre>
3019 </div>
3020
3021 <p>
3022 <b>String Conversion</b>
3023 </p>
3024
3025 <div class="code">
3026 <pre>
3027 %typemap(in) char * {
3028    int len;
3029    $1 = Tcl_GetStringFromObj(interp, &amp;len);
3030    }
3031 }
3032 </pre>
3033 </div>
3034
3035 <br>
3036
3037 <div class="code">
3038 <pre>
3039 %typemap(out) char * {
3040    Tcl_SetStringObj($result,$1);
3041 }
3042 </pre>
3043 </div>
3044
3045 <H3><a name="Tcl_nn42"></a>33.7.8 Pointer handling</H3>
3046
3047
3048 <p>
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.
3052 </p>
3053
3054 <p>
3055 <tt>
3056 int SWIG_ConvertPtr(Tcl_Obj *obj, void **ptr, swig_type_info *ty, int flags)</tt>
3057 </p>
3058
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.
3064 </div>
3065
3066 <p>
3067 <tt>
3068 Tcl_Obj *SWIG_NewPointerObj(void *ptr, swig_type_info *ty, int flags)</tt>
3069 </p>
3070
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.
3074 </div>
3075
3076 <p>
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:
3083 </p>
3084
3085 <div class="indent">
3086 <pre>
3087 Foo *f;
3088 if (SWIG_ConvertPtr($input, (void **) &amp;f, SWIGTYPE_p_Foo, 0) == -1) return NULL;
3089
3090 Tcl_Obj *;
3091 obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
3092 </pre>
3093 </div>
3094
3095 <p>
3096 In a typemap, the type descriptor should always be accessed using the special typemap
3097 variable <tt>$1_descriptor</tt>.  For example:
3098 </p>
3099
3100 <div class="indent">
3101 <pre>
3102 %typemap(in) Foo * {
3103    if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $1_descriptor,0)) == -1) return NULL;
3104 }
3105 </pre>
3106 </div>
3107
3108 <p>
3109 If necessary, the descriptor for any type can be obtained using the <tt>$descriptor()</tt> macro in a typemap.
3110 For example:
3111 </p>
3112
3113 <div class="indent">
3114 <pre>
3115 %typemap(in) Foo * {
3116    if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $descriptor(Foo *), 0)) == -1) return NULL;
3117 }
3118 </pre>
3119 </div>
3120
3121 <H2><a name="Tcl_nn43"></a>33.8 Turning a SWIG module into a Tcl Package.</H2>
3122
3123
3124 <p>
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:
3128 </p>
3129
3130 <div class="code">
3131 <pre>
3132 % swig -tcl -pkgversion 2.3 example.i
3133 </pre>
3134 </div>
3135
3136 <p>
3137 After building the SWIG generated module, you need to execute
3138 the "<tt>pkg_mkIndex</tt>" command inside tclsh.  For example :
3139 </p>
3140
3141 <div class="code"><pre>
3142 unix &gt; tclsh
3143 % pkg_mkIndex . example.so
3144 % exit
3145 </pre></div>
3146
3147 <p>
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 :
3151 </p>
3152
3153 <div class="code"><pre>
3154 ./example/
3155            pkgIndex.tcl           # The file created by pkg_mkIndex
3156            example.so             # The SWIG generated module
3157 </pre></div>
3158
3159 <p>
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 :
3165 </p>
3166
3167 <div class="code"><pre>
3168 unix &gt; tclsh
3169 % package require example
3170 % fact 4
3171 24
3172 %
3173 </pre></div>
3174
3175 <p>
3176 If  you're working with an example in the current directory and this doesn't work, do this instead :
3177 </p>
3178
3179 <div class="code"><pre>
3180 unix &gt; tclsh
3181 % lappend auto_path .
3182 % package require example
3183 % fact 4
3184 24
3185 </pre></div>
3186
3187 <p>
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.
3191 </p>
3192
3193 <H2><a name="Tcl_nn44"></a>33.9 Building new kinds of Tcl interfaces (in Tcl)</H2>
3194
3195
3196 <p>
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 :
3201 </p>
3202
3203 <div class="code"><pre>
3204 /* File : array.i */
3205 %module array
3206
3207 %inline %{
3208 double *new_double(int size) {
3209         return (double *) malloc(size*sizeof(double));
3210 }
3211 void delete_double(double *a) {
3212         free(a);
3213 }
3214 double get_double(double *a, int index) {
3215         return a[index];
3216 }
3217 void set_double(double *a, int index, double val) {
3218         a[index] = val;
3219 }
3220 int *new_int(int size) {
3221         return (int *) malloc(size*sizeof(int));
3222 }
3223 void delete_int(int *a) {
3224         free(a);
3225 }
3226 int get_int(int *a, int index) {
3227         return a[index];
3228 }
3229 int set_int(int *a, int index, int val) {
3230         a[index] = val;
3231 }
3232 %}
3233
3234 </pre></div>
3235
3236 <p>
3237 While these could be called directly, we could also write a Tcl script
3238 like this :
3239 </p>
3240
3241 <div class="code"><pre>
3242 proc Array {type size} {
3243     set ptr [new_$type $size]
3244     set code {
3245         set method [lindex $args 0]
3246         set parms [concat $ptr [lrange $args 1 end]]
3247         switch $method {
3248             get {return [eval "get_$type $parms"]}
3249             set {return [eval "set_$type $parms"]}
3250             delete {eval "delete_$type $ptr; rename $ptr {}"}
3251         }
3252     }
3253     # Create a procedure
3254     uplevel "proc $ptr args {set ptr $ptr; set type $type;$code}"
3255     return $ptr
3256 }
3257 </pre></div>
3258
3259 <p>
3260 Our script allows easy array access as follows :
3261 </p>
3262
3263 <div class="code"><pre>
3264 set a [Array double 100]                   ;# Create a double [100]
3265 for {set i 0} {$i &lt; 100} {incr i 1} {      ;# Clear the array
3266         $a set $i 0.0
3267 }
3268 $a set 3 3.1455                            ;# Set an individual element
3269 set b [$a get 10]                          ;# Retrieve an element
3270
3271 set ia [Array int 50]                      ;# Create an int[50]
3272 for {set i 0} {$i &lt; 50} {incr i 1} {       ;# Clear it
3273         $ia set $i 0
3274 }
3275 $ia set 3 7                                ;# Set an individual element
3276 set ib [$ia get 10]                        ;# Get an individual element
3277
3278 $a delete                                  ;# Destroy a
3279 $ia delete                                 ;# Destroy ia
3280 </pre></div>
3281
3282 <p>
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).
3290 </p>
3291
3292 <H3><a name="Tcl_nn45"></a>33.9.1 Proxy classes</H3>
3293
3294
3295 <p>
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.
3302 </p>
3303
3304 <div class="code"><pre>
3305 # swig_c++.tcl
3306 # Provides a simple object oriented interface using
3307 # SWIG's low level interface.
3308 #
3309
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".
3313     #
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
3318     #
3319     # Create the new object
3320     #
3321     eval set handle \[new_$objectType $args\]
3322     #
3323     # Set up the object procedure
3324     #
3325     proc $handle {cmd args} "eval ${objectType}_\$cmd $handle \$args"
3326     #
3327     # And the trace ...
3328     #
3329     uplevel trace variable $handle_r uw "{deleteObject $objectType $handle}"
3330     #
3331     # Return the handle so that 'new' can be used as an argument to a procedure
3332     #
3333     return $handle
3334 }
3335
3336 proc deleteObject {objectType handle name element op} {
3337     #
3338     # Check that the object handle has a reasonable form
3339     #
3340     if {![regexp {_[0-9a-f]*_(.+)_p} $handle]} {
3341         error "deleteObject: not a valid object handle: $handle"
3342     }
3343     #
3344     # Remove the object procedure
3345     #
3346     catch {rename $handle {}}
3347     #
3348     # Delete the object
3349     #
3350     delete_$objectType $handle
3351 }
3352
3353 proc delete {handle_r} {
3354     #
3355     # A synonym for unset that is more familiar to C++ programmers
3356     #
3357     uplevel unset $handle_r
3358 }
3359 </pre></div>
3360
3361 <p>
3362 To use this file, we simply source it and execute commands such as
3363 "new" and "delete" to manipulate objects.  For example :
3364 </p>
3365
3366 <div class="code"><pre>
3367 // list.i
3368 %module List
3369 %{
3370 #include "list.h"
3371 %}
3372
3373 // Very simple C++ example
3374
3375 class List {
3376 public:
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
3385 };
3386 </pre></div>
3387
3388 <p>
3389 Now a Tcl script using the interface...
3390 </p>
3391
3392 <div class="code"><pre>
3393 load ./list.so list       ; # Load the module
3394 source swig_c++.tcl       ; # Source the object file
3395
3396 new List l
3397 $l insert Dave
3398 $l insert John
3399 $l insert Guido
3400 $l remove Dave
3401 puts $l length_get
3402
3403 delete l
3404 </pre></div>
3405
3406 <p>
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
3410 interesting things.
3411 </p>
3412
3413 <H2><a name="Tcl_nn46"></a>33.10 Tcl/Tk Stubs</H2>
3414
3415
3416 <p>
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>.
3419 </p>
3420
3421 <p>
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>.
3424 </p>
3425
3426 <p>
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>.
3433 </p>
3434
3435 </body>
3436 </html>