PageRenderTime 51ms CodeModel.GetById 10ms app.highlight 27ms RepoModel.GetById 1ms app.codeStats 1ms

/trunk/Doc/Manual/Tcl.html

#
HTML | 2846 lines | 2334 code | 510 blank | 2 comment | 0 complexity | 02fb97030fb2a61385f4cfb887d8ad74 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   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>37 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>
  81This chapter discusses SWIG's support of Tcl. SWIG currently requires
  82Tcl 8.0 or a later release.   Earlier releases of SWIG supported Tcl 7.x, but
  83this is no longer supported.
  84</p>
  85
  86<H2><a name="Tcl_nn2"></a>37.1 Preliminaries</H2>
  87
  88
  89<p>
  90To 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>
  98If 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>
 106This creates a file <tt>example_wrap.c</tt> or
 107<tt>example_wrap.cxx</tt> that contains all of the code needed to
 108build a Tcl extension module.  To finish building the module, you 
 109need to compile this file and link it with the rest of your program.
 110</p>
 111
 112<H3><a name="Tcl_nn3"></a>37.1.1 Getting the right header files</H3>
 113
 114
 115<p>
 116In order to compile the wrapper code, the compiler needs the <tt>tcl.h</tt> header file.
 117This 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>
 125Be aware that some Tcl versions install this header file with a version number attached to it.  If
 126this is the case, you should probably make a symbolic link so that <tt>tcl.h</tt> points to the correct
 127header file.
 128</p>
 129
 130<H3><a name="Tcl_nn4"></a>37.1.2 Compiling a dynamic module</H3>
 131
 132
 133<p>
 134The preferred approach to building an extension module is to compile it into
 135a shared object file or DLL.   To do this, you will need to compile your program
 136using 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>
 147The exact commands for doing this vary from platform to platform. 
 148SWIG tries to guess the right options when it is installed.  Therefore, 
 149you may want to start with one of the examples in the <tt>SWIG/Examples/tcl</tt> 
 150directory.   If that doesn't work, you will need to read the man-pages for
 151your compiler and linker to get the right set of options.  You might also
 152check the <a href="http://www.dabeaz.com/cgi-bin/wiki.pl">SWIG Wiki</a> for
 153additional information.
 154</p>
 155
 156<p>
 157When linking the module, the name of the output file has to match the name
 158of the module.  If the name of your SWIG module is "<tt>example</tt>", the
 159name of the corresponding object file should be
 160"<tt>example.so</tt>".
 161The 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>37.1.3 Static linking</H3>
 166
 167
 168<p>
 169An alternative approach to dynamic linking is to rebuild the Tcl
 170interpreter with your extension module added to it.  In the past,
 171this approach was sometimes necessary due to limitations in dynamic loading
 172support on certain machines.  However, the situation has improved greatly
 173over the last few years and you should not consider this approach 
 174unless there is really no other option.
 175</p>
 176
 177<p>
 178The usual procedure for adding a new module to Tcl involves writing a
 179special function <tt>Tcl_AppInit()</tt> and using it to initialize the interpreter and
 180your module.  With SWIG, the <tt>tclsh.i</tt> and <tt>wish.i</tt> library files
 181can be used to rebuild the <tt>tclsh</tt> and <tt>wish</tt> interpreters respectively.
 182For example:
 183</p>
 184
 185<div class="code"><pre>
 186%module example
 187
 188%inline %{
 189extern int fact(int);
 190extern int mod(int, int);
 191extern double My_variable;
 192%}
 193
 194%include "tclsh.i"       // Include code for rebuilding tclsh
 195
 196</pre></div>
 197
 198<p>
 199The <tt>tclsh.i</tt> library file includes supporting code that
 200contains everything needed to rebuild tclsh. To rebuild the interpreter,
 201you 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>
 215You will need to supply the same libraries that were used to build Tcl the first
 216time.  This may include system libraries such as <tt>-lsocket</tt>, <tt>-lnsl</tt>,
 217and <tt>-lpthread</tt>.  If this actually works, the new version of Tcl
 218should be identical to the default version except that your extension module will be
 219a built-in part of the interpreter.
 220</p>
 221
 222<p>
 223<b>Comment:</b> In practice, you should probably try to avoid static
 224linking if possible. Some programmers may be inclined
 225to use static linking in the interest of getting better performance.
 226However, the performance gained by static linking tends to be rather
 227minimal in most situations (and quite frankly not worth the extra
 228hassle in the opinion of this author). 
 229</p>
 230
 231<H3><a name="Tcl_nn6"></a>37.1.4 Using your module</H3>
 232
 233
 234<p>
 235To use your module, simply use the Tcl <tt>load</tt> command.  If
 236all 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
 24324
 244%
 245</pre></div>
 246
 247<p>
 248A common error received by first-time users is the following:
 249</p>
 250
 251<div class="code">
 252<pre>
 253% load ./example.so
 254couldn't find procedure Example_Init
 255% 
 256</pre>
 257</div>
 258
 259<p>
 260This error is almost always caused when the name of the shared object file doesn't
 261match the name of the module supplied using the SWIG <tt>%module</tt> directive.
 262Double-check the interface to make sure the module name and the shared object
 263file match.  Another possible cause of this error is forgetting to link the SWIG-generated
 264wrapper code with the rest of your application when creating the extension module.
 265</p>
 266
 267<p>
 268Another common error is something similar to the following:
 269</p>
 270
 271<div class="code">
 272<pre>
 273% load ./example.so
 274couldn't load file "./example.so": ./example.so: undefined symbol: fact
 275% 
 276</pre>
 277</div>
 278
 279<p>
 280This error usually indicates that you forgot to include some object
 281files or libraries in the linking of the shared library file.  Make
 282sure you compile both the SWIG wrapper file and your original program
 283into a shared library file.  Make sure you pass all of the required libraries
 284to the linker.  
 285</p>
 286
 287<p>
 288Sometimes unresolved symbols occur because a wrapper has been created
 289for a function that doesn't actually exist in a library.  This usually
 290occurs when a header file includes a declaration for a function that
 291was never actually implemented or it was removed from a library
 292without updating the header file.  To fix this, you can either edit
 293the SWIG input file to remove the offending declaration or you can use
 294the <tt>%ignore</tt> directive to ignore the declaration.
 295</p>
 296
 297<p>
 298Finally, 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>
 309If the <tt>foo</tt> library is compiled as a shared library, you might get the following
 310problem when you try to use your module:
 311</p>
 312
 313<div class="code">
 314<pre>
 315% load ./example.so
 316couldn't load file "./example.so": libfoo.so: cannot open shared object file:
 317No such file or directory
 318%        
 319</pre>
 320</div>
 321
 322<p>
 323This error is generated because the dynamic linker can't locate the
 324<tt>libfoo.so</tt> library.  When shared libraries are loaded, the
 325system normally only checks a few standard locations such as
 326<tt>/usr/lib</tt> and <tt>/usr/local/lib</tt>.   To fix this problem,
 327there are several things you can do.  First, you can recompile your extension
 328module 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>
 340Alternatively, you can set the <tt>LD_LIBRARY_PATH</tt> environment variable to
 341include the directory with your shared libraries. 
 342If setting <tt>LD_LIBRARY_PATH</tt>, be aware that setting this variable can introduce
 343a noticeable performance impact on all other applications that you run.
 344To 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>
 354Finally, you can use a command such as <tt>ldconfig</tt> to add additional search paths
 355to the default system configuration (this requires root access and you will need to read
 356the man pages). 
 357</p>
 358
 359<H3><a name="Tcl_nn7"></a>37.1.5 Compilation of C++ extensions</H3>
 360
 361
 362<p>
 363Compilation of C++ extensions has traditionally been a tricky problem.
 364Since the Tcl interpreter is written in C, you need to take steps to
 365make sure C++ is properly initialized and that modules are compiled
 366correctly.
 367</p>
 368
 369<p>
 370On most machines, C++ extension modules should be linked using the C++
 371compiler.  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>
 382In addition to this, you may need to include additional library
 383files to make it work.  For example, if you are using the Sun C++ compiler on
 384Solaris, 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>
 395Of course, the extra libraries to use are completely non-portable---you will 
 396probably need to do some experimentation.
 397</p>
 398
 399<p>
 400Sometimes people have suggested that it is necessary to relink the
 401Tcl interpreter using the C++ compiler to make C++ extension modules work.
 402In the experience of this author, this has never actually appeared to be
 403necessary.   Relinking the interpreter with C++ really only includes the 
 404special run-time libraries described above---as long as you link your extension 
 405modules with these libraries, it should not be necessary to rebuild Tcl.
 406</p>
 407
 408<p>
 409If you aren't entirely sure about the linking of a C++ extension, you
 410might look at an existing C++ program.  On many Unix machines, the
 411<tt>ldd</tt> command will list library dependencies.  This should give
 412you some clues about what you might have to include when you link your
 413extension 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>
 428As a final complication, a major weakness of C++ is that it does not
 429define any sort of standard for binary linking of libraries.  This
 430means that C++ code compiled by different compilers will not link
 431together properly as libraries nor is the memory layout of classes and
 432data structures implemented in any kind of portable manner.  In a
 433monolithic C++ program, this problem may be unnoticed.  However, in Tcl, it
 434is possible for different extension modules to be compiled with
 435different C++ compilers.  As long as these modules are self-contained,
 436this probably won't matter.  However, if these modules start sharing data,
 437you will need to take steps to avoid segmentation faults and other
 438erratic program behavior.   If working with lots of software components, you
 439might want to investigate using a more formal standard such as COM.
 440</p>
 441
 442<H3><a name="Tcl_nn8"></a>37.1.6 Compiling for 64-bit platforms</H3>
 443
 444
 445<p>
 446On platforms that support 64-bit applications (Solaris, Irix, etc.),
 447special care is required when building extension modules.  On these
 448machines, 64-bit applications are compiled and linked using a different
 449set of compiler/linker options.  In addition, it is not generally possible to mix 
 45032-bit and 64-bit code together in the same application.
 451</p>
 452
 453<p>
 454To utilize 64-bits, the Tcl executable will need to be recompiled
 455as a 64-bit application.  In addition, all libraries, wrapper code,
 456and every other part of your application will need to be compiled for
 45764-bits.  If you plan to use other third-party extension modules, they
 458will also have to be recompiled as 64-bit extensions.
 459</p>
 460
 461<p>
 462If you are wrapping commercial software for which you have no source
 463code, you will be forced to use the same linking standard as used by
 464that software.  This may prevent the use of 64-bit extensions.  It may
 465also introduce problems on platforms that support more than one
 466linking standard (e.g., -o32 and -n32 on Irix).
 467</p>
 468
 469<H3><a name="Tcl_nn9"></a>37.1.7 Setting a package prefix</H3>
 470
 471
 472<p>
 473To avoid namespace problems, you can instruct SWIG to append a package
 474prefix 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>
 479swig -tcl -prefix Foo example.i
 480</pre></div>
 481
 482<p>
 483If you have a function "<tt>bar</tt>" in the SWIG file, the prefix
 484option will append the prefix to the name when creating a command and
 485call it "<tt>Foo_bar</tt>".
 486</p>
 487
 488<H3><a name="Tcl_nn10"></a>37.1.8 Using namespaces</H3>
 489
 490
 491<p>
 492Alternatively, you can have SWIG install your module into a Tcl
 493namespace by specifying the <tt>-namespace</tt> option :
 494</p>
 495
 496<div class="code"><pre>
 497swig -tcl -namespace example.i
 498</pre></div>
 499
 500<p>
 501By default, the name of the namespace will be the same as the module
 502name, but you can override it using the <tt>-prefix</tt> option.
 503</p>
 504
 505<p>
 506When the<tt> -namespace</tt> option is used, objects in the module
 507are always accessed with the namespace name such as <tt>Foo::bar</tt>.
 508</p>
 509
 510<H2><a name="Tcl_nn11"></a>37.2 Building Tcl/Tk Extensions under Windows 95/NT</H2>
 511
 512
 513<p>
 514Building a SWIG extension to Tcl/Tk under Windows 95/NT is roughly
 515similar to the process used with Unix.  Normally, you will want to
 516produce a DLL that can be loaded into tclsh or wish.  This section
 517covers the process of using SWIG with Microsoft Visual C++.
 518although the procedure may be similar with other compilers.
 519</p>
 520
 521<H3><a name="Tcl_nn12"></a>37.2.1 Running SWIG from Developer Studio</H3>
 522
 523
 524<p>
 525If you are developing your application within Microsoft developer
 526studio, SWIG can be invoked as a custom build option.  The process
 527roughly 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
 534files, 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
 536different suffix for the wrapper file such as
 537<tt>example_wrap.cxx</tt>. Don't worry if the wrapper file doesn't
 538exist 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
 541settings, 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
 552installation 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
 556example "<tt>tcl80.lib</tt>".  Also, set the name of the output file
 557to match the name of your Tcl module (ie. example.dll).
 558
 559<li>Build your project.
 560</ul>
 561
 562<p>
 563Now, assuming all went well, SWIG will be automatically invoked when
 564you build your project.  Any changes made to the interface file will
 565result in SWIG being automatically invoked to produce a new version of
 566the 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.
 568For example :
 569</p>
 570
 571<div class="code"><pre>
 572MSDOS &gt; tclsh80
 573% load example.dll
 574% fact 4
 57524
 576%
 577</pre></div>
 578
 579<H3><a name="Tcl_nn13"></a>37.2.2 Using NMAKE</H3>
 580
 581
 582<p>
 583Alternatively, SWIG extensions can be built by writing a Makefile for
 584NMAKE.  To do this, make sure the environment variables for MSVC++ are
 585available and the MSVC++ tools are in your path.  Now, just write a
 586short Makefile like this :
 587</p>
 588
 589<div class="code"><pre>
 590# Makefile for building various SWIG generated extensions
 591
 592SRCS          = example.c
 593IFILE         = example
 594INTERFACE     = $(IFILE).i
 595WRAPFILE      = $(IFILE)_wrap.c
 596
 597# Location of the Visual C++ tools (32 bit assumed)
 598
 599TOOLS         = c:\msdev
 600TARGET        = example.dll
 601CC            = $(TOOLS)\bin\cl.exe
 602LINK          = $(TOOLS)\bin\link.exe
 603INCLUDE32     = -I$(TOOLS)\include
 604MACHINE       = IX86
 605
 606# C Library needed to build a DLL
 607
 608DLLIBC        = msvcrt.lib oldnames.lib  
 609
 610# Windows libraries that are apparently needed
 611WINLIB        = kernel32.lib advapi32.lib user32.lib gdi32.lib comdlg32.lib 
 612winspool.lib
 613
 614# Libraries common to all DLLs
 615LIBS          = $(DLLIBC) $(WINLIB) 
 616
 617# Linker options
 618LOPT      = -debug:full -debugtype:cv /NODEFAULTLIB /RELEASE /NOLOGO /
 619MACHINE:$(MACHINE) -entry:_DllMainCRTStartup@12 -dll
 620
 621# C compiler flags
 622
 623CFLAGS    = /Z7 /Od /c /nologo
 624TCL_INCLUDES  = -Id:\tcl8.0a2\generic -Id:\tcl8.0a2\win
 625TCLLIB        = d:\tcl8.0a2\win\tcl80.lib
 626
 627tcl::
 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>
 636To build the extension, run NMAKE (you may need to run vcvars32
 637first).  This is a pretty minimal Makefile, but hopefully its enough
 638to get you started.  With a little practice, you'll be making lots of
 639Tcl extensions.
 640</p>
 641
 642<H2><a name="Tcl_nn14"></a>37.3 A tour of basic C/C++ wrapping</H2>
 643
 644
 645<p>
 646By default, SWIG tries to build a very natural Tcl interface to your
 647C/C++ code.  Functions are wrapped as functions, classes are wrapped
 648in an interface that mimics the style of Tk widgets and [incr Tcl]
 649classes.  This section briefly covers the essential aspects of this
 650wrapping.
 651</p>
 652
 653<H3><a name="Tcl_nn15"></a>37.3.1 Modules</H3>
 654
 655
 656<p>
 657The SWIG <tt>%module</tt> directive specifies the name of the Tcl
 658module. If you specify `<tt>%module example</tt>', then everything is
 659compiled into an extension module <tt>example.so</tt>. When choosing a
 660module name, make sure you don't use the same name as a built-in
 661Tcl command.
 662</p>
 663
 664<p>
 665One pitfall to watch out for is module names involving numbers.  If
 666you specify a module name like <tt>%module md5</tt>, you'll find that the
 667load command no longer seems to work:
 668</p>
 669
 670<div class="code">
 671<pre>
 672% load ./md5.so
 673couldn't find procedure Md_Init
 674</pre>
 675</div>
 676
 677<p>
 678To 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>37.3.2 Functions</H3>
 688
 689
 690<p>
 691Global functions are wrapped as new Tcl built-in commands.  For example,
 692</p>
 693
 694<div class="code"><pre>
 695%module example
 696int fact(int n);
 697</pre></div>
 698
 699<p>
 700creates a built-in function <tt>fact</tt> that works exactly
 701like you think it does:
 702</p>
 703
 704<div class="code"><pre>
 705% load ./example.so
 706% fact 4
 70724
 708% set x [fact 6]
 709%
 710</pre></div>
 711
 712<H3><a name="Tcl_nn17"></a>37.3.3 Global variables</H3>
 713
 714
 715<p>
 716C/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 %{
 724extern double density;
 725%}
 726...
 727</pre></div>
 728
 729<p>
 730Now look at the Tcl interface:
 731</p>
 732
 733<div class="code"><pre>
 734% puts $density          # Output value of C global variable
 7351.0
 736% set density 0.95       # Change value
 737</pre></div>
 738
 739<p>
 740If you make an error in variable assignment, you will get an
 741error message.  For example:
 742</p>
 743
 744<div class="code"><pre>
 745% set density "hello"
 746can't set "density": Type error. expected a double.
 747%
 748</pre></div>
 749
 750<p>
 751If a variable is declared as <tt>const</tt>, it is wrapped as a
 752read-only variable.  Attempts to modify its value will result in an
 753error.
 754</p>
 755
 756<p>
 757To 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%{
 763extern char *path;
 764%}
 765%immutable;
 766extern char *path;
 767%mutable;
 768</pre>
 769</div>
 770
 771<p>
 772The <tt>%immutable</tt> directive stays in effect until it is explicitly disabled or cleared using
 773<tt>%mutable</tt>.
 774See the <a href="SWIG.html#SWIG_readonly_variables">Creating read-only variables</a> section for further details.
 775</p>
 776
 777<p>
 778If 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%{
 784extern char *path;
 785%}
 786%immutable path;
 787...
 788extern char *path;      // Read-only (due to %immutable)
 789</pre>
 790</div>
 791
 792<H3><a name="Tcl_nn18"></a>37.3.4 Constants and enums</H3>
 793
 794
 795<p>
 796C/C++ constants are installed as global Tcl variables containing the
 797appropriate 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
 806enum 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>
 814For enums, make sure that the definition of the enumeration actually appears in a header
 815file or in the wrapper file somehow---if you just stick an enum in a SWIG interface without
 816also telling the C compiler about it, the wrapper code won't compile.
 817</p>
 818
 819<p>
 820Note:  declarations declared as <tt>const</tt> are wrapped as read-only variables and
 821will be accessed using the <tt>cvar</tt> object described in the previous section.  They
 822are 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>
 826Constants are not guaranteed to remain constant in Tcl---the value
 827of the constant could be accidentally reassigned.You will just have to be careful.
 828</p>
 829
 830<p>
 831A peculiarity of installing constants as variables is that it is necessary to use the Tcl <tt>global</tt> statement to
 832access constants in procedure bodies.  For example:
 833</p>
 834
 835<div class="code">
 836<pre>
 837proc blah {} {
 838   global FOO
 839   bar $FOO
 840}
 841</pre>
 842</div>
 843
 844<p>
 845If a program relies on a lot of constants, this can be extremely annoying.  To fix the problem, consider using the
 846following typemap rule:
 847</p>
 848
 849<div class="code">
 850<pre>
 851%apply int CONSTANT { int x };
 852#define FOO 42
 853...
 854void bar(int x);
 855</pre>
 856</div>
 857
 858<p>
 859When applied to an input argument, the <tt>CONSTANT</tt> rule allows a constant to be passed to a function using
 860its actual value or a symbolic identifier name.  For example:
 861</p>
 862
 863<div class="code">
 864<pre>
 865proc blah {} {
 866   bar FOO
 867}
 868</pre>
 869</div>
 870
 871<p>
 872When an identifier name is given, it is used to perform an implicit hash-table lookup of the value during argument 
 873conversion.  This allows the <tt>global</tt> statement to be omitted.
 874</p>
 875
 876<H3><a name="Tcl_nn19"></a>37.3.5 Pointers</H3>
 877
 878
 879<p>
 880C/C++ pointers are fully supported by SWIG.  Furthermore, SWIG has no problem working with
 881incomplete type information.  Here is a rather simple interface:
 882</p>
 883
 884<div class="code">
 885<pre>
 886%module example
 887
 888FILE *fopen(const char *filename, const char *mode);
 889int fputs(const char *, FILE *);
 890int fclose(FILE *);
 891</pre>
 892</div>
 893
 894<p>
 895When wrapped, you will be able to use the functions in a natural way from Tcl. 
 896For 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>
 909If this makes you uneasy, rest assured that there is no
 910deep magic involved.  Underneath the covers, pointers to C/C++ objects are
 911simply represented as opaque values--normally an encoded character
 912string like this:
 913</p>
 914
 915<div class="code"><pre>
 916% puts $f
 917_c0671108_p_FILE
 918% 
 919</pre></div>
 920
 921<p>
 922This pointer value can be freely passed around to different C functions that
 923expect to receive an object of type <tt>FILE *</tt>.  The only thing you can't do is 
 924dereference the pointer from Tcl.
 925</p>
 926
 927<p>
 928The NULL pointer is represented by the string <tt>NULL</tt>.
 929</p>
 930
 931<p>
 932As much as you might be inclined to modify a pointer value directly
 933from Tcl, don't.  The hexadecimal encoding is not necessarily the
 934same as the logical memory address of the underlying object.  Instead
 935it is the raw byte encoding of the pointer value.  The encoding will
 936vary depending on the native byte-ordering of the platform (i.e.,
 937big-endian vs. little-endian).  Similarly, don't try to manually cast
 938a pointer to a new type by simply replacing the type-string.  This
 939may not work like you expect and it is particularly dangerous when
 940casting C++ objects. If you need to cast a pointer or
 941change its value, consider writing some helper functions instead.  For
 942example:
 943</p>
 944
 945<div class="code">
 946<pre>
 947%inline %{
 948/* C-style cast */
 949Bar *FooToBar(Foo *f) {
 950   return (Bar *) f;
 951}
 952
 953/* C++-style cast */
 954Foo *BarToFoo(Bar *b) {
 955   return dynamic_cast&lt;Foo*&gt;(b);
 956}
 957
 958Foo *IncrFoo(Foo *f, int i) {
 959    return f+i;
 960}
 961%}
 962</pre>
 963</div>
 964
 965<p>
 966Also, if working with C++, you should always try
 967to use the new C++ style casts.  For example, in the above code, the
 968C-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>37.3.6 Structures</H3>
 973
 974
 975<p>
 976If you wrap a C structure, it is wrapped by a Tcl interface that somewhat resembles a Tk widget.
 977This provides a very natural interface.  For example,
 978</p>
 979
 980<div class="code"><pre>
 981struct Vector {
 982	double x,y,z;
 983};
 984
 985</pre></div>
 986
 987<p>
 988is 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]"
 9953.5 7.2 0.0
 996% 
 997</pre></div>
 998
 999<p>
1000Similar access is provided for unions and the data members of C++ classes.
1001</p>
1002
1003<p>
1004In the above example, <tt>v</tt> is a name that's used for the object.  However,
1005underneath the covers, there's a pointer to a raw C structure.  This can be obtained
1006by 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>
1017Further details about the relationship between the Tcl and the underlying C structure
1018are covered a little later.
1019</p>
1020
1021<p>
1022<tt>const</tt> members of a structure are read-only. Data members
1023can also be forced to be read-only using the <tt>%immutable</tt> directive. For example:
1024</p>
1025
1026<div class="code">
1027<pre>
1028struct Foo {
1029   ...
1030   %immutable;
1031   int x;        /* Read-only members */
1032   char *name;
1033   %mutable;
1034   ...
1035};
1036</pre>
1037</div>
1038
1039<p>
1040When <tt>char *</tt> members of a structure are wrapped, the contents are assumed to be
1041dynamically allocated using <tt>malloc</tt> or <tt>new</tt> (depending on whether or not
1042SWIG is run with the -c++ option).   When the structure member is set, the old contents will be 
1043released and a new value created.   If this is not the behavior you want, you will have to use
1044a typemap (described later).
1045</p>
1046
1047<p>
1048If a structure contains arrays, access to those arrays is managed through pointers.  For
1049example, consider this:
1050</p>
1051
1052<div class="code">
1053<pre>
1054struct Bar {
1055    int  x[16];
1056};
1057</pre>
1058</div>
1059
1060<p>
1061If 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>
1074This pointer can be passed around to functions that expect to receive
1075an <tt>int *</tt> (just like C).   You can also set the value of an array member using
1076another 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>
1087For array assignment, SWIG copies the entire contents of the array starting with the data pointed
1088to by <tt>b.x</tt>.   In this example, 16 integers would be copied.  Like C, SWIG makes
1089no assumptions about bounds checking---if you pass a bad pointer, you may get a segmentation
1090fault or access violation.
1091</p>
1092
1093<p>
1094When a member of a structure is itself a structure, it is handled as a
1095pointer.  For example, suppose you have two structures like this:
1096</p>
1097
1098<div class="code">
1099<pre>
1100struct Foo {
1101   int a;
1102};
1103
1104struct Bar {
1105   Foo f;
1106};
1107</pre>
1108</div>
1109
1110<p>
1111Now, 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>
1122In this case, <tt>x</tt> is a pointer that points to the <tt>Foo</tt> that is inside <tt>b</tt>.
1123This is the same value as generated by this C code:
1124</p>
1125
1126<div class="code">
1127<pre>
1128Bar b;
1129Foo *x = &amp;b-&gt;f;       /* Points inside b */
1130</pre>
1131</div>
1132
1133<p>
1134However, one peculiarity of accessing a substructure like this is that the returned
1135value 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
1143invalid command name "x"
1144</pre>
1145</div>
1146
1147<p>
1148This is because the returned value was not created in a normal way from the interpreter (x is 
1149not a command object). To make it function normally, just
1150evaluate 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
11580
1159%
1160</pre>
1161</div>
1162
1163<p>
1164In this example, <tt>x</tt> points inside the original structure.  This means that modifications
1165work 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>
1179In many of these structure examples, a simple name like "v" or "b" has been given
1180to wrapped structures.  If necessary, this name can be passed to functions
1181that expect to receive an object.  For example, if you have a function like this,
1182</p>
1183
1184<div class="code">
1185<pre>
1186void blah(Foo *f);
1187</pre>
1188</div>
1189
1190<p>
1191you 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>
1202It is also possible to call the function using the raw pointer value. For
1203instance:
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>
1213It 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>
1227Finally, to destroy objects created from Tcl, you can either let the object
1228name 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>
1239or
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>
1250Note: Tcl only destroys the underlying object if it has ownership.  See the
1251memory management section that appears shortly.
1252</p>
1253
1254<H3><a name="Tcl_nn21"></a>37.3.7 C++ classes</H3>
1255
1256
1257<p>
1258C++ classes are wrapped as an extension of structure wrapping. For example, if you have this class,
1259</p>
1260
1261<div class="code"><pre>
1262class List {
1263public:
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>
1275you 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
1284Stout
1285% puts [l cget -length]
12863
1287%
1288</pre></div>
1289
1290<p>
1291Class data members are accessed in the same manner as C structures.  
1292</p>
1293
1294<p>
1295Static class members are accessed as global functions or variables.
1296To illustrate, suppose you have a class like this:
1297</p>
1298
1299<div class="code">
1300<pre>
1301class Spam {
1302public:
1303   static void foo();
1304   static int bar;
1305
1306};
1307</pre>
1308</div>
1309
1310<p>
1311In 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>37.3.8 C++ inheritance</H3>
1322
1323
1324<p>
1325SWIG is fully aware of issues related to C++ inheritance.  Therefore, if you have
1326classes like this
1327</p>
1328
1329<div class="code">
1330<pre>
1331class Foo {
1332...
1333};
1334
1335class Bar : public Foo {
1336...
1337};
1338</pre>
1339</div>
1340
1341<p>
1342An object of type <tt>Bar</tt> can be used where a <tt>Foo</tt> is expected.  For
1343example, if you have this function:
1344</p>
1345
1346<div class="code">
1347<pre>
1348void spam(Foo *f);
1349</pre>
1350</div>
1351
1352<p>
1353then the function <tt>spam()</tt> accepts a <tt>Foo *</tt> or a pointer to any class derived from <tt>Foo</tt>.
1354For 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>
1367It is safe to use multiple inheritance with SWIG.
1368</p>
1369
1370<H3><a name="Tcl_nn23"></a>37.3.9 Pointers, references, values, and arrays</H3>
1371
1372
1373<p>
1374In C++, there are many different ways a function might receive
1375and manipulate objects.  For example:
1376</p>
1377
1378<div class="code">
1379<pre>
1380void spam1(Foo *x);      // Pass by pointer
1381void spam2(Foo &amp;x);      // Pass by reference
1382void spam3(Foo x);       // Pass by value
1383void spam4(Foo x[]);     // Array of objects
1384</pre>
1385</div>
1386
1387<p>
1388In Tcl, there is no detailed distinction like this.
1389Because of this, SWIG unifies all of these types
1390together in the wrapper code.  For instance, if you actually had the
1391above 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>
1405Similar behavior occurs for return values.  For example, if you had
1406functions like this,
1407</p>
1408
1409<div class="code">
1410<pre>
1411Foo *spam5();
1412Foo &amp;spam6();
1413Foo  spam7();
1414</pre>
1415</div>
1416
1417<p>
1418then all three functions will return a pointer to some <tt>Foo</tt> object.
1419Since the third function (spam7) returns a value, newly allocated memory is used 
1420to hold the result and a pointer is returned (Tcl will release this memory 
1421when the return value is garbage collected).
1422</p>
1423
1424<H3><a name="Tcl_nn24"></a>37.3.10 C++ overloaded functions</H3>
1425
1426
1427<p>
1428C++ overloaded functions, methods, and constructors are mostly supported by SWIG.  For example,
1429if you have two functions like this:
1430</p>
1431
1432<div class="code">
1433<pre>
1434void foo(int);
1435void foo(char *c);
1436</pre>
1437</div>
1438
1439<p>
1440You 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>
1451Similarly, if you have a class like this,
1452</p>
1453
1454<div class="code">
1455<pre>
1456class Foo {
1457public:
1458    Foo();
1459    Foo(const Foo &amp;);
1460    ...
1461};
1462</pre>
1463</div>
1464
1465<p>
1466you 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>
1477Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG
1478can't disambiguate. For example:
1479</p>
1480
1481<div class="code">
1482<pre>
1483void spam(int);
1484void spam(short);
1485</pre>
1486</div>
1487
1488<p>
1489or
1490</p>
1491
1492<div class="code">
1493<pre>
1494void foo(Bar *b);
1495void foo(Bar &amp;b);
1496</pre>
1497</div>
1498
1499<p>
1500If declarations such as these appear, you will get a warning message like this:
1501</p>
1502
1503<div class="code">
1504<pre>
1505example.i:12: Warning 509: Overloaded method spam(short) effectively ignored,
1506example.i:11: Warning 509: as it is shadowed by spam(int).
1507</pre>
1508</div>
1509
1510<p>
1511To 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...
1518void spam(int);    
1519void spam(short);   // Accessed as spam_short
1520</pre>
1521</div>
1522
1523<p>
1524or
1525</p>
1526
1527<div class="code">
1528<pre>
1529%ignore spam(short);
1530...
1531void spam(int);    
1532void spam(short);   // Ignored
1533</pre>
1534</div>
1535
1536<p>
1537SWIG resolves overloaded functions and methods using a disambiguation scheme that ranks and sorts
1538declarations according to a set of type-precedence rules.    The order in which declarations appear
1539in the input does not matter except in situations where ambiguity arises--in this case, the
1540first declaration takes precedence.
1541</p>
1542
1543<p>
1544Please refer to the "SWIG and C++" chapter for more information about overloading. 
1545</p>
1546
1547<H3><a name="Tcl_nn25"></a>37.3.11 C++ operators</H3>
1548
1549
1550<p>
1551Certain C++ overloaded operators can be handled automatically by SWIG.  For example,
1552consider a class like this:
1553</p>
1554
1555<div class="code">
1556<pre>
1557class Complex {
1558private:
1559  double rpart, ipart;
1560public:
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>
1576When 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
158510.0
1586% $e im
158712.0
1588</pre>
1589</div>
1590
1591<p>
1592It should be stressed that operators in SWIG have no relationship to operators
1593in 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
1595statement <tt>[c + d]</tt> is really just invoking the <tt>+</tt> method on <tt>c</tt>.
1596When more than operator is defined (with different arguments), the standard
1597method 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]"
160610.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>
1615One restriction with operator overloading support is that SWIG is not
1616able to fully handle operators that aren't defined as part of the class.
1617For example, if you had code like this
1618</p>
1619
1620<div class="code">
1621<pre>
1622class Complex {
1623...
1624friend Complex operator+(double, const Complex &amp;c);
1625...
1626};
1627</pre>
1628</div>
1629
1630<p>
1631then SWIG doesn't know what to do with the friend function--in fact,
1632it simply ignores it and issues a warning.   You can still wrap the operator,
1633but 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...
1640Complex operator+(double, const Complex &amp;c);
1641</pre>
1642</div>
1643
1644<p>
1645There are ways to make this operator appear as part of the class using the <tt>%extend</tt> directive.
1646Keep reading.
1647</p>
1648
1649<H3><a name="Tcl_nn26"></a>37.3.12 C++ namespaces</H3>
1650
1651
1652<p>
1653SWIG is aware of C++ namespaces, but namespace names do not appear in
1654the module nor do namespaces result in a module that is broken up into
1655submodules or packages.  For example, if you have a file like this,
1656</p>
1657
1658<div class="code">
1659<pre>
1660%module example
1661
1662namespace foo {
1663   int fact(int n);
1664   struct Vector {
1665       double x,y,z;
1666   };
1667};
1668</pre>
1669</div>
1670
1671<p>
1672it works in Tcl as follows:
1673</p>
1674
1675<div class="code">
1676<pre>
1677% load ./example.so
1678% fact 3
16796
1680% Vector v
1681% v configure -x 3.4
1682</pre>
1683</div>
1684
1685<p>
1686If your program has more than one namespace, name conflicts (if any) can be resolved using <tt>%rename</tt>
1687For example:
1688</p>
1689
1690<div class="code">
1691<pre>
1692%rename(Bar_spam) Bar::spam;
1693
1694namespace Foo {
1695    int spam();
1696}
1697
1698namespace Bar {
1699    int spam();
1700}
1701</pre>
1702</div>
1703
1704<p>
1705If you have more than one namespace and your want to keep their
1706symbols separate, consider wrapping them as separate SWIG modules.
1707For example, make the module name the same as the namespace and create
1708extension modules for each namespace separately.  If your program
1709utilizes thousands of small deeply nested namespaces each with
1710identical symbol names, well, then you get what you deserve.
1711</p>
1712
1713<H3><a name="Tcl_nn27"></a>37.3.13 C++ templates</H3>
1714
1715
1716<p>
1717C++ templates don't present a huge problem for SWIG.  However, in order
1718to create wrappers, you have to tell SWIG to create wrappers for a particular
1719template instantiation.  To do this, you use the <tt>%template</tt> directive.
1720For example:
1721</p>
1722
1723<div class="code">
1724<pre>
1725%module example
1726%{
1727#include "pair.h"
1728%}
1729
1730template&lt;class T1, class T2&gt;
1731struct 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>
1746In Tcl:
1747</p>
1748
1749<div class="code">
1750<pre>
1751% pairii p 3 4
1752% p cget -first
17533
1754% p cget -second
17554
1756</pre>
1757</div>
1758
1759<p>
1760Obviously, there is more to template wrapping than shown in this example.
1761More details can be found in the <a href="SWIGPlus.html#SWIGPlus">SWIG and C++</a> chapter.   Some more complicated
1762examples will appear later.
1763</p>
1764
1765<H3><a name="Tcl_nn28"></a>37.3.14 C++ Smart Pointers</H3>
1766
1767
1768<p>
1769In certain C++ programs, it is common to use classes that have been wrapped by
1770so-called "smart pointers."   Generally, this involves the use of a template class
1771that implements <tt>operator-&gt;()</tt> like this:
1772</p>
1773
1774<div class="code">
1775<pre>
1776template&lt;class T&gt; class SmartPtr {
1777   ...
1778   T *operator-&gt;();
1779   ...
1780}
1781</pre>
1782</div>
1783
1784<p>
1785Then, if you have a class like this,
1786</p>
1787
1788<div class="code">
1789<pre>
1790class Foo {
1791public:
1792     int x;
1793     int bar();
1794};
1795</pre>
1796</div>
1797
1798<p>
1799A smart pointer would be used in C++ as follows:
1800</p>
1801
1802<div class="code">
1803<pre>
1804SmartPtr&lt;Foo&gt; p = CreateFoo();   // Created somehow (not shown)
1805...
1806p-&gt;x = 3;                        // Foo::x
1807int y = p-&gt;bar();                // Foo::bar
1808</pre>
1809</div>
1810
1811<p>
1812To 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.
1814For 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>
1827Now, 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>
1839If you ever need to access the underlying pointer returned by <tt>operator-&gt;()</tt> itself,
1840simply 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>37.4 Further details on the Tcl class interface</H2>
1850
1851
1852<p>
1853In the previous section, a high-level view of Tcl wrapping was
1854presented.  A key component of this wrapping is that structures and
1855classes are wrapped by Tcl class-like objects. This provides a very
1856natural Tcl interface and allows SWIG to support a number of
1857advanced features such as operator overloading.   However, a number
1858of low-level details were omitted.  This section provides a brief overview
1859of how the proxy classes work.
1860</p>
1861
1862<H3><a name="Tcl_nn30"></a>37.4.1 Proxy classes</H3>
1863
1864
1865<p>
1866In the <a href="SWIG.html#SWIG">"SWIG basics"</a> and <a href="SWIGPlus.html#SWIGPlus">"SWIG and C++"</a> chapters,
1867details of low-level structure and class wrapping are described.  To summarize those chapters, if you
1868have a class like this
1869</p>
1870
1871<div class="code">
1872<pre>
1873class Foo {
1874public:
1875     int x;
1876     int spam(int);
1877     ...
1878</pre>
1879</div>
1880
1881<p>
1882then SWIG transforms it into a set of low-level procedural wrappers. For example:
1883</p>
1884
1885<div class="code">
1886<pre>
1887Foo *new_Foo() {
1888    return new Foo();
1889}
1890void delete_Foo(Foo *f) {
1891    delete f;
1892}
1893int Foo_x_get(Foo *f) {
1894    return f-&gt;x;
1895}
1896void Foo_x_set(Foo *f, int value) {
1897    f-&gt;x = value;
1898}
1899int Foo_spam(Foo *f, int arg1) {
1900    return f-&gt;spam(arg1);
1901}
1902</pre>
1903</div>
1904
1905<p>
1906These 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
19140
1915% Foo_spam $f 3
19161
1917%
1918</pre>
1919</div>
1920
1921<p>
1922However, in addition to this, the classname <tt>Foo</tt> is used as an object constructor
1923function.   This allows objects to be encapsulated objects that look a lot like Tk widgets
1924as shown in the last section.
1925</p>
1926
1927<H3><a name="Tcl_nn31"></a>37.4.2 Memory management</H3>
1928
1929
1930<p>
1931Associated with each wrapped object, is an ownership flag <tt>thisown</tt>   The value of this
1932flag determines who is responsible for deleting the underlying C++ object.  If set to 1,
1933the Tcl interpreter destroys the C++ object when the proxy class is 
1934garbage collected.   If set to 0 (or if the attribute is missing), then the destruction
1935of the proxy class has no effect on the C++ object.
1936</p>
1937
1938<p>
1939When an object is created by a constructor or returned by value, Tcl automatically takes
1940ownership of the result.  For example:
1941</p>
1942
1943<div class="code">
1944<pre>
1945class Foo {
1946public:
1947    Foo();
1948    Foo bar();
1949};
1950</pre>
1951</div>
1952
1953<p>
1954In Tcl:
1955</p>
1956
1957<div class="code">
1958<pre>
1959% Foo f
1960% f cget -thisown
19611
1962% set g [f bar]
1963% $g cget -thisown
19641
1965</pre>
1966</div>
1967
1968<p>
1969On the other hand, when pointers are returned to Tcl, there is often no way to know where
1970they came from.  Therefore, the ownership is set to zero.  For example:
1971</p>
1972
1973<div class="code">
1974<pre>
1975class Foo {
1976public:
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
19910
1992% 
1993</pre>
1994</div>
1995
1996<p>
1997This behavior is especially important for classes that act as
1998containers.  For example, if a method returns a pointer to an object
1999that is contained inside another object, you definitely don't want
2000Tcl to assume ownership and destroy it!
2001</p>
2002
2003<p>
2004Related to containers, ownership issues can arise whenever an object is assigned to a member
2005or global variable.  For example, consider this interface:
2006</p>
2007
2008<div class="code">
2009<pre>
2010%module example
2011
2012struct Foo {
2013    int  value;
2014    Foo  *next;
2015};
2016
2017Foo *head = 0;
2018</pre>
2019</div>
2020
2021<p>
2022When wrapped in Tcl, careful observation will reveal that ownership changes whenever an object
2023is assigned to a global variable.  For example:
2024</p>
2025
2026<div class="code">
2027<pre>
2028% Foo f
2029% f cget -thisown
20301
2031% set head f
2032% f cget -thisown
20330
2034</pre>
2035</div>
2036
2037<p>
2038In this case, C is now holding a reference to the object---you probably don't want Tcl to destroy it.
2039Similarly, 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
20471
2048% g cget -thisown
20491
2050% f configure -next g
2051% g cget -thisown 
20520
2053%
2054</pre>
2055</div>
2056
2057<p>
2058For the most part, memory management issues remain hidden.  However,
2059there are occasionally situations where you might have to manually
2060change the ownership of an object.  For instance, consider code like this:
2061</p>
2062
2063<div class="code">
2064<pre>
2065class Node {
2066   Object *value;
2067public:
2068   void set_value(Object *v) { value = v; }
2069   ...
2070};
2071</pre>
2072</div>
2073
2074<p>
2075Now, 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
20841
2085% 
2086</pre>
2087</div>
2088
2089<p>
2090In 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
2092has occurred.  Therefore, Tcl still thinks that it has ownersh…

Large files files are truncated, but you can click here to view the full file