Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / v8plus / html / swig / Tcl.html
CommitLineData
920dae64
AT
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>28 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</ul>
70</div>
71<!-- INDEX -->
72
73
74
75<p>
76<b>Caution: This chapter is under repair!</b>
77</p>
78
79<p>
80This chapter discusses SWIG's support of Tcl. SWIG currently requires
81Tcl 8.0 or a later release. Earlier releases of SWIG supported Tcl 7.x, but
82this is no longer supported.
83</p>
84
85<H2><a name="Tcl_nn2"></a>28.1 Preliminaries</H2>
86
87
88<p>
89To build a Tcl module, run SWIG using the <tt>-tcl</tt> option :
90</p>
91
92<div class="code"><pre>
93$ swig -tcl example.i
94</pre></div>
95
96<p>
97If building a C++ extension, add the <tt>-c++</tt> option:
98</p>
99
100<div class="code"><pre>
101$ swig -c++ -tcl example.i
102</pre></div>
103
104<p>
105This creates a file <tt>example_wrap.c</tt> or
106<tt>example_wrap.cxx</tt> that contains all of the code needed to
107build a Tcl extension module. To finish building the module, you
108need to compile this file and link it with the rest of your program.
109</p>
110
111<H3><a name="Tcl_nn3"></a>28.1.1 Getting the right header files</H3>
112
113
114<p>
115In order to compile the wrapper code, the compiler needs the <tt>tcl.h</tt> header file.
116This file is usually contained in the directory
117</p>
118
119<div class="code"><pre>
120/usr/local/include
121</pre></div>
122
123<p>
124Be aware that some Tcl versions install this header file with a version number attached to it. If
125this is the case, you should probably make a symbolic link so that <tt>tcl.h</tt> points to the correct
126header file.
127</p>
128
129<H3><a name="Tcl_nn4"></a>28.1.2 Compiling a dynamic module</H3>
130
131
132<p>
133The preferred approach to building an extension module is to compile it into
134a shared object file or DLL. To do this, you will need to compile your program
135using comands like this (shown for Linux):
136</p>
137
138<div class="code"><pre>
139$ swig -tcl example.i
140$ gcc -c example.c
141$ gcc -c example_wrap.c -I/usr/local/include
142$ gcc -shared example.o example_wrap.o -o example.so
143</pre></div>
144
145<p>
146The exact commands for doing this vary from platform to platform.
147SWIG tries to guess the right options when it is installed. Therefore,
148you may want to start with one of the examples in the <tt>SWIG/Examples/tcl</tt>
149directory. If that doesn't work, you will need to read the man-pages for
150your compiler and linker to get the right set of options. You might also
151check the <a href="http://swig.cs.uchicago.edu/cgi-bin/wiki.pl">SWIG Wiki</a> for
152additional information.
153</p>
154
155<p>
156When linking the module, the name of the output file has to match the name
157of the module. If the name of your SWIG module is "<tt>example</tt>", the
158name of the corresponding object file should be
159"<tt>example.so</tt>".
160The name of the module is specified using the <tt>%module</tt> directive or the
161<tt> -module</tt> command line option.
162</p>
163
164<H3><a name="Tcl_nn5"></a>28.1.3 Static linking</H3>
165
166
167<p>
168An alternative approach to dynamic linking is to rebuild the Tcl
169interpreter with your extension module added to it. In the past,
170this approach was sometimes necesssary due to limitations in dynamic loading
171support on certain machines. However, the situation has improved greatly
172over the last few years and you should not consider this approach
173unless there is really no other option.
174</p>
175
176<p>
177The usual procedure for adding a new module to Tcl involves writing a
178special function <tt>Tcl_AppInit()</tt> and using it to initialize the interpreter and
179your module. With SWIG, the <tt>tclsh.i</tt> and <tt>wish.i</tt> library files
180can be used to rebuild the <tt>tclsh</tt> and <tt>wish</tt> interpreters respectively.
181For example:
182</p>
183
184<div class="code"><pre>
185%module example
186
187%inline %{
188extern int fact(int);
189extern int mod(int, int);
190extern double My_variable;
191%}
192
193%include tclsh.i // Include code for rebuilding tclsh
194
195</pre></div>
196
197<p>
198The <tt>tclsh.i</tt> library file includes supporting code that
199contains everything needed to rebuild tclsh. To rebuild the interpreter,
200you simply do something like this:
201</p>
202
203<div class="code"><pre>
204$ swig -tcl example.i
205$ gcc example.c example_wrap.c \
206 -Xlinker -export-dynamic \
207 -DHAVE_CONFIG_H -I/usr/local/include/ \
208 -L/usr/local/lib -ltcl -lm -ldl \
209 -o mytclsh
210
211</pre></div>
212
213<p>
214You will need to supply the same libraries that were used to build Tcl the first
215time. This may include system libraries such as <tt>-lsocket</tt>, <tt>-lnsl</tt>,
216and <tt>-lpthread</tt>. If this actually works, the new version of Tcl
217should be identical to the default version except that your extension module will be
218a built-in part of the interpreter.
219</p>
220
221<p>
222<b>Comment:</b> In practice, you should probably try to avoid static
223linking if possible. Some programmers may be inclined
224to use static linking in the interest of getting better performance.
225However, the performance gained by static linking tends to be rather
226minimal in most situations (and quite frankly not worth the extra
227hassle in the opinion of this author).
228</p>
229
230<H3><a name="Tcl_nn6"></a>28.1.4 Using your module</H3>
231
232
233<p>
234To use your module, simply use the Tcl <tt>load</tt> command. If
235all goes well, you will be able to this:
236</p>
237
238<div class="code"><pre>
239$ tclsh
240% load ./example.so
241% fact 4
24224
243%
244</pre></div>
245
246<p>
247A common error received by first-time users is the following:
248</p>
249
250<div class="code">
251<pre>
252% load ./example.so
253couldn't find procedure Example_Init
254%
255</pre>
256</div>
257
258<p>
259This error is almost always caused when the name of the shared object file doesn't
260match the name of the module supplied using the SWIG <tt>%module</tt> directive.
261Double-check the interface to make sure the module name and the shared object
262file match. Another possible cause of this error is forgetting to link the SWIG-generated
263wrapper code with the rest of your application when creating the extension module.
264</p>
265
266<p>
267Another common error is something similar to the following:
268</p>
269
270<div class="code">
271<pre>
272% load ./example.so
273couldn't load file "./example.so": ./example.so: undefined symbol: fact
274%
275</pre>
276</div>
277
278<p>
279This error usually indicates that you forgot to include some object
280files or libraries in the linking of the shared library file. Make
281sure you compile both the SWIG wrapper file and your original program
282into a shared library file. Make sure you pass all of the required libraries
283to the linker.
284</p>
285
286<p>
287Sometimes unresolved symbols occur because a wrapper has been created
288for a function that doesn't actually exist in a library. This usually
289occurs when a header file includes a declaration for a function that
290was never actually implemented or it was removed from a library
291without updating the header file. To fix this, you can either edit
292the SWIG input file to remove the offending declaration or you can use
293the <tt>%ignore</tt> directive to ignore the declaration.
294</p>
295
296<p>
297Finally, suppose that your extension module is linked with another library like this:
298</p>
299
300<div class="code">
301<pre>
302$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
303 -o example.so
304</pre>
305</div>
306
307<p>
308If the <tt>foo</tt> library is compiled as a shared library, you might get the following
309problem when you try to use your module:
310</p>
311
312<div class="code">
313<pre>
314% load ./example.so
315couldn't load file "./example.so": libfoo.so: cannot open shared object file:
316No such file or directory
317%
318</pre>
319</div>
320
321<p>
322This error is generated because the dynamic linker can't locate the
323<tt>libfoo.so</tt> library. When shared libraries are loaded, the
324system normally only checks a few standard locations such as
325<tt>/usr/lib</tt> and <tt>/usr/local/lib</tt>. To fix this problem,
326there are several things you can do. First, you can recompile your extension
327module with extra path information. For example, on Linux you can do this:
328</p>
329
330<div class="code">
331<pre>
332$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
333 -Xlinker -rpath /home/beazley/projects/lib \
334 -o example.so
335</pre>
336</div>
337
338<p>
339Alternatively, you can set the <tt>LD_LIBRARY_PATH</tt> environment variable to
340include the directory with your shared libraries.
341If setting <tt>LD_LIBRARY_PATH</tt>, be aware that setting this variable can introduce
342a noticeable performance impact on all other applications that you run.
343To set it only for Tcl, you might want to do this instead:
344</p>
345
346<div class="code">
347<pre>
348$ env LD_LIBRARY_PATH=/home/beazley/projects/lib tclsh
349</pre>
350</div>
351
352<p>
353Finally, you can use a command such as <tt>ldconfig</tt> to add additional search paths
354to the default system configuration (this requires root access and you will need to read
355the man pages).
356</p>
357
358<H3><a name="Tcl_nn7"></a>28.1.5 Compilation of C++ extensions</H3>
359
360
361<p>
362Compilation of C++ extensions has traditionally been a tricky problem.
363Since the Tcl interpreter is written in C, you need to take steps to
364make sure C++ is properly initialized and that modules are compiled
365correctly.
366</p>
367
368<p>
369On most machines, C++ extension modules should be linked using the C++
370compiler. For example:
371</p>
372
373<div class="code"><pre>
374% swig -c++ -tcl example.i
375% g++ -c example.cxx
376% g++ -c example_wrap.cxx -I/usr/local/include
377% g++ -shared example.o example_wrap.o -o example.so
378</pre></div>
379
380<p>
381In addition to this, you may need to include additional library
382files to make it work. For example, if you are using the Sun C++ compiler on
383Solaris, you often need to add an extra library <tt>-lCrun</tt> like this:
384</p>
385
386<div class="code"><pre>
387% swig -c++ -tcl example.i
388% CC -c example.cxx
389% CC -c example_wrap.cxx -I/usr/local/include
390% CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o example.so -lCrun
391</pre></div>
392
393<p>
394Of course, the extra libraries to use are completely non-portable---you will
395probably need to do some experimentation.
396</p>
397
398<p>
399Sometimes people have suggested that it is necessary to relink the
400Tcl interpreter using the C++ compiler to make C++ extension modules work.
401In the experience of this author, this has never actually appeared to be
402necessary. Relinking the interpreter with C++ really only includes the
403special run-time libraries described above---as long as you link your extension
404modules with these libraries, it should not be necessary to rebuild Tcl.
405</p>
406
407<p>
408If you aren't entirely sure about the linking of a C++ extension, you
409might look at an existing C++ program. On many Unix machines, the
410<tt>ldd</tt> command will list library dependencies. This should give
411you some clues about what you might have to include when you link your
412extension module. For example:
413</p>
414
415<div class="code">
416<pre>
417$ ldd swig
418 libstdc++-libc6.1-1.so.2 =&gt; /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
419 libm.so.6 =&gt; /lib/libm.so.6 (0x4005b000)
420 libc.so.6 =&gt; /lib/libc.so.6 (0x40077000)
421 /lib/ld-linux.so.2 =&gt; /lib/ld-linux.so.2 (0x40000000)
422$
423</pre>
424</div>
425
426<p>
427As a final complication, a major weakness of C++ is that it does not
428define any sort of standard for binary linking of libraries. This
429means that C++ code compiled by different compilers will not link
430together properly as libraries nor is the memory layout of classes and
431data structures implemented in any kind of portable manner. In a
432monolithic C++ program, this problem may be unnoticed. However, in Tcl, it
433is possible for different extension modules to be compiled with
434different C++ compilers. As long as these modules are self-contained,
435this probably won't matter. However, if these modules start sharing data,
436you will need to take steps to avoid segmentation faults and other
437erratic program behavior. If working with lots of software components, you
438might want to investigate using a more formal standard such as COM.
439</p>
440
441<H3><a name="Tcl_nn8"></a>28.1.6 Compiling for 64-bit platforms</H3>
442
443
444<p>
445On platforms that support 64-bit applications (Solaris, Irix, etc.),
446special care is required when building extension modules. On these
447machines, 64-bit applications are compiled and linked using a different
448set of compiler/linker options. In addition, it is not generally possible to mix
44932-bit and 64-bit code together in the same application.
450</p>
451
452<p>
453To utilize 64-bits, the Tcl executable will need to be recompiled
454as a 64-bit application. In addition, all libraries, wrapper code,
455and every other part of your application will need to be compiled for
45664-bits. If you plan to use other third-party extension modules, they
457will also have to be recompiled as 64-bit extensions.
458</p>
459
460<p>
461If you are wrapping commercial software for which you have no source
462code, you will be forced to use the same linking standard as used by
463that software. This may prevent the use of 64-bit extensions. It may
464also introduce problems on platforms that support more than one
465linking standard (e.g., -o32 and -n32 on Irix).
466</p>
467
468<H3><a name="Tcl_nn9"></a>28.1.7 Setting a package prefix</H3>
469
470
471<p>
472To avoid namespace problems, you can instruct SWIG to append a package
473prefix to all of your functions and variables. This is done using the
474-prefix option as follows :
475</p>
476
477<div class="code"><pre>
478swig -tcl -prefix Foo example.i
479</pre></div>
480
481<p>
482If you have a function "<tt>bar</tt>" in the SWIG file, the prefix
483option will append the prefix to the name when creating a command and
484call it "<tt>Foo_bar</tt>".
485</p>
486
487<H3><a name="Tcl_nn10"></a>28.1.8 Using namespaces</H3>
488
489
490<p>
491Alternatively, you can have SWIG install your module into a Tcl
492namespace by specifying the <tt>-namespace</tt> option :
493</p>
494
495<div class="code"><pre>
496swig -tcl -namespace example.i
497</pre></div>
498
499<p>
500By default, the name of the namespace will be the same as the module
501name, but you can override it using the <tt>-prefix</tt> option.
502</p>
503
504<p>
505When the<tt> -namespace</tt> option is used, objects in the module
506are always accessed with the namespace name such as <tt>Foo::bar</tt>.
507</p>
508
509<H2><a name="Tcl_nn11"></a>28.2 Building Tcl/Tk Extensions under Windows 95/NT</H2>
510
511
512<p>
513Building a SWIG extension to Tcl/Tk under Windows 95/NT is roughly
514similar to the process used with Unix. Normally, you will want to
515produce a DLL that can be loaded into tclsh or wish. This section
516covers the process of using SWIG with Microsoft Visual C++.
517although the procedure may be similar with other compilers.
518</p>
519
520<H3><a name="Tcl_nn12"></a>28.2.1 Running SWIG from Developer Studio</H3>
521
522
523<p>
524If you are developing your application within Microsoft developer
525studio, SWIG can be invoked as a custom build option. The process
526roughly follows these steps :
527</p>
528
529<ul>
530<li>Open up a new workspace and use the AppWizard to select a DLL project.
531
532<li>Add both the SWIG interface file (the .i file), any supporting C
533files, and the name of the wrapper file that will be created by SWIG
534(ie. <tt>example_wrap.c</tt>). Note : If using C++, choose a
535different suffix for the wrapper file such as
536<tt>example_wrap.cxx</tt>. Don't worry if the wrapper file doesn't
537exist yet--Developer studio will keep a reference to it around.
538
539<li>Select the SWIG interface file and go to the settings menu. Under
540settings, select the "Custom Build" option.
541
542<li>Enter "SWIG" in the description field.
543
544<li>Enter "<tt>swig -tcl -o $(ProjDir)\$(InputName)_wrap.c
545$(InputPath)</tt>" in the "Build command(s) field"
546
547<li>Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>" in the "Output files(s) field".
548
549<li>Next, select the settings for the entire project and go to
550"C++:Preprocessor". Add the include directories for your Tcl
551installation under "Additional include directories".
552
553<li>Finally, select the settings for the entire project and go to
554"Link Options". Add the Tcl library file to your link libraries. For
555example "<tt>tcl80.lib</tt>". Also, set the name of the output file
556to match the name of your Tcl module (ie. example.dll).
557
558<li>Build your project.
559</ul>
560
561<p>
562Now, assuming all went well, SWIG will be automatically invoked when
563you build your project. Any changes made to the interface file will
564result in SWIG being automatically invoked to produce a new version of
565the wrapper file. To run your new Tcl extension, simply run
566<tt>tclsh</tt> or <tt>wish</tt> and use the <tt>load</tt> command.
567For example :
568</p>
569
570<div class="code"><pre>
571MSDOS &gt; tclsh80
572% load example.dll
573% fact 4
57424
575%
576</pre></div>
577
578<H3><a name="Tcl_nn13"></a>28.2.2 Using NMAKE</H3>
579
580
581<p>
582Alternatively, SWIG extensions can be built by writing a Makefile for
583NMAKE. To do this, make sure the environment variables for MSVC++ are
584available and the MSVC++ tools are in your path. Now, just write a
585short Makefile like this :
586</p>
587
588<div class="code"><pre>
589# Makefile for building various SWIG generated extensions
590
591SRCS = example.c
592IFILE = example
593INTERFACE = $(IFILE).i
594WRAPFILE = $(IFILE)_wrap.c
595
596# Location of the Visual C++ tools (32 bit assumed)
597
598TOOLS = c:\msdev
599TARGET = example.dll
600CC = $(TOOLS)\bin\cl.exe
601LINK = $(TOOLS)\bin\link.exe
602INCLUDE32 = -I$(TOOLS)\include
603MACHINE = IX86
604
605# C Library needed to build a DLL
606
607DLLIBC = msvcrt.lib oldnames.lib
608
609# Windows libraries that are apparently needed
610WINLIB = kernel32.lib advapi32.lib user32.lib gdi32.lib comdlg32.lib
611winspool.lib
612
613# Libraries common to all DLLs
614LIBS = $(DLLIBC) $(WINLIB)
615
616# Linker options
617LOPT = -debug:full -debugtype:cv /NODEFAULTLIB /RELEASE /NOLOGO /
618MACHINE:$(MACHINE) -entry:_DllMainCRTStartup@12 -dll
619
620# C compiler flags
621
622CFLAGS = /Z7 /Od /c /nologo
623TCL_INCLUDES = -Id:\tcl8.0a2\generic -Id:\tcl8.0a2\win
624TCLLIB = d:\tcl8.0a2\win\tcl80.lib
625
626tcl::
627 ..\..\swig -tcl -o $(WRAPFILE) $(INTERFACE)
628 $(CC) $(CFLAGS) $(TCL_INCLUDES) $(SRCS) $(WRAPFILE)
629 set LIB=$(TOOLS)\lib
630 $(LINK) $(LOPT) -out:example.dll $(LIBS) $(TCLLIB) example.obj example_wrap.obj
631
632</pre></div>
633
634<p>
635To build the extension, run NMAKE (you may need to run vcvars32
636first). This is a pretty minimal Makefile, but hopefully its enough
637to get you started. With a little practice, you'll be making lots of
638Tcl extensions.
639</p>
640
641<H2><a name="Tcl_nn14"></a>28.3 A tour of basic C/C++ wrapping</H2>
642
643
644<p>
645By default, SWIG tries to build a very natural Tcl interface to your
646C/C++ code. Functions are wrapped as functions, classes are wrapped
647in an interface that mimics the style of Tk widgets and [incr Tcl]
648classes. This section briefly covers the essential aspects of this
649wrapping.
650</p>
651
652<H3><a name="Tcl_nn15"></a>28.3.1 Modules</H3>
653
654
655<p>
656The SWIG <tt>%module</tt> directive specifies the name of the Tcl
657module. If you specify `<tt>%module example</tt>', then everything is
658compiled into an extension module <tt>example.so</tt>. When choosing a
659module name, make sure you don't use the same name as a built-in
660Tcl command.
661</p>
662
663<p>
664One pitfall to watch out for is module names involving numbers. If
665you specify a module name like <tt>%module md5</tt>, you'll find that the
666load command no longer seems to work:
667</p>
668
669<div class="code">
670<pre>
671% load ./md5.so
672couldn't find procedure Md_Init
673</pre>
674</div>
675
676<p>
677To fix this, supply an extra argument to <tt>load</tt> like this:
678</p>
679
680<div class="code">
681<pre>
682% load ./md5.so md5
683</pre>
684</div>
685
686<H3><a name="Tcl_nn16"></a>28.3.2 Functions</H3>
687
688
689<p>
690Global functions are wrapped as new Tcl built-in commands. For example,
691</p>
692
693<div class="code"><pre>
694%module example
695int fact(int n);
696</pre></div>
697
698<p>
699creates a built-in function <tt>fact</tt> that works exactly
700like you think it does:
701</p>
702
703<div class="code"><pre>
704% load ./example.so
705% fact 4
70624
707% set x [fact 6]
708%
709</pre></div>
710
711<H3><a name="Tcl_nn17"></a>28.3.3 Global variables</H3>
712
713
714<p>
715C/C++ global variables are wrapped by Tcl global variables. For example:
716</p>
717
718<div class="code"><pre>
719// SWIG interface file with global variables
720%module example
721...
722%inline %{
723extern double density;
724%}
725...
726</pre></div>
727
728<p>
729Now look at the Tcl interface:
730</p>
731
732<div class="code"><pre>
733% puts $density # Output value of C global variable
7341.0
735% set density 0.95 # Change value
736</pre></div>
737
738<p>
739If you make an error in variable assignment, you will get an
740error message. For example:
741</p>
742
743<div class="code"><pre>
744% set density "hello"
745can't set "density": Type error. expected a double.
746%
747</pre></div>
748
749<p>
750If a variable is declared as <tt>const</tt>, it is wrapped as a
751read-only variable. Attempts to modify its value will result in an
752error.
753</p>
754
755<p>
756To make ordinary variables read-only, you can use the <tt>%immutable</tt> directive. For example:
757</p>
758
759<div class="code">
760<pre>
761%{
762extern char *path;
763%}
764%immutable;
765extern char *path;
766%mutable;
767</pre>
768</div>
769
770<p>
771The <tt>%immutable</tt> directive stays in effect until it is explicitly disabled or cleared using
772<tt>%mutable</tt>.
773See the <a href="SWIG.html#SWIG_readonly_variables">Creatng read-only variables</a> section for further details.
774</p>
775
776<p>
777If you just want to make a specific variable immutable, supply a declaration name. For example:
778</p>
779
780<div class="code">
781<pre>
782%{
783extern char *path;
784%}
785%immutable path;
786...
787extern char *path; // Read-only (due to %immutable)
788</pre>
789</div>
790
791<H3><a name="Tcl_nn18"></a>28.3.4 Constants and enums</H3>
792
793
794<p>
795C/C++ constants are installed as global Tcl variables containing the
796appropriate value. To create a constant, use <tt>#define</tt>, <tt>enum</tt>, or the
797<tt>%constant</tt> directive. For example:
798</p>
799
800<div class="code">
801<pre>
802#define PI 3.14159
803#define VERSION "1.0"
804
805enum Beverage { ALE, LAGER, STOUT, PILSNER };
806
807%constant int FOO = 42;
808%constant const char *path = "/usr/local";
809</pre>
810</div>
811
812<p>
813For enums, make sure that the definition of the enumeration actually appears in a header
814file or in the wrapper file somehow---if you just stick an enum in a SWIG interface without
815also telling the C compiler about it, the wrapper code won't compile.
816</p>
817
818<p>
819Note: declarations declared as <tt>const</tt> are wrapped as read-only variables and
820will be accessed using the <tt>cvar</tt> object described in the previous section. They
821are not wrapped as constants. For further discussion about this, see the <a href="SWIG.html#SWIG">SWIG Basics</a> chapter.
822</p>
823
824<p>
825Constants are not guaranteed to remain constant in Tcl---the value
826of the constant could be accidentally reassigned.You will just have to be careful.
827</p>
828
829<p>
830A peculiarity of installing constants as variables is that it is necessary to use the Tcl <tt>global</tt> statement to
831access constants in procedure bodies. For example:
832</p>
833
834<div class="code">
835<pre>
836proc blah {} {
837 global FOO
838 bar $FOO
839}
840</pre>
841</div>
842
843<p>
844If a program relies on a lot of constants, this can be extremely annoying. To fix the problem, consider using the
845following typemap rule:
846</p>
847
848<div class="code">
849<pre>
850%apply int CONSTANT { int x };
851#define FOO 42
852...
853void bar(int x);
854</pre>
855</div>
856
857<p>
858When applied to an input argument, the <tt>CONSTANT</tt> rule allows a constant to be passed to a function using
859its actual value or a symbolic identifier name. For example:
860</p>
861
862<div class="code">
863<pre>
864proc blah {} {
865 bar FOO
866}
867</pre>
868</div>
869
870<p>
871When an identifier name is given, it is used to perform an implicit hash-table lookup of the value during argument
872conversion. This allows the <tt>global</tt> statement to be ommitted.
873</p>
874
875<H3><a name="Tcl_nn19"></a>28.3.5 Pointers</H3>
876
877
878<p>
879C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with
880incomplete type information. Here is a rather simple interface:
881</p>
882
883<div class="code">
884<pre>
885%module example
886
887FILE *fopen(const char *filename, const char *mode);
888int fputs(const char *, FILE *);
889int fclose(FILE *);
890</pre>
891</div>
892
893<p>
894When wrapped, you will be able to use the functions in a natural way from Tcl.
895For example:
896</p>
897
898<div class="code">
899<pre>
900% load ./example.so
901% set f [fopen junk w]
902% fputs "Hello World\n" $f
903% fclose $f
904</pre>
905</div>
906
907<p>
908If this makes you uneasy, rest assured that there is no
909deep magic involved. Underneath the covers, pointers to C/C++ objects are
910simply represented as opaque values--normally an encoded character
911string like this:
912</p>
913
914<div class="code"><pre>
915% puts $f
916_c0671108_p_FILE
917%
918</pre></div>
919
920<p>
921This pointer value can be freely passed around to different C functions that
922expect to receive an object of type <tt>FILE *</tt>. The only thing you can't do is
923dereference the pointer from Tcl.
924</p>
925
926<p>
927The NULL pointer is represented by the string <tt>NULL</tt>.
928</p>
929
930<p>
931As much as you might be inclined to modify a pointer value directly
932from Tcl, don't. The hexadecimal encoding is not necessarily the
933same as the logical memory address of the underlying object. Instead
934it is the raw byte encoding of the pointer value. The encoding will
935vary depending on the native byte-ordering of the platform (i.e.,
936big-endian vs. little-endian). Similarly, don't try to manually cast
937a pointer to a new type by simply replacing the type-string. This
938may not work like you expect and it is particularly dangerous when
939casting C++ objects. If you need to cast a pointer or
940change its value, consider writing some helper functions instead. For
941example:
942</p>
943
944<div class="code">
945<pre>
946%inline %{
947/* C-style cast */
948Bar *FooToBar(Foo *f) {
949 return (Bar *) f;
950}
951
952/* C++-style cast */
953Foo *BarToFoo(Bar *b) {
954 return dynamic_cast&lt;Foo*&gt;(b);
955}
956
957Foo *IncrFoo(Foo *f, int i) {
958 return f+i;
959}
960%}
961</pre>
962</div>
963
964<p>
965Also, if working with C++, you should always try
966to use the new C++ style casts. For example, in the above code, the
967C-style cast may return a bogus result whereas as the C++-style cast will return
968<tt>None</tt> if the conversion can't be performed.
969</p>
970
971<H3><a name="Tcl_nn20"></a>28.3.6 Structures</H3>
972
973
974<p>
975If you wrap a C structure, it is wrapped by a Tcl interface that somewhat resembles a Tk widget.
976This provides a very natural interface. For example,
977</p>
978
979<div class="code"><pre>
980struct Vector {
981 double x,y,z;
982};
983
984</pre></div>
985
986<p>
987is used as follows:
988</p>
989
990<div class="code"><pre>
991% Vector v
992% v configure -x 3.5 -y 7.2
993% puts "[v cget -x] [v cget -y] [v cget -z]"
9943.5 7.2 0.0
995%
996</pre></div>
997
998<p>
999Similar access is provided for unions and the data members of C++ classes.
1000</p>
1001
1002<p>
1003In the above example, <tt>v</tt> is a name that's used for the object. However,
1004underneath the covers, there's a pointer to a raw C structure. This can be obtained
1005by looking at the <tt>-this</tt> attribute. For example:
1006</p>
1007
1008<div class="code">
1009<pre>
1010% puts [v cget -this]
1011_88e31408_p_Vector
1012</pre>
1013</div>
1014
1015<p>
1016Further details about the relationship between the Tcl and the underlying C structure
1017are covered a little later.
1018</p>
1019
1020<p>
1021<tt>const</tt> members of a structure are read-only. Data members
1022can also be forced to be read-only using the <tt>%immutable</tt> directive. For example:
1023</p>
1024
1025<div class="code">
1026<pre>
1027struct Foo {
1028 ...
1029 %immutable;
1030 int x; /* Read-only members */
1031 char *name;
1032 %mutable;
1033 ...
1034};
1035</pre>
1036</div>
1037
1038<p>
1039When <tt>char *</tt> members of a structure are wrapped, the contents are assumed to be
1040dynamically allocated using <tt>malloc</tt> or <tt>new</tt> (depending on whether or not
1041SWIG is run with the -c++ option). When the structure member is set, the old contents will be
1042released and a new value created. If this is not the behavior you want, you will have to use
1043a typemap (described later).
1044</p>
1045
1046<p>
1047If a structure contains arrays, access to those arrays is managed through pointers. For
1048example, consider this:
1049</p>
1050
1051<div class="code">
1052<pre>
1053struct Bar {
1054 int x[16];
1055};
1056</pre>
1057</div>
1058
1059<p>
1060If accessed in Tcl, you will see behavior like this:
1061</p>
1062
1063<div class="code">
1064<pre>
1065% Bar b
1066% puts [b cget -x]
1067_801861a4_p_int
1068%
1069</pre>
1070</div>
1071
1072<p>
1073This pointer can be passed around to functions that expect to receive
1074an <tt>int *</tt> (just like C). You can also set the value of an array member using
1075another pointer. For example:
1076</p>
1077
1078<div class="code">
1079<pre>
1080% Bar c
1081% c configure -x [b cget -x] # Copy contents of b.x to c.x
1082</pre>
1083</div>
1084
1085<p>
1086For array assignment, SWIG copies the entire contents of the array starting with the data pointed
1087to by <tt>b.x</tt>. In this example, 16 integers would be copied. Like C, SWIG makes
1088no assumptions about bounds checking---if you pass a bad pointer, you may get a segmentation
1089fault or access violation.
1090</p>
1091
1092<p>
1093When a member of a structure is itself a structure, it is handled as a
1094pointer. For example, suppose you have two structures like this:
1095</p>
1096
1097<div class="code">
1098<pre>
1099struct Foo {
1100 int a;
1101};
1102
1103struct Bar {
1104 Foo f;
1105};
1106</pre>
1107</div>
1108
1109<p>
1110Now, suppose that you access the <tt>f</tt> attribute of <tt>Bar</tt> like this:
1111</p>
1112
1113<div class="code">
1114<pre>
1115% Bar b
1116% set x [b cget -f]
1117</pre>
1118</div>
1119
1120<p>
1121In this case, <tt>x</tt> is a pointer that points to the <tt>Foo</tt> that is inside <tt>b</tt>.
1122This is the same value as generated by this C code:
1123</p>
1124
1125<div class="code">
1126<pre>
1127Bar b;
1128Foo *x = &amp;b-&gt;f; /* Points inside b */
1129</pre>
1130</div>
1131
1132<p>
1133However, one peculiarity of accessing a substructure like this is that the returned
1134value does work quite like you might expect. For example:
1135</p>
1136
1137<div class="code">
1138<pre>
1139% Bar b
1140% set x [b cget -f]
1141% x cget -a
1142invalid command name "x"
1143</pre>
1144</div>
1145
1146<p>
1147This is because the returned value was not created in a normal way from the interpreter (x is
1148not a command object). To make it function normally, just
1149evaluate the variable like this:
1150</p>
1151
1152<div class="code">
1153<pre>
1154% Bar b
1155% set x [b cget -f]
1156% $x cget -a
11570
1158%
1159</pre>
1160</div>
1161
1162<p>
1163In this example, <tt>x</tt> points inside the original structure. This means that modifications
1164work just like you would expect. For example:
1165</p>
1166
1167<div class="code">
1168<pre>
1169
1170% Bar b
1171% set x [b cget -f]
1172% $x configure -a 3 # Modifies contents of f (inside b)
1173% [b cget -f] -configure -a 3 # Same thing
1174</pre>
1175</div>
1176
1177<p>
1178In many of these structure examples, a simple name like "v" or "b" has been given
1179to wrapped structures. If necessary, this name can be passed to functions
1180that expect to receive an object. For example, if you have a function like this,
1181</p>
1182
1183<div class="code">
1184<pre>
1185void blah(Foo *f);
1186</pre>
1187</div>
1188
1189<p>
1190you can call the function in Tcl as follows:
1191</p>
1192
1193<div class="code">
1194<pre>
1195% Foo x # Create a Foo object
1196% blah x # Pass the object to a function
1197</pre>
1198</div>
1199
1200<p>
1201It is also possible to call the function using the raw pointer value. For
1202instance:
1203</p>
1204
1205<div class="code">
1206<pre>
1207% blah [x cget -this] # Pass object to a function
1208</pre>
1209</div>
1210
1211<p>
1212It is also possible to create and use objects using variables. For example:
1213</p>
1214
1215<div class="code">
1216<pre>
1217% set b [Bar] # Create a Bar
1218% $b cget -f # Member access
1219% puts $b
1220_108fea88_p_Bar
1221%
1222</pre>
1223</div>
1224
1225<p>
1226Finally, to destroy objects created from Tcl, you can either let the object
1227name go out of scope or you can explicitly delete the object. For example:
1228</p>
1229
1230<div class="code">
1231<pre>
1232% Foo f # Create object f
1233% rename f ""
1234</pre>
1235</div>
1236
1237<p>
1238or
1239</p>
1240
1241<div class="code">
1242<pre>
1243% Foo f # Create object f
1244% f -delete
1245</pre>
1246</div>
1247
1248<p>
1249Note: Tcl only destroys the underlying object if it has ownership. See the
1250memory management section that appears shortly.
1251</p>
1252
1253<H3><a name="Tcl_nn21"></a>28.3.7 C++ classes</H3>
1254
1255
1256<p>
1257C++ classes are wrapped as an extension of structure wrapping. For example, if you have this class,
1258</p>
1259
1260<div class="code"><pre>
1261class List {
1262public:
1263 List();
1264 ~List();
1265 int search(char *item);
1266 void insert(char *item);
1267 void remove(char *item);
1268 char *get(int n);
1269 int length;
1270};
1271</pre></div>
1272
1273<p>
1274you can use it in Tcl like this:
1275</p>
1276
1277<div class="code"><pre>
1278% List x
1279% x insert Ale
1280% x insert Stout
1281% x insert Lager
1282% x get 1
1283Stout
1284% puts [l cget -length]
12853
1286%
1287</pre></div>
1288
1289<p>
1290Class data members are accessed in the same manner as C structures.
1291</p>
1292
1293<p>
1294Static class members are accessed as global functions or variables.
1295To illustrate, suppose you have a class like this:
1296</p>
1297
1298<div class="code">
1299<pre>
1300class Spam {
1301public:
1302 static void foo();
1303 static int bar;
1304
1305};
1306</pre>
1307</div>
1308
1309<p>
1310In Tcl, the static member is accessed as follows:
1311</p>
1312
1313<div class="code">
1314<pre>
1315% Spam_foo # Spam::foo()
1316% puts $Spam_bar # Spam::bar
1317</pre>
1318</div>
1319
1320<H3><a name="Tcl_nn22"></a>28.3.8 C++ inheritance</H3>
1321
1322
1323<p>
1324SWIG is fully aware of issues related to C++ inheritance. Therefore, if you have
1325classes like this
1326</p>
1327
1328<div class="code">
1329<pre>
1330class Foo {
1331...
1332};
1333
1334class Bar : public Foo {
1335...
1336};
1337</pre>
1338</div>
1339
1340<p>
1341An object of type <tt>Bar</tt> can be used where a <tt>Foo</tt> is expected. For
1342example, if you have this function:
1343</p>
1344
1345<div class="code">
1346<pre>
1347void spam(Foo *f);
1348</pre>
1349</div>
1350
1351<p>
1352then the function <tt>spam()</tt> accepts a <tt>Foo *</tt> or a pointer to any class derived from <tt>Foo</tt>.
1353For instance:
1354</p>
1355
1356<div class="code">
1357<pre>
1358% Foo f # Create a Foo
1359% Bar b # Create a Bar
1360% spam f # OK
1361% spam b # OK
1362</pre>
1363</div>
1364
1365<p>
1366It is safe to use multiple inheritance with SWIG.
1367</p>
1368
1369<H3><a name="Tcl_nn23"></a>28.3.9 Pointers, references, values, and arrays</H3>
1370
1371
1372<p>
1373In C++, there are many different ways a function might receive
1374and manipulate objects. For example:
1375</p>
1376
1377<div class="code">
1378<pre>
1379void spam1(Foo *x); // Pass by pointer
1380void spam2(Foo &amp;x); // Pass by reference
1381void spam3(Foo x); // Pass by value
1382void spam4(Foo x[]); // Array of objects
1383</pre>
1384</div>
1385
1386<p>
1387In Tcl, there is no detailed distinction like this.
1388Because of this, SWIG unifies all of these types
1389together in the wrapper code. For instance, if you actually had the
1390above functions, it is perfectly legal to do this:
1391</p>
1392
1393<div class="code">
1394<pre>
1395% Foo f # Create a Foo
1396% spam1 f # Ok. Pointer
1397% spam2 f # Ok. Reference
1398% spam3 f # Ok. Value.
1399% spam4 f # Ok. Array (1 element)
1400</pre>
1401</div>
1402
1403<p>
1404Similar behavior occurs for return values. For example, if you had
1405functions like this,
1406</p>
1407
1408<div class="code">
1409<pre>
1410Foo *spam5();
1411Foo &amp;spam6();
1412Foo spam7();
1413</pre>
1414</div>
1415
1416<p>
1417then all three functions will return a pointer to some <tt>Foo</tt> object.
1418Since the third function (spam7) returns a value, newly allocated memory is used
1419to hold the result and a pointer is returned (Tcl will release this memory
1420when the return value is garbage collected).
1421</p>
1422
1423<H3><a name="Tcl_nn24"></a>28.3.10 C++ overloaded functions</H3>
1424
1425
1426<p>
1427C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example,
1428if you have two functions like this:
1429</p>
1430
1431<div class="code">
1432<pre>
1433void foo(int);
1434void foo(char *c);
1435</pre>
1436</div>
1437
1438<p>
1439You can use them in Tcl in a straightforward manner:
1440</p>
1441
1442<div class="code">
1443<pre>
1444% foo 3 # foo(int)
1445% foo Hello # foo(char *c)
1446</pre>
1447</div>
1448
1449<p>
1450Similarly, if you have a class like this,
1451</p>
1452
1453<div class="code">
1454<pre>
1455class Foo {
1456public:
1457 Foo();
1458 Foo(const Foo &amp;);
1459 ...
1460};
1461</pre>
1462</div>
1463
1464<p>
1465you can write Tcl code like this:
1466</p>
1467
1468<div class="code">
1469<pre>
1470% Foo f # Create a Foo
1471% Foo g f # Copy f
1472</pre>
1473</div>
1474
1475<p>
1476Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG
1477can't disambiguate. For example:
1478</p>
1479
1480<div class="code">
1481<pre>
1482void spam(int);
1483void spam(short);
1484</pre>
1485</div>
1486
1487<p>
1488or
1489</p>
1490
1491<div class="code">
1492<pre>
1493void foo(Bar *b);
1494void foo(Bar &amp;b);
1495</pre>
1496</div>
1497
1498<p>
1499If declarations such as these appear, you will get a warning message like this:
1500</p>
1501
1502<div class="code">
1503<pre>
1504example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)
1505at example.i:11.
1506</pre>
1507</div>
1508
1509<p>
1510To fix this, you either need to ignore or rename one of the methods. For example:
1511</p>
1512
1513<div class="code">
1514<pre>
1515%rename(spam_short) spam(short);
1516...
1517void spam(int);
1518void spam(short); // Accessed as spam_short
1519</pre>
1520</div>
1521
1522<p>
1523or
1524</p>
1525
1526<div class="code">
1527<pre>
1528%ignore spam(short);
1529...
1530void spam(int);
1531void spam(short); // Ignored
1532</pre>
1533</div>
1534
1535<p>
1536SWIG resolves overloaded functions and methods using a disambiguation scheme that ranks and sorts
1537declarations according to a set of type-precedence rules. The order in which declarations appear
1538in the input does not matter except in situations where ambiguity arises--in this case, the
1539first declaration takes precedence.
1540</p>
1541
1542<p>
1543Please refer to the "SWIG and C++" chapter for more information about overloading.
1544</p>
1545
1546<H3><a name="Tcl_nn25"></a>28.3.11 C++ operators</H3>
1547
1548
1549<p>
1550Certain C++ overloaded operators can be handled automatically by SWIG. For example,
1551consider a class like this:
1552</p>
1553
1554<div class="code">
1555<pre>
1556class Complex {
1557private:
1558 double rpart, ipart;
1559public:
1560 Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
1561 Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
1562 Complex &amp;operator=(const Complex &amp;c);
1563 Complex operator+(const Complex &amp;c) const;
1564 Complex operator-(const Complex &amp;c) const;
1565 Complex operator*(const Complex &amp;c) const;
1566 Complex operator-() const;
1567
1568 double re() const { return rpart; }
1569 double im() const { return ipart; }
1570};
1571</pre>
1572</div>
1573
1574<p>
1575When wrapped, it works like this:
1576</p>
1577
1578<div class="code">
1579<pre>
1580% Complex c 3 4
1581% Complex d 7 8
1582% set e [c + d]
1583% $e re
158410.0
1585% $e im
158612.0
1587</pre>
1588</div>
1589
1590<p>
1591It should be stressed that operators in SWIG have no relationship to operators
1592in Tcl. In fact, the only thing that's happening here is that an operator like
1593<tt>operator +</tt> has been renamed to a method <tt>+</tt>. Therefore, the
1594statement <tt>[c + d]</tt> is really just invoking the <tt>+</tt> method on <tt>c</tt>.
1595When more than operator is defined (with different arguments), the standard
1596method overloading facilities are used. Here is a rather odd looking example:
1597</p>
1598
1599<div class="code">
1600<pre>
1601% Complex c 3 4
1602% Complex d 7 8
1603% set e [c - d] # operator-(const Complex &amp;)
1604% puts "[$e re] [$e im]"
160510.0 12.0
1606% set f [c -] # operator-()
1607% puts "[$f re] [$f im]"
1608-3.0 -4.0
1609%
1610</pre>
1611</div>
1612
1613<p>
1614One restriction with operator overloading support is that SWIG is not
1615able to fully handle operators that aren't defined as part of the class.
1616For example, if you had code like this
1617</p>
1618
1619<div class="code">
1620<pre>
1621class Complex {
1622...
1623friend Complex operator+(double, const Complex &amp;c);
1624...
1625};
1626</pre>
1627</div>
1628
1629<p>
1630then SWIG doesn't know what to do with the friend function--in fact,
1631it simply ignores it and issues a warning. You can still wrap the operator,
1632but you may have to encapsulate it in a special function. For example:
1633</p>
1634
1635<div class="code">
1636<pre>
1637%rename(Complex_add_dc) operator+(double, const Complex &amp;);
1638...
1639Complex operator+(double, const Complex &amp;c);
1640</pre>
1641</div>
1642
1643<p>
1644There are ways to make this operator appear as part of the class using the <tt>%extend</tt> directive.
1645Keep reading.
1646</p>
1647
1648<H3><a name="Tcl_nn26"></a>28.3.12 C++ namespaces</H3>
1649
1650
1651<p>
1652SWIG is aware of C++ namespaces, but namespace names do not appear in
1653the module nor do namespaces result in a module that is broken up into
1654submodules or packages. For example, if you have a file like this,
1655</p>
1656
1657<div class="code">
1658<pre>
1659%module example
1660
1661namespace foo {
1662 int fact(int n);
1663 struct Vector {
1664 double x,y,z;
1665 };
1666};
1667</pre>
1668</div>
1669
1670<p>
1671it works in Tcl as follows:
1672</p>
1673
1674<div class="code">
1675<pre>
1676% load ./example.so
1677% fact 3
16786
1679% Vector v
1680% v configure -x 3.4
1681</pre>
1682</div>
1683
1684<p>
1685If your program has more than one namespace, name conflicts (if any) can be resolved using <tt>%rename</tt>
1686For example:
1687</p>
1688
1689<div class="code">
1690<pre>
1691%rename(Bar_spam) Bar::spam;
1692
1693namespace Foo {
1694 int spam();
1695}
1696
1697namespace Bar {
1698 int spam();
1699}
1700</pre>
1701</div>
1702
1703<p>
1704If you have more than one namespace and your want to keep their
1705symbols separate, consider wrapping them as separate SWIG modules.
1706For example, make the module name the same as the namespace and create
1707extension modules for each namespace separately. If your program
1708utilizes thousands of small deeply nested namespaces each with
1709identical symbol names, well, then you get what you deserve.
1710</p>
1711
1712<H3><a name="Tcl_nn27"></a>28.3.13 C++ templates</H3>
1713
1714
1715<p>
1716C++ templates don't present a huge problem for SWIG. However, in order
1717to create wrappers, you have to tell SWIG to create wrappers for a particular
1718template instantiation. To do this, you use the <tt>%template</tt> directive.
1719For example:
1720</p>
1721
1722<div class="code">
1723<pre>
1724%module example
1725%{
1726#include "pair.h"
1727%}
1728
1729template&lt;class T1, class T2&gt;
1730struct pair {
1731 typedef T1 first_type;
1732 typedef T2 second_type;
1733 T1 first;
1734 T2 second;
1735 pair();
1736 pair(const T1&amp;, const T2&amp;);
1737 ~pair();
1738};
1739
1740%template(pairii) pair&lt;int,int&gt;;
1741</pre>
1742</div>
1743
1744<p>
1745In Tcl:
1746</p>
1747
1748<div class="code">
1749<pre>
1750% pairii p 3 4
1751% p cget -first
17523
1753% p cget -second
17544
1755</pre>
1756</div>
1757
1758<p>
1759Obviously, there is more to template wrapping than shown in this example.
1760More details can be found in the <a href="SWIGPlus.html#SWIGPlus">SWIG and C++</a> chapter. Some more complicated
1761examples will appear later.
1762</p>
1763
1764<H3><a name="Tcl_nn28"></a>28.3.14 C++ Smart Pointers</H3>
1765
1766
1767<p>
1768In certain C++ programs, it is common to use classes that have been wrapped by
1769so-called "smart pointers." Generally, this involves the use of a template class
1770that implements <tt>operator-&gt;()</tt> like this:
1771</p>
1772
1773<div class="code">
1774<pre>
1775template&lt;class T&gt; class SmartPtr {
1776 ...
1777 T *operator-&gt;();
1778 ...
1779}
1780</pre>
1781</div>
1782
1783<p>
1784Then, if you have a class like this,
1785</p>
1786
1787<div class="code">
1788<pre>
1789class Foo {
1790public:
1791 int x;
1792 int bar();
1793};
1794</pre>
1795</div>
1796
1797<p>
1798A smart pointer would be used in C++ as follows:
1799</p>
1800
1801<div class="code">
1802<pre>
1803SmartPtr&lt;Foo&gt; p = CreateFoo(); // Created somehow (not shown)
1804...
1805p-&gt;x = 3; // Foo::x
1806int y = p-&gt;bar(); // Foo::bar
1807</pre>
1808</div>
1809
1810<p>
1811To wrap this in Tcl, simply tell SWIG about the <tt>SmartPtr</tt> class and the low-level
1812<tt>Foo</tt> object. Make sure you instantiate <tt>SmartPtr</tt> using <tt>%template</tt> if necessary.
1813For example:
1814</p>
1815
1816<div class="code">
1817<pre>
1818%module example
1819...
1820%template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
1821...
1822</pre>
1823</div>
1824
1825<p>
1826Now, in Tcl, everything should just "work":
1827</p>
1828
1829<div class="code">
1830<pre>
1831% set p [CreateFoo] # Create a smart-pointer somehow
1832% $p configure -x 3 # Foo::x
1833% $p bar # Foo::bar
1834</pre>
1835</div>
1836
1837<p>
1838If you ever need to access the underlying pointer returned by <tt>operator-&gt;()</tt> itself,
1839simply use the <tt>__deref__()</tt> method. For example:
1840</p>
1841
1842<div class="code">
1843<pre>
1844% set f [$p __deref__] # Returns underlying Foo *
1845</pre>
1846</div>
1847
1848<H2><a name="Tcl_nn29"></a>28.4 Further details on the Tcl class interface</H2>
1849
1850
1851<p>
1852In the previous section, a high-level view of Tcl wrapping was
1853presented. A key component of this wrapping is that structures and
1854classes are wrapped by Tcl class-like objects. This provides a very
1855natural Tcl interface and allows SWIG to support a number of
1856advanced features such as operator overloading. However, a number
1857of low-level details were omitted. This section provides a brief overview
1858of how the proxy classes work.
1859</p>
1860
1861<H3><a name="Tcl_nn30"></a>28.4.1 Proxy classes</H3>
1862
1863
1864<p>
1865In the <a href="SWIG.html#SWIG">"SWIG basics"</a> and <a href="SWIGPlus.html#SWIGPlus">"SWIG and C++"</a> chapters,
1866details of low-level structure and class wrapping are described. To summarize those chapters, if you
1867have a class like this
1868</p>
1869
1870<div class="code">
1871<pre>
1872class Foo {
1873public:
1874 int x;
1875 int spam(int);
1876 ...
1877</pre>
1878</div>
1879
1880<p>
1881then SWIG transforms it into a set of low-level procedural wrappers. For example:
1882</p>
1883
1884<div class="code">
1885<pre>
1886Foo *new_Foo() {
1887 return new Foo();
1888}
1889void delete_Foo(Foo *f) {
1890 delete f;
1891}
1892int Foo_x_get(Foo *f) {
1893 return f-&gt;x;
1894}
1895void Foo_x_set(Foo *f, int value) {
1896 f-&gt;x = value;
1897}
1898int Foo_spam(Foo *f, int arg1) {
1899 return f-&gt;spam(arg1);
1900}
1901</pre>
1902</div>
1903
1904<p>
1905These wrappers are actually found in the Tcl extension module. For example, you can certainly do this:
1906</p>
1907
1908<div class="code">
1909<pre>
1910% load ./example.so
1911% set f [new_Foo]
1912% Foo_x_get $f
19130
1914% Foo_spam $f 3
19151
1916%
1917</pre>
1918</div>
1919
1920<p>
1921However, in addition to this, the classname <tt>Foo</tt> is used as an object constructor
1922function. This allows objects to be encapsulated objects that look a lot like Tk widgets
1923as shown in the last section.
1924</p>
1925
1926<H3><a name="Tcl_nn31"></a>28.4.2 Memory management</H3>
1927
1928
1929<p>
1930Associated with each wrapped object, is an ownership flag <tt>thisown</tt> The value of this
1931flag determines who is responsible for deleting the underlying C++ object. If set to 1,
1932the Tcl interpreter destroys the C++ object when the proxy class is
1933garbage collected. If set to 0 (or if the attribute is missing), then the destruction
1934of the proxy class has no effect on the C++ object.
1935</p>
1936
1937<p>
1938When an object is created by a constructor or returned by value, Tcl automatically takes
1939ownership of the result. For example:
1940</p>
1941
1942<div class="code">
1943<pre>
1944class Foo {
1945public:
1946 Foo();
1947 Foo bar();
1948};
1949</pre>
1950</div>
1951
1952<p>
1953In Tcl:
1954</p>
1955
1956<div class="code">
1957<pre>
1958% Foo f
1959% f cget -thisown
19601
1961% set g [f bar]
1962% $g cget -thisown
19631
1964</pre>
1965</div>
1966
1967<p>
1968On the other hand, when pointers are returned to Tcl, there is often no way to know where
1969they came from. Therefore, the ownership is set to zero. For example:
1970</p>
1971
1972<div class="code">
1973<pre>
1974class Foo {
1975public:
1976 ...
1977 Foo *spam();
1978 ...
1979};
1980</pre>
1981</div>
1982
1983<br>
1984
1985<div class="code">
1986<pre>
1987% Foo f
1988% set s [f spam]
1989% $s cget -thisown
19900
1991%
1992</pre>
1993</div>
1994
1995<p>
1996This behavior is especially important for classes that act as
1997containers. For example, if a method returns a pointer to an object
1998that is contained inside another object, you definitely don't want
1999Tcl to assume ownership and destroy it!
2000</p>
2001
2002<p>
2003Related to containers, ownership issues can arise whenever an object is assigned to a member
2004or global variable. For example, consider this interface:
2005</p>
2006
2007<div class="code">
2008<pre>
2009%module example
2010
2011struct Foo {
2012 int value;
2013 Foo *next;
2014};
2015
2016Foo *head = 0;
2017</pre>
2018</div>
2019
2020<p>
2021When wrapped in Tcl, careful observation will reveal that ownership changes whenever an object
2022is assigned to a global variable. For example:
2023</p>
2024
2025<div class="code">
2026<pre>
2027% Foo f
2028% f cget -thisown
20291
2030% set head f
2031% f cget -thisown
20320
2033</pre>
2034</div>
2035
2036<p>
2037In this case, C is now holding a reference to the object---you probably don't want Tcl to destroy it.
2038Similarly, this occurs for members. For example:
2039</p>
2040
2041<div class="code">
2042<pre>
2043% Foo f
2044% Foo g
2045% f cget -thisown
20461
2047% g cget -thisown
20481
2049% f configure -next g
2050% g cget -thisown
20510
2052%
2053</pre>
2054</div>
2055
2056<p>
2057For the most part, memory management issues remain hidden. However,
2058there are occasionally situations where you might have to manually
2059change the ownership of an object. For instance, consider code like this:
2060</p>
2061
2062<div class="code">
2063<pre>
2064class Node {
2065 Object *value;
2066public:
2067 void set_value(Object *v) { value = v; }
2068 ...
2069};
2070</pre>
2071</div>
2072
2073<p>
2074Now, consider the following Tcl code:
2075</p>
2076
2077<div class="code">
2078<pre>
2079% Object v # Create an object
2080% Node n # Create a node
2081% n setvalue v # Set value
2082% v cget -thisown
20831
2084%
2085</pre>
2086</div>
2087
2088<p>
2089In this case, the object <tt>n</tt> is holding a reference to
2090<tt>v</tt> internally. However, SWIG has no way to know that this
2091has occurred. Therefore, Tcl still thinks that it has ownership of the
2092object. Should the proxy object be destroyed, then the C++ destructor
2093will be invoked and <tt>n</tt> will be holding a stale-pointer. If
2094you're lucky, you will only get a segmentation fault.
2095</p>
2096
2097<p>
2098To work around this, it is always possible to flip the ownership flag. For example,
2099</p>
2100
2101<div class="code">
2102<pre>
2103% v -disown # Give ownership to C/C++
2104% v -acquire # Acquire ownership
2105</pre>
2106</div>
2107
2108<p>
2109It is also possible to deal with situations like this using
2110typemaps--an advanced topic discussed later.
2111</p>
2112
2113
2114<H2><a name="Tcl_nn32"></a>28.5 Input and output parameters</H2>
2115
2116
2117<p>
2118A common problem in some C programs is handling parameters passed as simple pointers. For
2119example:
2120</p>
2121
2122<div class="code">
2123<pre>
2124void add(int x, int y, int *result) {
2125 *result = x + y;
2126}
2127</pre>
2128</div>
2129
2130<p>
2131or perhaps
2132</p>
2133
2134<div class="code">
2135<pre>
2136int sub(int *x, int *y) {
2137 return *x+*y;
2138}
2139</pre>
2140</div>
2141
2142<p>
2143The easiest way to handle these situations is to use the <tt>typemaps.i</tt> file. For example:
2144</p>
2145
2146<div class="code">
2147<pre>
2148%module example
2149%include "typemaps.i"
2150
2151void add(int, int, int *OUTPUT);
2152int sub(int *INPUT, int *INPUT);
2153</pre>
2154</div>
2155
2156<p>
2157In Tcl, this allows you to pass simple values instead of pointer. For example:
2158</p>
2159
2160<div class="code">
2161<pre>
2162set a [add 3 4]
2163puts $a
21647
2165</pre>
2166</div>
2167
2168<p>
2169Notice how the <tt>INPUT</tt> parameters allow integer values to be passed instead of pointers
2170and how the <tt>OUTPUT</tt> parameter creates a return result.
2171</p>
2172
2173<p>
2174If you don't want to use the names <tt>INPUT</tt> or <tt>OUTPUT</tt>, use the <tt>%apply</tt>
2175directive. For example:
2176</p>
2177
2178<div class="code">
2179<pre>
2180%module example
2181%include "typemaps.i"
2182
2183%apply int *OUTPUT { int *result };
2184%apply int *INPUT { int *x, int *y};
2185
2186void add(int x, int y, int *result);
2187int sub(int *x, int *y);
2188</pre>
2189</div>
2190
2191<p>
2192If a function mutates one of its parameters like this,
2193</p>
2194
2195<div class="code">
2196<pre>
2197void negate(int *x) {
2198 *x = -(*x);
2199}
2200</pre>
2201</div>
2202
2203<p>
2204you can use <tt>INOUT</tt> like this:
2205</p>
2206
2207<div class="code">
2208<pre>
2209%include "typemaps.i"
2210...
2211void negate(int *INOUT);
2212</pre>
2213</div>
2214
2215<p>
2216In Tcl, a mutated parameter shows up as a return value. For example:
2217</p>
2218
2219<div class="code">
2220<pre>
2221set a [negate 3]
2222puts $a
2223-3
2224</pre>
2225</div>
2226
2227<p>
2228The most common use of these special typemap rules is to handle functions that
2229return more than one value. For example, sometimes a function returns a result
2230as well as a special error code:
2231</p>
2232
2233<div class="code">
2234<pre>
2235/* send message, return number of bytes sent, along with success code */
2236int send_message(char *text, int len, int *success);
2237</pre>
2238</div>
2239
2240<p>
2241To wrap such a function, simply use the <tt>OUTPUT</tt> rule above. For example:
2242</p>
2243
2244<div class="code">
2245<pre>
2246%module example
2247%include "typemaps.i"
2248%apply int *OUTPUT { int *success };
2249...
2250int send_message(char *text, int *success);
2251</pre>
2252</div>
2253
2254<p>
2255When used in Tcl, the function will return multiple values as a list.
2256</p>
2257
2258<div class="code">
2259<pre>
2260set r [send_message "Hello World"]
2261set bytes [lindex $r 0]
2262set success [lindex $r 1]
2263</pre>
2264</div>
2265
2266<p>
2267Another common use of multiple return values are in query functions. For example:
2268</p>
2269
2270<div class="code">
2271<pre>
2272void get_dimensions(Matrix *m, int *rows, int *columns);
2273</pre>
2274</div>
2275
2276<p>
2277To wrap this, you might use the following:
2278</p>
2279
2280<div class="code">
2281<pre>
2282%module example
2283%include "typemaps.i"
2284%apply int *OUTPUT { int *rows, int *columns };
2285...
2286void get_dimensions(Matrix *m, int *rows, *columns);
2287</pre>
2288</div>
2289
2290<p>
2291Now, in Perl:
2292</p>
2293
2294<div class="code">
2295<pre>
2296set dim [get_dimensions $m]
2297set r [lindex $dim 0]
2298set c [lindex $dim 1]
2299</pre>
2300</div>
2301
2302<H2><a name="Tcl_nn33"></a>28.6 Exception handling </H2>
2303
2304
2305<p>
2306The <tt>%exception</tt> directive can be used to create a user-definable
2307exception handler in charge of converting exceptions in your C/C++
2308program into Tcl exceptions. The chapter on customization features
2309contains more details, but suppose you extended the array example into
2310a C++ class like the following :
2311</p>
2312
2313<div class="code"><pre>
2314class RangeError {}; // Used for an exception
2315
2316class DoubleArray {
2317 private:
2318 int n;
2319 double *ptr;
2320 public:
2321 // Create a new array of fixed size
2322 DoubleArray(int size) {
2323 ptr = new double[size];
2324 n = size;
2325 }
2326 // Destroy an array
2327 ~DoubleArray() {
2328 delete ptr;
2329 }
2330 // Return the length of the array
2331 int length() {
2332 return n;
2333 }
2334
2335 // Get an item from the array and perform bounds checking.
2336 double getitem(int i) {
2337 if ((i &gt;= 0) &amp;&amp; (i &lt; n))
2338 return ptr[i];
2339 else
2340 throw RangeError();
2341 }
2342
2343 // Set an item in the array and perform bounds checking.
2344 void setitem(int i, double val) {
2345 if ((i &gt;= 0) &amp;&amp; (i &lt; n))
2346 ptr[i] = val;
2347 else {
2348 throw RangeError();
2349 }
2350 }
2351 };
2352</pre></div>
2353
2354<p>
2355The functions associated with this class can throw a C++ range
2356exception for an out-of-bounds array access. We can catch this in our
2357Tcl extension by specifying the following in an interface file :
2358</p>
2359
2360<div class="code"><pre>
2361%exception {
2362 try {
2363 $action // Gets substituted by actual function call
2364 }
2365 catch (RangeError) {
2366 Tcl_SetStringObj(tcl_result,"Array index out-of-bounds");
2367 return TCL_ERROR;
2368 }
2369}
2370</pre></div>
2371
2372<p>
2373As shown, the exception handling code will be added to every wrapper function.
2374Since this is somewhat inefficient. You might consider refining the
2375exception handler to only apply to specific methods like this:
2376</p>
2377
2378<div class="code">
2379<pre>
2380%exception getitem {
2381 try {
2382 $action
2383 }
2384 catch (RangeError) {
2385 Tcl_SetStringObj(tcl_result,"Array index out-of-bounds");
2386 return TCL_ERROR;
2387 }
2388}
2389
2390%exception setitem {
2391 try {
2392 $action
2393 }
2394 catch (RangeError) {
2395 Tcl_SetStringObj(tcl_result,"Array index out-of-bounds");
2396 return TCL_ERROR;
2397 }
2398}
2399</pre>
2400</div>
2401
2402<p>
2403In this case, the exception handler is only attached to methods and functions
2404named <tt>getitem</tt> and <tt>setitem</tt>.
2405</p>
2406
2407<p>
2408If you had a lot of different methods, you can avoid extra typing by using a macro.
2409For example:
2410</p>
2411
2412<div class="code">
2413<pre>
2414%define RANGE_ERROR
2415{
2416 try {
2417 $action
2418 }
2419 catch (RangeError) {
2420 Tcl_SetStringObj(tcl_result,"Array index out-of-bounds");
2421 return TCL_ERROR;
2422 }
2423}
2424%enddef
2425
2426%exception getitem RANGE_ERROR;
2427%exception setitem RANGE_ERROR;
2428</pre>
2429</div>
2430
2431<p>
2432Since SWIG's exception handling is user-definable, you are not limited to C++ exception handling.
2433See the chapter on "<a href="Customization.html#Customization">Customization Features</a>" for more examples.
2434</p>
2435
2436<H2><a name="Tcl_nn34"></a>28.7 Typemaps</H2>
2437
2438
2439<p>
2440This section describes how you can modify SWIG's default wrapping behavior
2441for various C/C++ datatypes using the <tt>%typemap</tt> directive. This
2442is an advanced topic that assumes familiarity with the Tcl C API as well
2443as the material in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
2444</p>
2445
2446<p>
2447Before proceeding, it should be stressed that typemaps are not a required
2448part of using SWIG---the default wrapping behavior is enough in most cases.
2449Typemaps are only used if you want to change some aspect of the primitive
2450C-Tcl interface.
2451</p>
2452
2453<H3><a name="Tcl_nn35"></a>28.7.1 What is a typemap?</H3>
2454
2455
2456<p>
2457A typemap is nothing more than a code generation rule that is attached to
2458a specific C datatype. For example, to convert integers from Tcl to C,
2459you might define a typemap like this:
2460</p>
2461
2462<div class="code"><pre>
2463%module example
2464
2465%typemap(in) int {
2466 if (Tcl_GetIntFromObj(interp,$input,&amp;$1) == TCL_ERROR) return TCL_ERROR;
2467 printf("Received an integer : %d\n",$1);
2468}
2469%inline %{
2470extern int fact(int n);
2471%}
2472</pre></div>
2473
2474<p>
2475Typemaps are always associated with some specific aspect of code generation.
2476In this case, the "in" method refers to the conversion of input arguments
2477to C/C++. The datatype <tt>int</tt> is the datatype to which the typemap
2478will be applied. The supplied C code is used to convert values. In this
2479code a number of special variable prefaced by a <tt>$</tt> are used. The
2480<tt>$1</tt> variable is placeholder for a local variable of type <tt>int</tt>.
2481The <tt>$input</tt> variable is the input object of type <tt>Tcl_Obj *</tt>.
2482</p>
2483
2484<p>
2485When this example is compiled into a Tcl module, it operates as follows:
2486</p>
2487
2488<div class="code"><pre>
2489% load ./example.so
2490% fact 6
2491Received an integer : 6
2492720
2493</pre></div>
2494
2495<p>
2496In this example, the typemap is applied to all occurrences of the <tt>int</tt> datatype.
2497You can refine this by supplying an optional parameter name. For example:
2498</p>
2499
2500<div class="code"><pre>
2501%module example
2502
2503%typemap(in) int n {
2504 if (Tcl_GetIntFromObj(interp,$input,&amp;$1) == TCL_ERROR) return TCL_ERROR;
2505 printf("n = %d\n",$1);
2506}
2507%inline %{
2508extern int fact(int n);
2509%}
2510</pre></div>
2511
2512<p>
2513In this case, the typemap code is only attached to arguments that exactly match <tt>int n</tt>.
2514</p>
2515
2516<p>
2517The application of a typemap to specific datatypes and argument names involves
2518more than simple text-matching--typemaps are fully integrated into the
2519SWIG type-system. When you define a typemap for <tt>int</tt>, that typemap
2520applies to <tt>int</tt> and qualified variations such as <tt>const int</tt>. In addition,
2521the typemap system follows <tt>typedef</tt> declarations. For example:
2522</p>
2523
2524<div class="code">
2525<pre>
2526%typemap(in) int n {
2527 if (Tcl_GetIntFromObj(interp,$input,&amp;$1) == TCL_ERROR) return TCL_ERROR;
2528 printf("n = %d\n",$1);
2529}
2530%inline %{
2531typedef int Integer;
2532extern int fact(Integer n); // Above typemap is applied
2533%}
2534</pre>
2535</div>
2536
2537<p>
2538However, the matching of <tt>typedef</tt> only occurs in one direction. If you
2539defined a typemap for <tt>Integer</tt>, it is not applied to arguments of
2540type <tt>int</tt>.
2541</p>
2542
2543<p>
2544Typemaps can also be defined for groups of consecutive arguments. For example:
2545</p>
2546
2547<div class="code">
2548<pre>
2549%typemap(in) (char *str, int len) {
2550 $1 = Tcl_GetStringFromObj($input,&amp;$2);
2551};
2552
2553int count(char c, char *str, int len);
2554</pre>
2555</div>
2556
2557<p>
2558When a multi-argument typemap is defined, the arguments are always handled as a single
2559Tcl object. This allows the function to be used like this (notice how the length
2560parameter is ommitted):
2561</p>
2562
2563<div class="code">
2564<pre>
2565% count e "Hello World"
25661
2567</pre>
2568</div>
2569
2570<H3><a name="Tcl_nn36"></a>28.7.2 Tcl typemaps</H3>
2571
2572
2573<p>
2574The previous section illustrated an "in" typemap for converting Tcl objects to C.
2575A variety of different typemap methods are defined by the Tcl module. For example,
2576to convert a C integer back into a Tcl object, you might define an "out" typemap
2577like this:
2578</p>
2579
2580<div class="code">
2581<pre>
2582%typemap(out) int {
2583 Tcl_SetObjResult(interp,Tcl_NewIntObj($1));
2584}
2585</pre>
2586</div>
2587
2588<p>
2589The following list details all of the typemap methods that can be used by the Tcl module:
2590</p>
2591
2592<p>
2593<tt>%typemap(in)</tt>
2594</p>
2595
2596<div class="indent">
2597Converts Tcl objects to input function arguments
2598</div>
2599
2600<p>
2601<tt>%typemap(out)</tt>
2602</p>
2603
2604<div class="indent">
2605Converts return value of a C function to a Tcl object
2606</div>
2607
2608<p>
2609<tt>%typemap(varin)</tt>
2610</p>
2611
2612<div class="indent">
2613Assigns a C global variable from a Tcl object
2614</div>
2615
2616<p>
2617<tt>%typemap(varout)</tt>
2618</p>
2619
2620<div class="indent">
2621Returns a C global variable as a Tcl object
2622</div>
2623
2624<p>
2625<tt>%typemap(freearg)</tt>
2626</p>
2627
2628<div class="indent">
2629Cleans up a function argument (if necessary)
2630</div>
2631
2632<p>
2633<tt>%typemap(argout)</tt>
2634</p>
2635
2636<div class="indent">
2637Output argument processing
2638</div>
2639
2640<p>
2641<tt>%typemap(ret)</tt>
2642</p>
2643
2644<div class="indent">
2645Cleanup of function return values
2646</div>
2647
2648<p>
2649<tt>%typemap(consttab)</tt>
2650</p>
2651
2652<div class="indent">
2653Creation of Tcl constants (constant table)
2654</div>
2655
2656<p>
2657<tt>%typemap(constcode)</tt>
2658</p>
2659
2660<div class="indent">
2661Creation of Tcl constants (init function)
2662</div>
2663
2664<p>
2665<tt>%typemap(memberin)</tt>
2666</p>
2667
2668<div class="indent">
2669Setting of structure/class member data
2670</div>
2671
2672<p>
2673<tt>%typemap(globalin)</tt>
2674</p>
2675
2676<div class="indent">
2677Setting of C global variables
2678</div>
2679
2680<p>
2681<tt>%typemap(check)</tt>
2682</p>
2683
2684<div class="indent">
2685Checks function input values.
2686</div>
2687
2688<p>
2689<tt>%typemap(default)</tt>
2690</p>
2691
2692<div class="indent">
2693Set a default value for an argument (making it optional).
2694</div>
2695
2696<p>
2697<tt>%typemap(arginit)</tt>
2698</p>
2699
2700<div class="indent">
2701Initialize an argument to a value before any conversions occur.
2702</div>
2703
2704<p>
2705Examples of these methods will appear shortly.
2706</p>
2707
2708<H3><a name="Tcl_nn37"></a>28.7.3 Typemap variables</H3>
2709
2710
2711<p>
2712Within typemap code, a number of special variables prefaced with a <tt>$</tt> may appear.
2713A full list of variables can be found in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
2714This is a list of the most common variables:
2715</p>
2716
2717<p>
2718<tt>$1</tt>
2719</p>
2720
2721<div class="indent">
2722A C local variable corresponding to the actual type specified in the
2723<tt>%typemap</tt> directive. For input values, this is a C local variable
2724that's supposed to hold an argument value. For output values, this is
2725the raw result that's supposed to be returned to Tcl.
2726</div>
2727
2728<p>
2729<tt>$input</tt>
2730</p>
2731
2732<div class="indent">
2733 A <tt>Tcl_Obj *</tt> holding a raw Tcl object with an argument or variable value.
2734</div>
2735
2736<p>
2737<tt>$result</tt>
2738</p>
2739
2740<div class="indent">
2741A <tt>Tcl_Obj *</tt> that holds the result to be returned to Tcl.
2742</div>
2743
2744<p>
2745<tt>$1_name</tt>
2746</p>
2747
2748<div class="indent">
2749The parameter name that was matched.
2750</div>
2751
2752<p>
2753<tt>$1_type</tt>
2754</p>
2755
2756<div class="indent">
2757The actual C datatype matched by the typemap.
2758</div>
2759
2760<p>
2761<tt>$1_ltype</tt>
2762</p>
2763
2764<div class="indent">
2765An assignable version of the datatype matched by the typemap (a type that can appear on the left-hand-side of
2766a C assignment operation). This type is stripped of qualifiers and may be an altered version of <tt>$1_type</tt>.
2767All arguments and local variables in wrapper functions are declared using this type so that their values can be
2768properly assigned.
2769</div>
2770
2771<p>
2772<tt>$symname</tt>
2773</p>
2774
2775<div class="indent">
2776The Tcl name of the wrapper function being created.
2777</div>
2778
2779<H3><a name="Tcl_nn38"></a>28.7.4 Converting a Tcl list to a char ** </H3>
2780
2781
2782<p>
2783A common problem in many C programs is the processing of command line
2784arguments, which are usually passed in an array of NULL terminated
2785strings. The following SWIG interface file allows a Tcl list to be
2786used as a <tt>char **</tt> object.
2787</p>
2788
2789<div class="code"><pre>
2790%module argv
2791
2792// This tells SWIG to treat char ** as a special case
2793%typemap(in) char ** {
2794 Tcl_Obj **listobjv;
2795 int nitems;
2796 int i;
2797 if (Tcl_ListObjGetElements(interp, $input, &amp;nitems, &amp;listobjv) == TCL_ERROR) {
2798 return TCL_ERROR;
2799 }
2800 $1 = (char **) malloc((nitems+1)*sizeof(char *));
2801 for (i = 0; i &lt; nitems; i++) {
2802 $1[i] = Tcl_GetStringFromObj(listobjv[i],0);
2803 }
2804 $1[i] = 0;
2805}
2806
2807// This gives SWIG some cleanup code that will get called after the function call
2808%typemap(freearg) char ** {
2809 if ($1) {
2810 free($1);
2811 }
2812}
2813
2814// Now a test functions
2815%inline %{
2816int print_args(char **argv) {
2817 int i = 0;
2818 while (argv[i]) {
2819 printf("argv[%d] = %s\n", i,argv[i]);
2820 i++;
2821 }
2822 return i;
2823}
2824%}
2825%include tclsh.i
2826
2827</pre></div>
2828
2829<p>
2830In Tcl:
2831</p>
2832
2833<div class="code"><pre>
2834% print_args {John Guido Larry}
2835argv[0] = John
2836argv[1] = Guido
2837argv[2] = Larry
28383
2839</pre></div>
2840
2841<H3><a name="Tcl_nn39"></a>28.7.5 Returning values in arguments</H3>
2842
2843
2844<p>
2845The "argout" typemap can be used to return a value originating from a
2846function argument. For example :
2847</p>
2848
2849<div class="code"><pre>
2850// A typemap defining how to return an argument by appending it to the result
2851%typemap(argout) double *outvalue {
2852 Tcl_Obj *o = Tcl_NewDoubleObj($1);
2853 Tcl_ListObjAppendElement(interp,$result,o);
2854}
2855
2856// A typemap telling SWIG to ignore an argument for input
2857// However, we still need to pass a pointer to the C function
2858%typemap(in,numinputs=0) double *outvalue (double temp) {
2859 $1 = &amp;temp;
2860}
2861
2862// Now a function returning two values
2863int mypow(double a, double b, double *outvalue) {
2864 if ((a &lt; 0) || (b &lt; 0)) return -1;
2865 *outvalue = pow(a,b);
2866 return 0;
2867};
2868</pre></div>
2869
2870<p>
2871When wrapped, SWIG matches the <tt>argout</tt> typemap to the
2872"<tt>double *outvalue</tt>" argument. The numinputs=0 specification tells SWIG
2873to simply ignore this argument when generating wrapper code. As a
2874result, a Tcl function using these typemaps will work like this :
2875</p>
2876
2877<div class="code"><pre>
2878% mypow 2 3 # Returns two values, a status value and the result
28790 8
2880%
2881</pre></div>
2882
2883<H3><a name="Tcl_nn40"></a>28.7.6 Useful functions</H3>
2884
2885
2886<p>
2887The following tables provide some functions that may be useful in
2888writing Tcl typemaps.
2889</p>
2890
2891<p>
2892<b>Integers</b>
2893</p>
2894
2895<div class="code">
2896<pre>
2897Tcl_Obj *Tcl_NewIntObj(int Value);
2898void Tcl_SetIntObj(Tcl_Obj *obj, int Value);
2899int Tcl_GetIntFromObj(Tcl_Interp *, Tcl_Obj *obj, int *ip);
2900</pre>
2901</div>
2902
2903<p>
2904<b>Floating Point</b>
2905</p>
2906
2907<div class="code">
2908<pre>
2909Tcl_Obj *Tcl_NewDoubleObj(double Value);
2910void Tcl_SetDoubleObj(Tcl_Obj *obj, double value);
2911int Tcl_GetDoubleFromObj(Tcl_Interp *, Tcl_Obj *o, double *dp);
2912</pre>
2913</div>
2914
2915<p>
2916<b>Strings</b>
2917</p>
2918
2919<div class="code">
2920<pre>
2921Tcl_Obj *Tcl_NewStringObj(char *str, int len);
2922void Tcl_SetStringObj(Tcl_Obj *obj, char *str, int len);
2923char *Tcl_GetStringFromObj(Tcl_Obj *obj, int *len);
2924void Tcl_AppendToObj(Tcl_Obj *obj, char *str, int len);
2925</pre>
2926</div>
2927
2928<p>
2929<b>Lists</b>
2930</p>
2931
2932<div class="code">
2933<pre>
2934Tcl_Obj *Tcl_NewListObj(int objc, Tcl_Obj *objv);
2935int Tcl_ListObjAppendList(Tcl_Interp *, Tcl_Obj *listPtr, Tcl_Obj *elemListPtr);
2936int Tcl_ListObjAppendElement(Tcl_Interp *, Tcl_Obj *listPtr, Tcl_Obj *element);
2937int Tcl_ListObjGetElements(Tcl_Interp *, Tcl_Obj *listPtr, int *objcPtr,
2938 Tcl_Obj ***objvPtr);
2939int Tcl_ListObjLength(Tcl_Interp *, Tcl_Obj *listPtr, int *intPtr);
2940int Tcl_ListObjIndex(Tcl_Interp *, Tcl_Obj *listPtr, int index,
2941 Tcl_Obj_Obj **objptr);
2942int Tcl_ListObjReplace(Tcl_Interp *, Tcl_Obj *listPtr, int first, int count,
2943 int objc, Tcl_Obj *objv);
2944</pre>
2945</div>
2946
2947<p>
2948<b>Objects</b>
2949</p>
2950
2951<div class="code">
2952<pre>
2953Tcl_Obj *Tcl_DuplicateObj(Tcl_Obj *obj);
2954void Tcl_IncrRefCount(Tcl_Obj *obj);
2955void Tcl_DecrRefCount(Tcl_Obj *obj);
2956int Tcl_IsShared(Tcl_Obj *obj);
2957</pre>
2958</div>
2959
2960<H3><a name="Tcl_nn41"></a>28.7.7 Standard typemaps</H3>
2961
2962
2963<p>
2964The following typemaps show how to convert a few common kinds of
2965objects between Tcl and C (and to give a better idea of how typemaps
2966work)
2967</p>
2968
2969
2970<p>
2971<b>Integer conversion</b>
2972</p>
2973
2974<div class="code">
2975<pre>
2976%typemap(in) int, short, long {
2977 int temp;
2978 if (Tcl_GetIntFromObj(interp, $input, &amp;temp) == TCL_ERROR)
2979 return TCL_ERROR;
2980 $1 = ($1_ltype) temp;
2981}
2982</pre>
2983</div>
2984
2985<br>
2986
2987<div class="code">
2988<pre>
2989%typemap(out) int, short, long {
2990 Tcl_SetIntObj($result,(int) $1);
2991}
2992</pre>
2993</div>
2994
2995<p>
2996<b>Floating point conversion</b>
2997</p>
2998
2999<div class="code">
3000<pre>
3001%typemap(in) float, double {
3002 double temp;
3003 if (Tcl_GetDoubleFromObj(interp, $input, &amp;temp) == TCL_ERROR)
3004 return TCL_ERROR;
3005 $1 = ($1_ltype) temp;
3006}
3007</pre>
3008</div>
3009
3010<br>
3011
3012<div class="code">
3013<pre>
3014%typemap(out) float, double {
3015 Tcl_SetDoubleObj($result, $1);
3016}
3017</pre>
3018</div>
3019
3020<p>
3021<b>String Conversion</b>
3022</p>
3023
3024<div class="code">
3025<pre>
3026%typemap(in) char * {
3027 int len;
3028 $1 = Tcl_GetStringFromObj(interp, &amp;len);
3029 }
3030}
3031</pre>
3032</div>
3033
3034<br>
3035
3036<div class="code">
3037<pre>
3038%typemap(out) char * {
3039 Tcl_SetStringObj($result,$1);
3040}
3041</pre>
3042</div>
3043
3044<H3><a name="Tcl_nn42"></a>28.7.8 Pointer handling</H3>
3045
3046
3047<p>
3048SWIG pointers are mapped into Tcl strings containing the
3049hexadecimal value and type. The following functions can be used to
3050create and read pointer values.
3051</p>
3052
3053<p>
3054<tt>
3055int SWIG_ConvertPtr(Tcl_Obj *obj, void **ptr, swig_type_info *ty, int flags)</tt>
3056</p>
3057
3058<div class="indent">
3059Converts a Tcl object <tt>obj</tt> to a C pointer. The result of the conversion is placed
3060into the pointer located at <tt>ptr</tt>. <tt>ty</tt> is a SWIG type descriptor structure.
3061<tt>flags</tt> is used to handle error checking and other aspects of conversion. It is currently
3062reserved for future expansion. Returns 0 on success and -1 on error.
3063</div>
3064
3065<p>
3066<tt>
3067Tcl_Obj *SWIG_NewPointerObj(void *ptr, swig_type_info *ty, int flags)</tt>
3068</p>
3069
3070<div class="indent">
3071Creates a new Tcl pointer object. <tt>ptr</tt> is the pointer to convert, <tt>ty</tt> is the SWIG type descriptor structure that
3072describes the type, and <tt>own</tt> is a flag reserved for future expansion.
3073</div>
3074
3075<p>
3076Both of these functions require the use of a special SWIG
3077type-descriptor structure. This structure contains information about
3078the mangled name of the datatype, type-equivalence information, as
3079well as information about converting pointer values under C++
3080inheritance. For a type of <tt>Foo *</tt>, the type descriptor structure
3081is usually accessed as follows:
3082</p>
3083
3084<div class="indent">
3085<pre>
3086Foo *f;
3087if (SWIG_ConvertPtr($input, (void **) &amp;f, SWIGTYPE_p_Foo, 0) == -1) return NULL;
3088
3089Tcl_Obj *;
3090obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
3091</pre>
3092</div>
3093
3094<p>
3095In a typemap, the type descriptor should always be accessed using the special typemap
3096variable <tt>$1_descriptor</tt>. For example:
3097</p>
3098
3099<div class="indent">
3100<pre>
3101%typemap(in) Foo * {
3102 if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $1_descriptor,0)) == -1) return NULL;
3103}
3104</pre>
3105</div>
3106
3107<p>
3108If necessary, the descriptor for any type can be obtained using the <tt>$descriptor()</tt> macro in a typemap.
3109For example:
3110</p>
3111
3112<div class="indent">
3113<pre>
3114%typemap(in) Foo * {
3115 if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $descriptor(Foo *), 0)) == -1) return NULL;
3116}
3117</pre>
3118</div>
3119
3120<H2><a name="Tcl_nn43"></a>28.8 Turning a SWIG module into a Tcl Package.</H2>
3121
3122
3123<p>
3124Tcl 7.4 introduced the idea of an extension package. By default, SWIG
3125generates all of the code necessary to create a package. To set the package version,
3126simply use the <tt>-pkgversion</tt> option. For example:
3127</p>
3128
3129<div class="code">
3130<pre>
3131% swig -tcl -pkgversion 2.3 example.i
3132</pre>
3133</div>
3134
3135<p>
3136After building the SWIG generated module, you need to execute
3137the "<tt>pkg_mkIndex</tt>" command inside tclsh. For example :
3138</p>
3139
3140<div class="code"><pre>
3141unix &gt; tclsh
3142% pkg_mkIndex . example.so
3143% exit
3144</pre></div>
3145
3146<p>
3147This creates a file "<tt>pkgIndex.tcl</tt>" with information about the
3148package. To use your package, you now need to move it to its own
3149subdirectory which has the same name as the package. For example :
3150</p>
3151
3152<div class="code"><pre>
3153./example/
3154 pkgIndex.tcl # The file created by pkg_mkIndex
3155 example.so # The SWIG generated module
3156</pre></div>
3157
3158<p>
3159Finally, assuming that you're not entirely confused at this point,
3160make sure that the example subdirectory is visible from the
3161directories contained in either the <tt>tcl_library</tt> or
3162<tt>auto_path</tt> variables. At this point you're ready to use the
3163package as follows :
3164</p>
3165
3166<div class="code"><pre>
3167unix &gt; tclsh
3168% package require example
3169% fact 4
317024
3171%
3172</pre></div>
3173
3174<p>
3175If you're working with an example in the current directory and this doesn't work, do this instead :
3176</p>
3177
3178<div class="code"><pre>
3179unix &gt; tclsh
3180% lappend auto_path .
3181% package require example
3182% fact 4
318324
3184</pre></div>
3185
3186<p>
3187As a final note, most SWIG examples do not yet use the
3188<tt>package</tt> commands. For simple extensions it may be easier just
3189to use the <tt>load</tt> command instead.
3190</p>
3191
3192<H2><a name="Tcl_nn44"></a>28.9 Building new kinds of Tcl interfaces (in Tcl)</H2>
3193
3194
3195<p>
3196One of the most interesting aspects of Tcl and SWIG is that you can
3197create entirely new kinds of Tcl interfaces in Tcl using the low-level
3198SWIG accessor functions. For example, suppose you had a library of
3199helper functions to access arrays :
3200</p>
3201
3202<div class="code"><pre>
3203/* File : array.i */
3204%module array
3205
3206%inline %{
3207double *new_double(int size) {
3208 return (double *) malloc(size*sizeof(double));
3209}
3210void delete_double(double *a) {
3211 free(a);
3212}
3213double get_double(double *a, int index) {
3214 return a[index];
3215}
3216void set_double(double *a, int index, double val) {
3217 a[index] = val;
3218}
3219int *new_int(int size) {
3220 return (int *) malloc(size*sizeof(int));
3221}
3222void delete_int(int *a) {
3223 free(a);
3224}
3225int get_int(int *a, int index) {
3226 return a[index];
3227}
3228int set_int(int *a, int index, int val) {
3229 a[index] = val;
3230}
3231%}
3232
3233</pre></div>
3234
3235<p>
3236While these could be called directly, we could also write a Tcl script
3237like this :
3238</p>
3239
3240<div class="code"><pre>
3241proc Array {type size} {
3242 set ptr [new_$type $size]
3243 set code {
3244 set method [lindex $args 0]
3245 set parms [concat $ptr [lrange $args 1 end]]
3246 switch $method {
3247 get {return [eval "get_$type $parms"]}
3248 set {return [eval "set_$type $parms"]}
3249 delete {eval "delete_$type $ptr; rename $ptr {}"}
3250 }
3251 }
3252 # Create a procedure
3253 uplevel "proc $ptr args {set ptr $ptr; set type $type;$code}"
3254 return $ptr
3255}
3256</pre></div>
3257
3258<p>
3259Our script allows easy array access as follows :
3260</p>
3261
3262<div class="code"><pre>
3263set a [Array double 100] ;# Create a double [100]
3264for {set i 0} {$i &lt; 100} {incr i 1} { ;# Clear the array
3265 $a set $i 0.0
3266}
3267$a set 3 3.1455 ;# Set an individual element
3268set b [$a get 10] ;# Retrieve an element
3269
3270set ia [Array int 50] ;# Create an int[50]
3271for {set i 0} {$i &lt; 50} {incr i 1} { ;# Clear it
3272 $ia set $i 0
3273}
3274$ia set 3 7 ;# Set an individual element
3275set ib [$ia get 10] ;# Get an individual element
3276
3277$a delete ;# Destroy a
3278$ia delete ;# Destroy ia
3279</pre></div>
3280
3281<p>
3282The cool thing about this approach is that it makes a common interface
3283for two different types of arrays. In fact, if we were to add more C
3284datatypes to our wrapper file, the Tcl code would work with those as
3285well--without modification. If an unsupported datatype was requested,
3286the Tcl code would simply return with an error so there is very little
3287danger of blowing something up (although it is easily accomplished
3288with an out of bounds array access).
3289</p>
3290
3291<H3><a name="Tcl_nn45"></a>28.9.1 Proxy classes</H3>
3292
3293
3294<p>
3295A similar approach can be applied to proxy classes (also known as
3296shadow classes). The following
3297example is provided by Erik Bierwagen and Paul Saxe. To use it, run
3298SWIG with the <tt>-noobject</tt> option (which disables the builtin
3299object oriented interface). When running Tcl, simply source this
3300file. Now, objects can be used in a more or less natural fashion.
3301</p>
3302
3303<div class="code"><pre>
3304# swig_c++.tcl
3305# Provides a simple object oriented interface using
3306# SWIG's low level interface.
3307#
3308
3309proc new {objectType handle_r args} {
3310 # Creates a new SWIG object of the given type,
3311 # returning a handle in the variable "handle_r".
3312 #
3313 # Also creates a procedure for the object and a trace on
3314 # the handle variable that deletes the object when the
3315 # handle varibale is overwritten or unset
3316 upvar $handle_r handle
3317 #
3318 # Create the new object
3319 #
3320 eval set handle \[new_$objectType $args\]
3321 #
3322 # Set up the object procedure
3323 #
3324 proc $handle {cmd args} "eval ${objectType}_\$cmd $handle \$args"
3325 #
3326 # And the trace ...
3327 #
3328 uplevel trace variable $handle_r uw "{deleteObject $objectType $handle}"
3329 #
3330 # Return the handle so that 'new' can be used as an argument to a procedure
3331 #
3332 return $handle
3333}
3334
3335proc deleteObject {objectType handle name element op} {
3336 #
3337 # Check that the object handle has a reasonable form
3338 #
3339 if {![regexp {_[0-9a-f]*_(.+)_p} $handle]} {
3340 error "deleteObject: not a valid object handle: $handle"
3341 }
3342 #
3343 # Remove the object procedure
3344 #
3345 catch {rename $handle {}}
3346 #
3347 # Delete the object
3348 #
3349 delete_$objectType $handle
3350}
3351
3352proc delete {handle_r} {
3353 #
3354 # A synonym for unset that is more familiar to C++ programmers
3355 #
3356 uplevel unset $handle_r
3357}
3358</pre></div>
3359
3360<p>
3361To use this file, we simply source it and execute commands such as
3362"new" and "delete" to manipulate objects. For example :
3363</p>
3364
3365<div class="code"><pre>
3366// list.i
3367%module List
3368%{
3369#include "list.h"
3370%}
3371
3372// Very simple C++ example
3373
3374class List {
3375public:
3376 List(); // Create a new list
3377 ~List(); // Destroy a list
3378 int search(char *value);
3379 void insert(char *); // Insert a new item into the list
3380 void remove(char *); // Remove item from list
3381 char *get(int n); // Get the nth item in the list
3382 int length; // The current length of the list
3383static void print(List *l); // Print out the contents of the list
3384};
3385</pre></div>
3386
3387<p>
3388Now a Tcl script using the interface...
3389</p>
3390
3391<div class="code"><pre>
3392load ./list.so list ; # Load the module
3393source swig_c++.tcl ; # Source the object file
3394
3395new List l
3396$l insert Dave
3397$l insert John
3398$l insert Guido
3399$l remove Dave
3400puts $l length_get
3401
3402delete l
3403</pre></div>
3404
3405<p>
3406The cool thing about this example is that it works with any C++ object
3407wrapped by SWIG and requires no special compilation. Proof that a
3408short, but clever Tcl script can be combined with SWIG to do many
3409interesting things.
3410</p>
3411
3412</body>
3413</html>