PageRenderTime 83ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/trunk/Doc/Manual/Tcl.html

#
HTML | 2846 lines | 2334 code | 510 blank | 2 comment | 0 complexity | 02fb97030fb2a61385f4cfb887d8ad74 MD5 | raw file
Possible License(s): LGPL-2.1, Cube, GPL-3.0, 0BSD, GPL-2.0

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. <body bgcolor="#ffffff">
  8. <H1><a name="Tcl"></a>37 SWIG and Tcl</H1>
  9. <!-- INDEX -->
  10. <div class="sectiontoc">
  11. <ul>
  12. <li><a href="#Tcl_nn2">Preliminaries</a>
  13. <ul>
  14. <li><a href="#Tcl_nn3">Getting the right header files</a>
  15. <li><a href="#Tcl_nn4">Compiling a dynamic module</a>
  16. <li><a href="#Tcl_nn5">Static linking</a>
  17. <li><a href="#Tcl_nn6">Using your module</a>
  18. <li><a href="#Tcl_nn7">Compilation of C++ extensions</a>
  19. <li><a href="#Tcl_nn8">Compiling for 64-bit platforms</a>
  20. <li><a href="#Tcl_nn9">Setting a package prefix</a>
  21. <li><a href="#Tcl_nn10">Using namespaces</a>
  22. </ul>
  23. <li><a href="#Tcl_nn11">Building Tcl/Tk Extensions under Windows 95/NT</a>
  24. <ul>
  25. <li><a href="#Tcl_nn12">Running SWIG from Developer Studio</a>
  26. <li><a href="#Tcl_nn13">Using NMAKE</a>
  27. </ul>
  28. <li><a href="#Tcl_nn14">A tour of basic C/C++ wrapping</a>
  29. <ul>
  30. <li><a href="#Tcl_nn15">Modules</a>
  31. <li><a href="#Tcl_nn16">Functions</a>
  32. <li><a href="#Tcl_nn17">Global variables</a>
  33. <li><a href="#Tcl_nn18">Constants and enums</a>
  34. <li><a href="#Tcl_nn19">Pointers</a>
  35. <li><a href="#Tcl_nn20">Structures</a>
  36. <li><a href="#Tcl_nn21">C++ classes</a>
  37. <li><a href="#Tcl_nn22">C++ inheritance</a>
  38. <li><a href="#Tcl_nn23">Pointers, references, values, and arrays</a>
  39. <li><a href="#Tcl_nn24">C++ overloaded functions</a>
  40. <li><a href="#Tcl_nn25">C++ operators</a>
  41. <li><a href="#Tcl_nn26">C++ namespaces</a>
  42. <li><a href="#Tcl_nn27">C++ templates</a>
  43. <li><a href="#Tcl_nn28">C++ Smart Pointers</a>
  44. </ul>
  45. <li><a href="#Tcl_nn29">Further details on the Tcl class interface</a>
  46. <ul>
  47. <li><a href="#Tcl_nn30">Proxy classes</a>
  48. <li><a href="#Tcl_nn31">Memory management</a>
  49. </ul>
  50. <li><a href="#Tcl_nn32">Input and output parameters</a>
  51. <li><a href="#Tcl_nn33">Exception handling </a>
  52. <li><a href="#Tcl_nn34">Typemaps</a>
  53. <ul>
  54. <li><a href="#Tcl_nn35">What is a typemap?</a>
  55. <li><a href="#Tcl_nn36">Tcl typemaps</a>
  56. <li><a href="#Tcl_nn37">Typemap variables</a>
  57. <li><a href="#Tcl_nn38">Converting a Tcl list to a char ** </a>
  58. <li><a href="#Tcl_nn39">Returning values in arguments</a>
  59. <li><a href="#Tcl_nn40">Useful functions</a>
  60. <li><a href="#Tcl_nn41">Standard typemaps</a>
  61. <li><a href="#Tcl_nn42">Pointer handling</a>
  62. </ul>
  63. <li><a href="#Tcl_nn43">Turning a SWIG module into a Tcl Package.</a>
  64. <li><a href="#Tcl_nn44">Building new kinds of Tcl interfaces (in Tcl)</a>
  65. <ul>
  66. <li><a href="#Tcl_nn45">Proxy classes</a>
  67. </ul>
  68. <li><a href="#Tcl_nn46">Tcl/Tk Stubs</a>
  69. </ul>
  70. </div>
  71. <!-- INDEX -->
  72. <p>
  73. <b>Caution: This chapter is under repair!</b>
  74. </p>
  75. <p>
  76. This chapter discusses SWIG's support of Tcl. SWIG currently requires
  77. Tcl 8.0 or a later release. Earlier releases of SWIG supported Tcl 7.x, but
  78. this is no longer supported.
  79. </p>
  80. <H2><a name="Tcl_nn2"></a>37.1 Preliminaries</H2>
  81. <p>
  82. To build a Tcl module, run SWIG using the <tt>-tcl</tt> option :
  83. </p>
  84. <div class="code"><pre>
  85. $ swig -tcl example.i
  86. </pre></div>
  87. <p>
  88. If building a C++ extension, add the <tt>-c++</tt> option:
  89. </p>
  90. <div class="code"><pre>
  91. $ swig -c++ -tcl example.i
  92. </pre></div>
  93. <p>
  94. This creates a file <tt>example_wrap.c</tt> or
  95. <tt>example_wrap.cxx</tt> that contains all of the code needed to
  96. build a Tcl extension module. To finish building the module, you
  97. need to compile this file and link it with the rest of your program.
  98. </p>
  99. <H3><a name="Tcl_nn3"></a>37.1.1 Getting the right header files</H3>
  100. <p>
  101. In order to compile the wrapper code, the compiler needs the <tt>tcl.h</tt> header file.
  102. This file is usually contained in the directory
  103. </p>
  104. <div class="code"><pre>
  105. /usr/local/include
  106. </pre></div>
  107. <p>
  108. Be aware that some Tcl versions install this header file with a version number attached to it. If
  109. this is the case, you should probably make a symbolic link so that <tt>tcl.h</tt> points to the correct
  110. header file.
  111. </p>
  112. <H3><a name="Tcl_nn4"></a>37.1.2 Compiling a dynamic module</H3>
  113. <p>
  114. The preferred approach to building an extension module is to compile it into
  115. a shared object file or DLL. To do this, you will need to compile your program
  116. using commands like this (shown for Linux):
  117. </p>
  118. <div class="code"><pre>
  119. $ swig -tcl example.i
  120. $ gcc -c example.c
  121. $ gcc -c example_wrap.c -I/usr/local/include
  122. $ gcc -shared example.o example_wrap.o -o example.so
  123. </pre></div>
  124. <p>
  125. The exact commands for doing this vary from platform to platform.
  126. SWIG tries to guess the right options when it is installed. Therefore,
  127. you may want to start with one of the examples in the <tt>SWIG/Examples/tcl</tt>
  128. directory. If that doesn't work, you will need to read the man-pages for
  129. your compiler and linker to get the right set of options. You might also
  130. check the <a href="http://www.dabeaz.com/cgi-bin/wiki.pl">SWIG Wiki</a> for
  131. additional information.
  132. </p>
  133. <p>
  134. When linking the module, the name of the output file has to match the name
  135. of the module. If the name of your SWIG module is "<tt>example</tt>", the
  136. name of the corresponding object file should be
  137. "<tt>example.so</tt>".
  138. The name of the module is specified using the <tt>%module</tt> directive or the
  139. <tt> -module</tt> command line option.
  140. </p>
  141. <H3><a name="Tcl_nn5"></a>37.1.3 Static linking</H3>
  142. <p>
  143. An alternative approach to dynamic linking is to rebuild the Tcl
  144. interpreter with your extension module added to it. In the past,
  145. this approach was sometimes necessary due to limitations in dynamic loading
  146. support on certain machines. However, the situation has improved greatly
  147. over the last few years and you should not consider this approach
  148. unless there is really no other option.
  149. </p>
  150. <p>
  151. The usual procedure for adding a new module to Tcl involves writing a
  152. special function <tt>Tcl_AppInit()</tt> and using it to initialize the interpreter and
  153. your module. With SWIG, the <tt>tclsh.i</tt> and <tt>wish.i</tt> library files
  154. can be used to rebuild the <tt>tclsh</tt> and <tt>wish</tt> interpreters respectively.
  155. For example:
  156. </p>
  157. <div class="code"><pre>
  158. %module example
  159. %inline %{
  160. extern int fact(int);
  161. extern int mod(int, int);
  162. extern double My_variable;
  163. %}
  164. %include "tclsh.i" // Include code for rebuilding tclsh
  165. </pre></div>
  166. <p>
  167. The <tt>tclsh.i</tt> library file includes supporting code that
  168. contains everything needed to rebuild tclsh. To rebuild the interpreter,
  169. you simply do something like this:
  170. </p>
  171. <div class="code"><pre>
  172. $ swig -tcl example.i
  173. $ gcc example.c example_wrap.c \
  174. -Xlinker -export-dynamic \
  175. -DHAVE_CONFIG_H -I/usr/local/include/ \
  176. -L/usr/local/lib -ltcl -lm -ldl \
  177. -o mytclsh
  178. </pre></div>
  179. <p>
  180. You will need to supply the same libraries that were used to build Tcl the first
  181. time. This may include system libraries such as <tt>-lsocket</tt>, <tt>-lnsl</tt>,
  182. and <tt>-lpthread</tt>. If this actually works, the new version of Tcl
  183. should be identical to the default version except that your extension module will be
  184. a built-in part of the interpreter.
  185. </p>
  186. <p>
  187. <b>Comment:</b> In practice, you should probably try to avoid static
  188. linking if possible. Some programmers may be inclined
  189. to use static linking in the interest of getting better performance.
  190. However, the performance gained by static linking tends to be rather
  191. minimal in most situations (and quite frankly not worth the extra
  192. hassle in the opinion of this author).
  193. </p>
  194. <H3><a name="Tcl_nn6"></a>37.1.4 Using your module</H3>
  195. <p>
  196. To use your module, simply use the Tcl <tt>load</tt> command. If
  197. all goes well, you will be able to this:
  198. </p>
  199. <div class="code"><pre>
  200. $ tclsh
  201. % load ./example.so
  202. % fact 4
  203. 24
  204. %
  205. </pre></div>
  206. <p>
  207. A common error received by first-time users is the following:
  208. </p>
  209. <div class="code">
  210. <pre>
  211. % load ./example.so
  212. couldn't find procedure Example_Init
  213. %
  214. </pre>
  215. </div>
  216. <p>
  217. This error is almost always caused when the name of the shared object file doesn't
  218. match the name of the module supplied using the SWIG <tt>%module</tt> directive.
  219. Double-check the interface to make sure the module name and the shared object
  220. file match. Another possible cause of this error is forgetting to link the SWIG-generated
  221. wrapper code with the rest of your application when creating the extension module.
  222. </p>
  223. <p>
  224. Another common error is something similar to the following:
  225. </p>
  226. <div class="code">
  227. <pre>
  228. % load ./example.so
  229. couldn't load file "./example.so": ./example.so: undefined symbol: fact
  230. %
  231. </pre>
  232. </div>
  233. <p>
  234. This error usually indicates that you forgot to include some object
  235. files or libraries in the linking of the shared library file. Make
  236. sure you compile both the SWIG wrapper file and your original program
  237. into a shared library file. Make sure you pass all of the required libraries
  238. to the linker.
  239. </p>
  240. <p>
  241. Sometimes unresolved symbols occur because a wrapper has been created
  242. for a function that doesn't actually exist in a library. This usually
  243. occurs when a header file includes a declaration for a function that
  244. was never actually implemented or it was removed from a library
  245. without updating the header file. To fix this, you can either edit
  246. the SWIG input file to remove the offending declaration or you can use
  247. the <tt>%ignore</tt> directive to ignore the declaration.
  248. </p>
  249. <p>
  250. Finally, suppose that your extension module is linked with another library like this:
  251. </p>
  252. <div class="code">
  253. <pre>
  254. $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
  255. -o example.so
  256. </pre>
  257. </div>
  258. <p>
  259. If the <tt>foo</tt> library is compiled as a shared library, you might get the following
  260. problem when you try to use your module:
  261. </p>
  262. <div class="code">
  263. <pre>
  264. % load ./example.so
  265. couldn't load file "./example.so": libfoo.so: cannot open shared object file:
  266. No such file or directory
  267. %
  268. </pre>
  269. </div>
  270. <p>
  271. This error is generated because the dynamic linker can't locate the
  272. <tt>libfoo.so</tt> library. When shared libraries are loaded, the
  273. system normally only checks a few standard locations such as
  274. <tt>/usr/lib</tt> and <tt>/usr/local/lib</tt>. To fix this problem,
  275. there are several things you can do. First, you can recompile your extension
  276. module with extra path information. For example, on Linux you can do this:
  277. </p>
  278. <div class="code">
  279. <pre>
  280. $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
  281. -Xlinker -rpath /home/beazley/projects/lib \
  282. -o example.so
  283. </pre>
  284. </div>
  285. <p>
  286. Alternatively, you can set the <tt>LD_LIBRARY_PATH</tt> environment variable to
  287. include the directory with your shared libraries.
  288. If setting <tt>LD_LIBRARY_PATH</tt>, be aware that setting this variable can introduce
  289. a noticeable performance impact on all other applications that you run.
  290. To set it only for Tcl, you might want to do this instead:
  291. </p>
  292. <div class="code">
  293. <pre>
  294. $ env LD_LIBRARY_PATH=/home/beazley/projects/lib tclsh
  295. </pre>
  296. </div>
  297. <p>
  298. Finally, you can use a command such as <tt>ldconfig</tt> to add additional search paths
  299. to the default system configuration (this requires root access and you will need to read
  300. the man pages).
  301. </p>
  302. <H3><a name="Tcl_nn7"></a>37.1.5 Compilation of C++ extensions</H3>
  303. <p>
  304. Compilation of C++ extensions has traditionally been a tricky problem.
  305. Since the Tcl interpreter is written in C, you need to take steps to
  306. make sure C++ is properly initialized and that modules are compiled
  307. correctly.
  308. </p>
  309. <p>
  310. On most machines, C++ extension modules should be linked using the C++
  311. compiler. For example:
  312. </p>
  313. <div class="code"><pre>
  314. % swig -c++ -tcl example.i
  315. % g++ -c example.cxx
  316. % g++ -c example_wrap.cxx -I/usr/local/include
  317. % g++ -shared example.o example_wrap.o -o example.so
  318. </pre></div>
  319. <p>
  320. In addition to this, you may need to include additional library
  321. files to make it work. For example, if you are using the Sun C++ compiler on
  322. Solaris, you often need to add an extra library <tt>-lCrun</tt> like this:
  323. </p>
  324. <div class="code"><pre>
  325. % swig -c++ -tcl example.i
  326. % CC -c example.cxx
  327. % CC -c example_wrap.cxx -I/usr/local/include
  328. % CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o example.so -lCrun
  329. </pre></div>
  330. <p>
  331. Of course, the extra libraries to use are completely non-portable---you will
  332. probably need to do some experimentation.
  333. </p>
  334. <p>
  335. Sometimes people have suggested that it is necessary to relink the
  336. Tcl interpreter using the C++ compiler to make C++ extension modules work.
  337. In the experience of this author, this has never actually appeared to be
  338. necessary. Relinking the interpreter with C++ really only includes the
  339. special run-time libraries described above---as long as you link your extension
  340. modules with these libraries, it should not be necessary to rebuild Tcl.
  341. </p>
  342. <p>
  343. If you aren't entirely sure about the linking of a C++ extension, you
  344. might look at an existing C++ program. On many Unix machines, the
  345. <tt>ldd</tt> command will list library dependencies. This should give
  346. you some clues about what you might have to include when you link your
  347. extension module. For example:
  348. </p>
  349. <div class="code">
  350. <pre>
  351. $ ldd swig
  352. libstdc++-libc6.1-1.so.2 =&gt; /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
  353. libm.so.6 =&gt; /lib/libm.so.6 (0x4005b000)
  354. libc.so.6 =&gt; /lib/libc.so.6 (0x40077000)
  355. /lib/ld-linux.so.2 =&gt; /lib/ld-linux.so.2 (0x40000000)
  356. $
  357. </pre>
  358. </div>
  359. <p>
  360. As a final complication, a major weakness of C++ is that it does not
  361. define any sort of standard for binary linking of libraries. This
  362. means that C++ code compiled by different compilers will not link
  363. together properly as libraries nor is the memory layout of classes and
  364. data structures implemented in any kind of portable manner. In a
  365. monolithic C++ program, this problem may be unnoticed. However, in Tcl, it
  366. is possible for different extension modules to be compiled with
  367. different C++ compilers. As long as these modules are self-contained,
  368. this probably won't matter. However, if these modules start sharing data,
  369. you will need to take steps to avoid segmentation faults and other
  370. erratic program behavior. If working with lots of software components, you
  371. might want to investigate using a more formal standard such as COM.
  372. </p>
  373. <H3><a name="Tcl_nn8"></a>37.1.6 Compiling for 64-bit platforms</H3>
  374. <p>
  375. On platforms that support 64-bit applications (Solaris, Irix, etc.),
  376. special care is required when building extension modules. On these
  377. machines, 64-bit applications are compiled and linked using a different
  378. set of compiler/linker options. In addition, it is not generally possible to mix
  379. 32-bit and 64-bit code together in the same application.
  380. </p>
  381. <p>
  382. To utilize 64-bits, the Tcl executable will need to be recompiled
  383. as a 64-bit application. In addition, all libraries, wrapper code,
  384. and every other part of your application will need to be compiled for
  385. 64-bits. If you plan to use other third-party extension modules, they
  386. will also have to be recompiled as 64-bit extensions.
  387. </p>
  388. <p>
  389. If you are wrapping commercial software for which you have no source
  390. code, you will be forced to use the same linking standard as used by
  391. that software. This may prevent the use of 64-bit extensions. It may
  392. also introduce problems on platforms that support more than one
  393. linking standard (e.g., -o32 and -n32 on Irix).
  394. </p>
  395. <H3><a name="Tcl_nn9"></a>37.1.7 Setting a package prefix</H3>
  396. <p>
  397. To avoid namespace problems, you can instruct SWIG to append a package
  398. prefix to all of your functions and variables. This is done using the
  399. -prefix option as follows :
  400. </p>
  401. <div class="code"><pre>
  402. swig -tcl -prefix Foo example.i
  403. </pre></div>
  404. <p>
  405. If you have a function "<tt>bar</tt>" in the SWIG file, the prefix
  406. option will append the prefix to the name when creating a command and
  407. call it "<tt>Foo_bar</tt>".
  408. </p>
  409. <H3><a name="Tcl_nn10"></a>37.1.8 Using namespaces</H3>
  410. <p>
  411. Alternatively, you can have SWIG install your module into a Tcl
  412. namespace by specifying the <tt>-namespace</tt> option :
  413. </p>
  414. <div class="code"><pre>
  415. swig -tcl -namespace example.i
  416. </pre></div>
  417. <p>
  418. By default, the name of the namespace will be the same as the module
  419. name, but you can override it using the <tt>-prefix</tt> option.
  420. </p>
  421. <p>
  422. When the<tt> -namespace</tt> option is used, objects in the module
  423. are always accessed with the namespace name such as <tt>Foo::bar</tt>.
  424. </p>
  425. <H2><a name="Tcl_nn11"></a>37.2 Building Tcl/Tk Extensions under Windows 95/NT</H2>
  426. <p>
  427. Building a SWIG extension to Tcl/Tk under Windows 95/NT is roughly
  428. similar to the process used with Unix. Normally, you will want to
  429. produce a DLL that can be loaded into tclsh or wish. This section
  430. covers the process of using SWIG with Microsoft Visual C++.
  431. although the procedure may be similar with other compilers.
  432. </p>
  433. <H3><a name="Tcl_nn12"></a>37.2.1 Running SWIG from Developer Studio</H3>
  434. <p>
  435. If you are developing your application within Microsoft developer
  436. studio, SWIG can be invoked as a custom build option. The process
  437. roughly follows these steps :
  438. </p>
  439. <ul>
  440. <li>Open up a new workspace and use the AppWizard to select a DLL project.
  441. <li>Add both the SWIG interface file (the .i file), any supporting C
  442. files, and the name of the wrapper file that will be created by SWIG
  443. (ie. <tt>example_wrap.c</tt>). Note : If using C++, choose a
  444. different suffix for the wrapper file such as
  445. <tt>example_wrap.cxx</tt>. Don't worry if the wrapper file doesn't
  446. exist yet--Developer studio will keep a reference to it around.
  447. <li>Select the SWIG interface file and go to the settings menu. Under
  448. settings, select the "Custom Build" option.
  449. <li>Enter "SWIG" in the description field.
  450. <li>Enter "<tt>swig -tcl -o $(ProjDir)\$(InputName)_wrap.c
  451. $(InputPath)</tt>" in the "Build command(s) field"
  452. <li>Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>" in the "Output files(s) field".
  453. <li>Next, select the settings for the entire project and go to
  454. "C++:Preprocessor". Add the include directories for your Tcl
  455. installation under "Additional include directories".
  456. <li>Finally, select the settings for the entire project and go to
  457. "Link Options". Add the Tcl library file to your link libraries. For
  458. example "<tt>tcl80.lib</tt>". Also, set the name of the output file
  459. to match the name of your Tcl module (ie. example.dll).
  460. <li>Build your project.
  461. </ul>
  462. <p>
  463. Now, assuming all went well, SWIG will be automatically invoked when
  464. you build your project. Any changes made to the interface file will
  465. result in SWIG being automatically invoked to produce a new version of
  466. the wrapper file. To run your new Tcl extension, simply run
  467. <tt>tclsh</tt> or <tt>wish</tt> and use the <tt>load</tt> command.
  468. For example :
  469. </p>
  470. <div class="code"><pre>
  471. MSDOS &gt; tclsh80
  472. % load example.dll
  473. % fact 4
  474. 24
  475. %
  476. </pre></div>
  477. <H3><a name="Tcl_nn13"></a>37.2.2 Using NMAKE</H3>
  478. <p>
  479. Alternatively, SWIG extensions can be built by writing a Makefile for
  480. NMAKE. To do this, make sure the environment variables for MSVC++ are
  481. available and the MSVC++ tools are in your path. Now, just write a
  482. short Makefile like this :
  483. </p>
  484. <div class="code"><pre>
  485. # Makefile for building various SWIG generated extensions
  486. SRCS = example.c
  487. IFILE = example
  488. INTERFACE = $(IFILE).i
  489. WRAPFILE = $(IFILE)_wrap.c
  490. # Location of the Visual C++ tools (32 bit assumed)
  491. TOOLS = c:\msdev
  492. TARGET = example.dll
  493. CC = $(TOOLS)\bin\cl.exe
  494. LINK = $(TOOLS)\bin\link.exe
  495. INCLUDE32 = -I$(TOOLS)\include
  496. MACHINE = IX86
  497. # C Library needed to build a DLL
  498. DLLIBC = msvcrt.lib oldnames.lib
  499. # Windows libraries that are apparently needed
  500. WINLIB = kernel32.lib advapi32.lib user32.lib gdi32.lib comdlg32.lib
  501. winspool.lib
  502. # Libraries common to all DLLs
  503. LIBS = $(DLLIBC) $(WINLIB)
  504. # Linker options
  505. LOPT = -debug:full -debugtype:cv /NODEFAULTLIB /RELEASE /NOLOGO /
  506. MACHINE:$(MACHINE) -entry:_DllMainCRTStartup@12 -dll
  507. # C compiler flags
  508. CFLAGS = /Z7 /Od /c /nologo
  509. TCL_INCLUDES = -Id:\tcl8.0a2\generic -Id:\tcl8.0a2\win
  510. TCLLIB = d:\tcl8.0a2\win\tcl80.lib
  511. tcl::
  512. ..\..\swig -tcl -o $(WRAPFILE) $(INTERFACE)
  513. $(CC) $(CFLAGS) $(TCL_INCLUDES) $(SRCS) $(WRAPFILE)
  514. set LIB=$(TOOLS)\lib
  515. $(LINK) $(LOPT) -out:example.dll $(LIBS) $(TCLLIB) example.obj example_wrap.obj
  516. </pre></div>
  517. <p>
  518. To build the extension, run NMAKE (you may need to run vcvars32
  519. first). This is a pretty minimal Makefile, but hopefully its enough
  520. to get you started. With a little practice, you'll be making lots of
  521. Tcl extensions.
  522. </p>
  523. <H2><a name="Tcl_nn14"></a>37.3 A tour of basic C/C++ wrapping</H2>
  524. <p>
  525. By default, SWIG tries to build a very natural Tcl interface to your
  526. C/C++ code. Functions are wrapped as functions, classes are wrapped
  527. in an interface that mimics the style of Tk widgets and [incr Tcl]
  528. classes. This section briefly covers the essential aspects of this
  529. wrapping.
  530. </p>
  531. <H3><a name="Tcl_nn15"></a>37.3.1 Modules</H3>
  532. <p>
  533. The SWIG <tt>%module</tt> directive specifies the name of the Tcl
  534. module. If you specify `<tt>%module example</tt>', then everything is
  535. compiled into an extension module <tt>example.so</tt>. When choosing a
  536. module name, make sure you don't use the same name as a built-in
  537. Tcl command.
  538. </p>
  539. <p>
  540. One pitfall to watch out for is module names involving numbers. If
  541. you specify a module name like <tt>%module md5</tt>, you'll find that the
  542. load command no longer seems to work:
  543. </p>
  544. <div class="code">
  545. <pre>
  546. % load ./md5.so
  547. couldn't find procedure Md_Init
  548. </pre>
  549. </div>
  550. <p>
  551. To fix this, supply an extra argument to <tt>load</tt> like this:
  552. </p>
  553. <div class="code">
  554. <pre>
  555. % load ./md5.so md5
  556. </pre>
  557. </div>
  558. <H3><a name="Tcl_nn16"></a>37.3.2 Functions</H3>
  559. <p>
  560. Global functions are wrapped as new Tcl built-in commands. For example,
  561. </p>
  562. <div class="code"><pre>
  563. %module example
  564. int fact(int n);
  565. </pre></div>
  566. <p>
  567. creates a built-in function <tt>fact</tt> that works exactly
  568. like you think it does:
  569. </p>
  570. <div class="code"><pre>
  571. % load ./example.so
  572. % fact 4
  573. 24
  574. % set x [fact 6]
  575. %
  576. </pre></div>
  577. <H3><a name="Tcl_nn17"></a>37.3.3 Global variables</H3>
  578. <p>
  579. C/C++ global variables are wrapped by Tcl global variables. For example:
  580. </p>
  581. <div class="code"><pre>
  582. // SWIG interface file with global variables
  583. %module example
  584. ...
  585. %inline %{
  586. extern double density;
  587. %}
  588. ...
  589. </pre></div>
  590. <p>
  591. Now look at the Tcl interface:
  592. </p>
  593. <div class="code"><pre>
  594. % puts $density # Output value of C global variable
  595. 1.0
  596. % set density 0.95 # Change value
  597. </pre></div>
  598. <p>
  599. If you make an error in variable assignment, you will get an
  600. error message. For example:
  601. </p>
  602. <div class="code"><pre>
  603. % set density "hello"
  604. can't set "density": Type error. expected a double.
  605. %
  606. </pre></div>
  607. <p>
  608. If a variable is declared as <tt>const</tt>, it is wrapped as a
  609. read-only variable. Attempts to modify its value will result in an
  610. error.
  611. </p>
  612. <p>
  613. To make ordinary variables read-only, you can use the <tt>%immutable</tt> directive. For example:
  614. </p>
  615. <div class="code">
  616. <pre>
  617. %{
  618. extern char *path;
  619. %}
  620. %immutable;
  621. extern char *path;
  622. %mutable;
  623. </pre>
  624. </div>
  625. <p>
  626. The <tt>%immutable</tt> directive stays in effect until it is explicitly disabled or cleared using
  627. <tt>%mutable</tt>.
  628. See the <a href="SWIG.html#SWIG_readonly_variables">Creating read-only variables</a> section for further details.
  629. </p>
  630. <p>
  631. If you just want to make a specific variable immutable, supply a declaration name. For example:
  632. </p>
  633. <div class="code">
  634. <pre>
  635. %{
  636. extern char *path;
  637. %}
  638. %immutable path;
  639. ...
  640. extern char *path; // Read-only (due to %immutable)
  641. </pre>
  642. </div>
  643. <H3><a name="Tcl_nn18"></a>37.3.4 Constants and enums</H3>
  644. <p>
  645. C/C++ constants are installed as global Tcl variables containing the
  646. appropriate value. To create a constant, use <tt>#define</tt>, <tt>enum</tt>, or the
  647. <tt>%constant</tt> directive. For example:
  648. </p>
  649. <div class="code">
  650. <pre>
  651. #define PI 3.14159
  652. #define VERSION "1.0"
  653. enum Beverage { ALE, LAGER, STOUT, PILSNER };
  654. %constant int FOO = 42;
  655. %constant const char *path = "/usr/local";
  656. </pre>
  657. </div>
  658. <p>
  659. For enums, make sure that the definition of the enumeration actually appears in a header
  660. file or in the wrapper file somehow---if you just stick an enum in a SWIG interface without
  661. also telling the C compiler about it, the wrapper code won't compile.
  662. </p>
  663. <p>
  664. Note: declarations declared as <tt>const</tt> are wrapped as read-only variables and
  665. will be accessed using the <tt>cvar</tt> object described in the previous section. They
  666. are not wrapped as constants. For further discussion about this, see the <a href="SWIG.html#SWIG">SWIG Basics</a> chapter.
  667. </p>
  668. <p>
  669. Constants are not guaranteed to remain constant in Tcl---the value
  670. of the constant could be accidentally reassigned.You will just have to be careful.
  671. </p>
  672. <p>
  673. A peculiarity of installing constants as variables is that it is necessary to use the Tcl <tt>global</tt> statement to
  674. access constants in procedure bodies. For example:
  675. </p>
  676. <div class="code">
  677. <pre>
  678. proc blah {} {
  679. global FOO
  680. bar $FOO
  681. }
  682. </pre>
  683. </div>
  684. <p>
  685. If a program relies on a lot of constants, this can be extremely annoying. To fix the problem, consider using the
  686. following typemap rule:
  687. </p>
  688. <div class="code">
  689. <pre>
  690. %apply int CONSTANT { int x };
  691. #define FOO 42
  692. ...
  693. void bar(int x);
  694. </pre>
  695. </div>
  696. <p>
  697. When applied to an input argument, the <tt>CONSTANT</tt> rule allows a constant to be passed to a function using
  698. its actual value or a symbolic identifier name. For example:
  699. </p>
  700. <div class="code">
  701. <pre>
  702. proc blah {} {
  703. bar FOO
  704. }
  705. </pre>
  706. </div>
  707. <p>
  708. When an identifier name is given, it is used to perform an implicit hash-table lookup of the value during argument
  709. conversion. This allows the <tt>global</tt> statement to be omitted.
  710. </p>
  711. <H3><a name="Tcl_nn19"></a>37.3.5 Pointers</H3>
  712. <p>
  713. C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with
  714. incomplete type information. Here is a rather simple interface:
  715. </p>
  716. <div class="code">
  717. <pre>
  718. %module example
  719. FILE *fopen(const char *filename, const char *mode);
  720. int fputs(const char *, FILE *);
  721. int fclose(FILE *);
  722. </pre>
  723. </div>
  724. <p>
  725. When wrapped, you will be able to use the functions in a natural way from Tcl.
  726. For example:
  727. </p>
  728. <div class="code">
  729. <pre>
  730. % load ./example.so
  731. % set f [fopen junk w]
  732. % fputs "Hello World\n" $f
  733. % fclose $f
  734. </pre>
  735. </div>
  736. <p>
  737. If this makes you uneasy, rest assured that there is no
  738. deep magic involved. Underneath the covers, pointers to C/C++ objects are
  739. simply represented as opaque values--normally an encoded character
  740. string like this:
  741. </p>
  742. <div class="code"><pre>
  743. % puts $f
  744. _c0671108_p_FILE
  745. %
  746. </pre></div>
  747. <p>
  748. This pointer value can be freely passed around to different C functions that
  749. expect to receive an object of type <tt>FILE *</tt>. The only thing you can't do is
  750. dereference the pointer from Tcl.
  751. </p>
  752. <p>
  753. The NULL pointer is represented by the string <tt>NULL</tt>.
  754. </p>
  755. <p>
  756. As much as you might be inclined to modify a pointer value directly
  757. from Tcl, don't. The hexadecimal encoding is not necessarily the
  758. same as the logical memory address of the underlying object. Instead
  759. it is the raw byte encoding of the pointer value. The encoding will
  760. vary depending on the native byte-ordering of the platform (i.e.,
  761. big-endian vs. little-endian). Similarly, don't try to manually cast
  762. a pointer to a new type by simply replacing the type-string. This
  763. may not work like you expect and it is particularly dangerous when
  764. casting C++ objects. If you need to cast a pointer or
  765. change its value, consider writing some helper functions instead. For
  766. example:
  767. </p>
  768. <div class="code">
  769. <pre>
  770. %inline %{
  771. /* C-style cast */
  772. Bar *FooToBar(Foo *f) {
  773. return (Bar *) f;
  774. }
  775. /* C++-style cast */
  776. Foo *BarToFoo(Bar *b) {
  777. return dynamic_cast&lt;Foo*&gt;(b);
  778. }
  779. Foo *IncrFoo(Foo *f, int i) {
  780. return f+i;
  781. }
  782. %}
  783. </pre>
  784. </div>
  785. <p>
  786. Also, if working with C++, you should always try
  787. to use the new C++ style casts. For example, in the above code, the
  788. C-style cast may return a bogus result whereas as the C++-style cast will return
  789. <tt>None</tt> if the conversion can't be performed.
  790. </p>
  791. <H3><a name="Tcl_nn20"></a>37.3.6 Structures</H3>
  792. <p>
  793. If you wrap a C structure, it is wrapped by a Tcl interface that somewhat resembles a Tk widget.
  794. This provides a very natural interface. For example,
  795. </p>
  796. <div class="code"><pre>
  797. struct Vector {
  798. double x,y,z;
  799. };
  800. </pre></div>
  801. <p>
  802. is used as follows:
  803. </p>
  804. <div class="code"><pre>
  805. % Vector v
  806. % v configure -x 3.5 -y 7.2
  807. % puts "[v cget -x] [v cget -y] [v cget -z]"
  808. 3.5 7.2 0.0
  809. %
  810. </pre></div>
  811. <p>
  812. Similar access is provided for unions and the data members of C++ classes.
  813. </p>
  814. <p>
  815. In the above example, <tt>v</tt> is a name that's used for the object. However,
  816. underneath the covers, there's a pointer to a raw C structure. This can be obtained
  817. by looking at the <tt>-this</tt> attribute. For example:
  818. </p>
  819. <div class="code">
  820. <pre>
  821. % puts [v cget -this]
  822. _88e31408_p_Vector
  823. </pre>
  824. </div>
  825. <p>
  826. Further details about the relationship between the Tcl and the underlying C structure
  827. are covered a little later.
  828. </p>
  829. <p>
  830. <tt>const</tt> members of a structure are read-only. Data members
  831. can also be forced to be read-only using the <tt>%immutable</tt> directive. For example:
  832. </p>
  833. <div class="code">
  834. <pre>
  835. struct Foo {
  836. ...
  837. %immutable;
  838. int x; /* Read-only members */
  839. char *name;
  840. %mutable;
  841. ...
  842. };
  843. </pre>
  844. </div>
  845. <p>
  846. When <tt>char *</tt> members of a structure are wrapped, the contents are assumed to be
  847. dynamically allocated using <tt>malloc</tt> or <tt>new</tt> (depending on whether or not
  848. SWIG is run with the -c++ option). When the structure member is set, the old contents will be
  849. released and a new value created. If this is not the behavior you want, you will have to use
  850. a typemap (described later).
  851. </p>
  852. <p>
  853. If a structure contains arrays, access to those arrays is managed through pointers. For
  854. example, consider this:
  855. </p>
  856. <div class="code">
  857. <pre>
  858. struct Bar {
  859. int x[16];
  860. };
  861. </pre>
  862. </div>
  863. <p>
  864. If accessed in Tcl, you will see behavior like this:
  865. </p>
  866. <div class="code">
  867. <pre>
  868. % Bar b
  869. % puts [b cget -x]
  870. _801861a4_p_int
  871. %
  872. </pre>
  873. </div>
  874. <p>
  875. This pointer can be passed around to functions that expect to receive
  876. an <tt>int *</tt> (just like C). You can also set the value of an array member using
  877. another pointer. For example:
  878. </p>
  879. <div class="code">
  880. <pre>
  881. % Bar c
  882. % c configure -x [b cget -x] # Copy contents of b.x to c.x
  883. </pre>
  884. </div>
  885. <p>
  886. For array assignment, SWIG copies the entire contents of the array starting with the data pointed
  887. to by <tt>b.x</tt>. In this example, 16 integers would be copied. Like C, SWIG makes
  888. no assumptions about bounds checking---if you pass a bad pointer, you may get a segmentation
  889. fault or access violation.
  890. </p>
  891. <p>
  892. When a member of a structure is itself a structure, it is handled as a
  893. pointer. For example, suppose you have two structures like this:
  894. </p>
  895. <div class="code">
  896. <pre>
  897. struct Foo {
  898. int a;
  899. };
  900. struct Bar {
  901. Foo f;
  902. };
  903. </pre>
  904. </div>
  905. <p>
  906. Now, suppose that you access the <tt>f</tt> attribute of <tt>Bar</tt> like this:
  907. </p>
  908. <div class="code">
  909. <pre>
  910. % Bar b
  911. % set x [b cget -f]
  912. </pre>
  913. </div>
  914. <p>
  915. In this case, <tt>x</tt> is a pointer that points to the <tt>Foo</tt> that is inside <tt>b</tt>.
  916. This is the same value as generated by this C code:
  917. </p>
  918. <div class="code">
  919. <pre>
  920. Bar b;
  921. Foo *x = &amp;b-&gt;f; /* Points inside b */
  922. </pre>
  923. </div>
  924. <p>
  925. However, one peculiarity of accessing a substructure like this is that the returned
  926. value does work quite like you might expect. For example:
  927. </p>
  928. <div class="code">
  929. <pre>
  930. % Bar b
  931. % set x [b cget -f]
  932. % x cget -a
  933. invalid command name "x"
  934. </pre>
  935. </div>
  936. <p>
  937. This is because the returned value was not created in a normal way from the interpreter (x is
  938. not a command object). To make it function normally, just
  939. evaluate the variable like this:
  940. </p>
  941. <div class="code">
  942. <pre>
  943. % Bar b
  944. % set x [b cget -f]
  945. % $x cget -a
  946. 0
  947. %
  948. </pre>
  949. </div>
  950. <p>
  951. In this example, <tt>x</tt> points inside the original structure. This means that modifications
  952. work just like you would expect. For example:
  953. </p>
  954. <div class="code">
  955. <pre>
  956. % Bar b
  957. % set x [b cget -f]
  958. % $x configure -a 3 # Modifies contents of f (inside b)
  959. % [b cget -f] -configure -a 3 # Same thing
  960. </pre>
  961. </div>
  962. <p>
  963. In many of these structure examples, a simple name like "v" or "b" has been given
  964. to wrapped structures. If necessary, this name can be passed to functions
  965. that expect to receive an object. For example, if you have a function like this,
  966. </p>
  967. <div class="code">
  968. <pre>
  969. void blah(Foo *f);
  970. </pre>
  971. </div>
  972. <p>
  973. you can call the function in Tcl as follows:
  974. </p>
  975. <div class="code">
  976. <pre>
  977. % Foo x # Create a Foo object
  978. % blah x # Pass the object to a function
  979. </pre>
  980. </div>
  981. <p>
  982. It is also possible to call the function using the raw pointer value. For
  983. instance:
  984. </p>
  985. <div class="code">
  986. <pre>
  987. % blah [x cget -this] # Pass object to a function
  988. </pre>
  989. </div>
  990. <p>
  991. It is also possible to create and use objects using variables. For example:
  992. </p>
  993. <div class="code">
  994. <pre>
  995. % set b [Bar] # Create a Bar
  996. % $b cget -f # Member access
  997. % puts $b
  998. _108fea88_p_Bar
  999. %
  1000. </pre>
  1001. </div>
  1002. <p>
  1003. Finally, to destroy objects created from Tcl, you can either let the object
  1004. name go out of scope or you can explicitly delete the object. For example:
  1005. </p>
  1006. <div class="code">
  1007. <pre>
  1008. % Foo f # Create object f
  1009. % rename f ""
  1010. </pre>
  1011. </div>
  1012. <p>
  1013. or
  1014. </p>
  1015. <div class="code">
  1016. <pre>
  1017. % Foo f # Create object f
  1018. % f -delete
  1019. </pre>
  1020. </div>
  1021. <p>
  1022. Note: Tcl only destroys the underlying object if it has ownership. See the
  1023. memory management section that appears shortly.
  1024. </p>
  1025. <H3><a name="Tcl_nn21"></a>37.3.7 C++ classes</H3>
  1026. <p>
  1027. C++ classes are wrapped as an extension of structure wrapping. For example, if you have this class,
  1028. </p>
  1029. <div class="code"><pre>
  1030. class List {
  1031. public:
  1032. List();
  1033. ~List();
  1034. int search(char *item);
  1035. void insert(char *item);
  1036. void remove(char *item);
  1037. char *get(int n);
  1038. int length;
  1039. };
  1040. </pre></div>
  1041. <p>
  1042. you can use it in Tcl like this:
  1043. </p>
  1044. <div class="code"><pre>
  1045. % List x
  1046. % x insert Ale
  1047. % x insert Stout
  1048. % x insert Lager
  1049. % x get 1
  1050. Stout
  1051. % puts [l cget -length]
  1052. 3
  1053. %
  1054. </pre></div>
  1055. <p>
  1056. Class data members are accessed in the same manner as C structures.
  1057. </p>
  1058. <p>
  1059. Static class members are accessed as global functions or variables.
  1060. To illustrate, suppose you have a class like this:
  1061. </p>
  1062. <div class="code">
  1063. <pre>
  1064. class Spam {
  1065. public:
  1066. static void foo();
  1067. static int bar;
  1068. };
  1069. </pre>
  1070. </div>
  1071. <p>
  1072. In Tcl, the static member is accessed as follows:
  1073. </p>
  1074. <div class="code">
  1075. <pre>
  1076. % Spam_foo # Spam::foo()
  1077. % puts $Spam_bar # Spam::bar
  1078. </pre>
  1079. </div>
  1080. <H3><a name="Tcl_nn22"></a>37.3.8 C++ inheritance</H3>
  1081. <p>
  1082. SWIG is fully aware of issues related to C++ inheritance. Therefore, if you have
  1083. classes like this
  1084. </p>
  1085. <div class="code">
  1086. <pre>
  1087. class Foo {
  1088. ...
  1089. };
  1090. class Bar : public Foo {
  1091. ...
  1092. };
  1093. </pre>
  1094. </div>
  1095. <p>
  1096. An object of type <tt>Bar</tt> can be used where a <tt>Foo</tt> is expected. For
  1097. example, if you have this function:
  1098. </p>
  1099. <div class="code">
  1100. <pre>
  1101. void spam(Foo *f);
  1102. </pre>
  1103. </div>
  1104. <p>
  1105. then the function <tt>spam()</tt> accepts a <tt>Foo *</tt> or a pointer to any class derived from <tt>Foo</tt>.
  1106. For instance:
  1107. </p>
  1108. <div class="code">
  1109. <pre>
  1110. % Foo f # Create a Foo
  1111. % Bar b # Create a Bar
  1112. % spam f # OK
  1113. % spam b # OK
  1114. </pre>
  1115. </div>
  1116. <p>
  1117. It is safe to use multiple inheritance with SWIG.
  1118. </p>
  1119. <H3><a name="Tcl_nn23"></a>37.3.9 Pointers, references, values, and arrays</H3>
  1120. <p>
  1121. In C++, there are many different ways a function might receive
  1122. and manipulate objects. For example:
  1123. </p>
  1124. <div class="code">
  1125. <pre>
  1126. void spam1(Foo *x); // Pass by pointer
  1127. void spam2(Foo &amp;x); // Pass by reference
  1128. void spam3(Foo x); // Pass by value
  1129. void spam4(Foo x[]); // Array of objects
  1130. </pre>
  1131. </div>
  1132. <p>
  1133. In Tcl, there is no detailed distinction like this.
  1134. Because of this, SWIG unifies all of these types
  1135. together in the wrapper code. For instance, if you actually had the
  1136. above functions, it is perfectly legal to do this:
  1137. </p>
  1138. <div class="code">
  1139. <pre>
  1140. % Foo f # Create a Foo
  1141. % spam1 f # Ok. Pointer
  1142. % spam2 f # Ok. Reference
  1143. % spam3 f # Ok. Value.
  1144. % spam4 f # Ok. Array (1 element)
  1145. </pre>
  1146. </div>
  1147. <p>
  1148. Similar behavior occurs for return values. For example, if you had
  1149. functions like this,
  1150. </p>
  1151. <div class="code">
  1152. <pre>
  1153. Foo *spam5();
  1154. Foo &amp;spam6();
  1155. Foo spam7();
  1156. </pre>
  1157. </div>
  1158. <p>
  1159. then all three functions will return a pointer to some <tt>Foo</tt> object.
  1160. Since the third function (spam7) returns a value, newly allocated memory is used
  1161. to hold the result and a pointer is returned (Tcl will release this memory
  1162. when the return value is garbage collected).
  1163. </p>
  1164. <H3><a name="Tcl_nn24"></a>37.3.10 C++ overloaded functions</H3>
  1165. <p>
  1166. C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example,
  1167. if you have two functions like this:
  1168. </p>
  1169. <div class="code">
  1170. <pre>
  1171. void foo(int);
  1172. void foo(char *c);
  1173. </pre>
  1174. </div>
  1175. <p>
  1176. You can use them in Tcl in a straightforward manner:
  1177. </p>
  1178. <div class="code">
  1179. <pre>
  1180. % foo 3 # foo(int)
  1181. % foo Hello # foo(char *c)
  1182. </pre>
  1183. </div>
  1184. <p>
  1185. Similarly, if you have a class like this,
  1186. </p>
  1187. <div class="code">
  1188. <pre>
  1189. class Foo {
  1190. public:
  1191. Foo();
  1192. Foo(const Foo &amp;);
  1193. ...
  1194. };
  1195. </pre>
  1196. </div>
  1197. <p>
  1198. you can write Tcl code like this:
  1199. </p>
  1200. <div class="code">
  1201. <pre>
  1202. % Foo f # Create a Foo
  1203. % Foo g f # Copy f
  1204. </pre>
  1205. </div>
  1206. <p>
  1207. Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG
  1208. can't disambiguate. For example:
  1209. </p>
  1210. <div class="code">
  1211. <pre>
  1212. void spam(int);
  1213. void spam(short);
  1214. </pre>
  1215. </div>
  1216. <p>
  1217. or
  1218. </p>
  1219. <div class="code">
  1220. <pre>
  1221. void foo(Bar *b);
  1222. void foo(Bar &amp;b);
  1223. </pre>
  1224. </div>
  1225. <p>
  1226. If declarations such as these appear, you will get a warning message like this:
  1227. </p>
  1228. <div class="code">
  1229. <pre>
  1230. example.i:12: Warning 509: Overloaded method spam(short) effectively ignored,
  1231. example.i:11: Warning 509: as it is shadowed by spam(int).
  1232. </pre>
  1233. </div>
  1234. <p>
  1235. To fix this, you either need to ignore or rename one of the methods. For example:
  1236. </p>
  1237. <div class="code">
  1238. <pre>
  1239. %rename(spam_short) spam(short);
  1240. ...
  1241. void spam(int);
  1242. void spam(short); // Accessed as spam_short
  1243. </pre>
  1244. </div>
  1245. <p>
  1246. or
  1247. </p>
  1248. <div class="code">
  1249. <pre>
  1250. %ignore spam(short);
  1251. ...
  1252. void spam(int);
  1253. void spam(short); // Ignored
  1254. </pre>
  1255. </div>
  1256. <p>
  1257. SWIG resolves overloaded functions and methods using a disambiguation scheme that ranks and sorts
  1258. declarations according to a set of type-precedence rules. The order in which declarations appear
  1259. in the input does not matter except in situations where ambiguity arises--in this case, the
  1260. first declaration takes precedence.
  1261. </p>
  1262. <p>
  1263. Please refer to the "SWIG and C++" chapter for more information about overloading.
  1264. </p>
  1265. <H3><a name="Tcl_nn25"></a>37.3.11 C++ operators</H3>
  1266. <p>
  1267. Certain C++ overloaded operators can be handled automatically by SWIG. For example,
  1268. consider a class like this:
  1269. </p>
  1270. <div class="code">
  1271. <pre>
  1272. class Complex {
  1273. private:
  1274. double rpart, ipart;
  1275. public:
  1276. Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
  1277. Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
  1278. Complex &amp;operator=(const Complex &amp;c);
  1279. Complex operator+(const Complex &amp;c) const;
  1280. Complex operator-(const Complex &amp;c) const;
  1281. Complex operator*(const Complex &amp;c) const;
  1282. Complex operator-() const;
  1283. double re() const { return rpart; }
  1284. double im() const { return ipart; }
  1285. };
  1286. </pre>
  1287. </div>
  1288. <p>
  1289. When wrapped, it works like this:
  1290. </p>
  1291. <div class="code">
  1292. <pre>
  1293. % Complex c 3 4
  1294. % Complex d 7 8
  1295. % set e [c + d]
  1296. % $e re
  1297. 10.0
  1298. % $e im
  1299. 12.0
  1300. </pre>
  1301. </div>
  1302. <p>
  1303. It should be stressed that operators in SWIG have no relationship to operators
  1304. in Tcl. In fact, the only thing that's happening here is that an operator like
  1305. <tt>operator +</tt> has been renamed to a method <tt>+</tt>. Therefore, the
  1306. statement <tt>[c + d]</tt> is really just invoking the <tt>+</tt> method on <tt>c</tt>.
  1307. When more than operator is defined (with different arguments), the standard
  1308. method overloading facilities are used. Here is a rather odd looking example:
  1309. </p>
  1310. <div class="code">
  1311. <pre>
  1312. % Complex c 3 4
  1313. % Complex d 7 8
  1314. % set e [c - d] # operator-(const Complex &amp;)
  1315. % puts "[$e re] [$e im]"
  1316. 10.0 12.0
  1317. % set f [c -] # operator-()
  1318. % puts "[$f re] [$f im]"
  1319. -3.0 -4.0
  1320. %
  1321. </pre>
  1322. </div>
  1323. <p>
  1324. One restriction with operator overloading support is that SWIG is not
  1325. able to fully handle operators that aren't defined as part of the class.
  1326. For example, if you had code like this
  1327. </p>
  1328. <div class="code">
  1329. <pre>
  1330. class Complex {
  1331. ...
  1332. friend Complex operator+(double, const Complex &amp;c);
  1333. ...
  1334. };
  1335. </pre>
  1336. </div>
  1337. <p>
  1338. then SWIG doesn't know what to do with the friend function--in fact,
  1339. it simply ignores it and issues a warning. You can still wrap the operator,
  1340. but you may have to encapsulate it in a special function. For example:
  1341. </p>
  1342. <div class="code">
  1343. <pre>
  1344. %rename(Complex_add_dc) operator+(double, const Complex &amp;);
  1345. ...
  1346. Complex operator+(double, const Complex &amp;c);
  1347. </pre>
  1348. </div>
  1349. <p>
  1350. There are ways to make this operator appear as part of the class using the <tt>%extend</tt> directive.
  1351. Keep reading.
  1352. </p>
  1353. <H3><a name="Tcl_nn26"></a>37.3.12 C++ namespaces</H3>
  1354. <p>
  1355. SWIG is aware of C++ namespaces, but namespace names do not appear in
  1356. the module nor do namespaces result in a module that is broken up into
  1357. submodules or packages. For example, if you have a file like this,
  1358. </p>
  1359. <div class="code">
  1360. <pre>
  1361. %module example
  1362. namespace foo {
  1363. int fact(int n);
  1364. struct Vector {
  1365. double x,y,z;
  1366. };
  1367. };
  1368. </pre>
  1369. </div>
  1370. <p>
  1371. it works in Tcl as follows:
  1372. </p>
  1373. <div class="code">
  1374. <pre>
  1375. % load ./example.so
  1376. % fact 3
  1377. 6
  1378. % Vector v
  1379. % v configure -x 3.4
  1380. </pre>
  1381. </div>
  1382. <p>
  1383. If your program has more than one namespace, name conflicts (if any) can be resolved using <tt>%rename</tt>
  1384. For example:
  1385. </p>
  1386. <div class="code">
  1387. <pre>
  1388. %rename(Bar_spam) Bar::spam;
  1389. namespace Foo {
  1390. int spam();
  1391. }
  1392. namespace Bar {
  1393. int spam();
  1394. }
  1395. </pre>
  1396. </div>
  1397. <p>
  1398. If you have more than one namespace and your want to keep their
  1399. symbols separate, consider wrapping them as separate SWIG modules.
  1400. For example, make the module name the same as the namespace and create
  1401. extension modules for each namespace separately. If your program
  1402. utilizes thousands of small deeply nested namespaces each with
  1403. identical symbol names, well, then you get what you deserve.
  1404. </p>
  1405. <H3><a name="Tcl_nn27"></a>37.3.13 C++ templates</H3>
  1406. <p>
  1407. C++ templates don't present a huge problem for SWIG. However, in order
  1408. to create wrappers, you have to tell SWIG to create wrappers for a particular
  1409. template instantiation. To do this, you use the <tt>%template</tt> directive.
  1410. For example:
  1411. </p>
  1412. <div class="code">
  1413. <pre>
  1414. %module example
  1415. %{
  1416. #include "pair.h"
  1417. %}
  1418. template&lt;class T1, class T2&gt;
  1419. struct pair {
  1420. typedef T1 first_type;
  1421. typedef T2 second_type;
  1422. T1 first;
  1423. T2 second;
  1424. pair();
  1425. pair(const T1&amp;, const T2&amp;);
  1426. ~pair();
  1427. };
  1428. %template(pairii) pair&lt;int,int&gt;;
  1429. </pre>
  1430. </div>
  1431. <p>
  1432. In Tcl:
  1433. </p>
  1434. <div class="code">
  1435. <pre>
  1436. % pairii p 3 4
  1437. % p cget -first
  1438. 3
  1439. % p cget -second
  1440. 4
  1441. </pre>
  1442. </div>
  1443. <p>
  1444. Obviously, there is more to template wrapping than shown in this example.
  1445. More details can be found in the <a href="SWIGPlus.html#SWIGPlus">SWIG and C++</a> chapter. Some more complicated
  1446. examples will appear later.
  1447. </p>
  1448. <H3><a name="Tcl_nn28"></a>37.3.14 C++ Smart Pointers</H3>
  1449. <p>
  1450. In certain C++ programs, it is common to use classes that have been wrapped by
  1451. so-called "smart pointers." Generally, this involves the use of a template class
  1452. that implements <tt>operator-&gt;()</tt> like this:
  1453. </p>
  1454. <div class="code">
  1455. <pre>
  1456. template&lt;class T&gt; class SmartPtr {
  1457. ...
  1458. T *operator-&gt;();
  1459. ...
  1460. }
  1461. </pre>
  1462. </div>
  1463. <p>
  1464. Then, if you have a class like this,
  1465. </p>
  1466. <div class="code">
  1467. <pre>
  1468. class Foo {
  1469. public:
  1470. int x;
  1471. int bar();
  1472. };
  1473. </pre>
  1474. </div>
  1475. <p>
  1476. A smart pointer would be used in C++ as follows:
  1477. </p>
  1478. <div class="code">
  1479. <pre>
  1480. SmartPtr&lt;Foo&gt; p = CreateFoo(); // Created somehow (not shown)
  1481. ...
  1482. p-&gt;x = 3; // Foo::x
  1483. int y = p-&gt;bar(); // Foo::bar
  1484. </pre>
  1485. </div>
  1486. <p>
  1487. To wrap this in Tcl, simply tell SWIG about the <tt>SmartPtr</tt> class and the low-level
  1488. <tt>Foo</tt> object. Make sure you instantiate <tt>SmartPtr</tt> using <tt>%template</tt> if necessary.
  1489. For example:
  1490. </p>
  1491. <div class="code">
  1492. <pre>
  1493. %module example
  1494. ...
  1495. %template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
  1496. ...
  1497. </pre>
  1498. </div>
  1499. <p>
  1500. Now, in Tcl, everything should just "work":
  1501. </p>
  1502. <div class="code">
  1503. <pre>
  1504. % set p [CreateFoo] # Create a smart-pointer somehow
  1505. % $p configure -x 3 # Foo::x
  1506. % $p bar # Foo::bar
  1507. </pre>
  1508. </div>
  1509. <p>
  1510. If you ever need to access the underlying pointer returned by <tt>operator-&gt;()</tt> itself,
  1511. simply use the <tt>__deref__()</tt> method. For example:
  1512. </p>
  1513. <div class="code">
  1514. <pre>
  1515. % set f [$p __deref__] # Returns underlying Foo *
  1516. </pre>
  1517. </div>
  1518. <H2><a name="Tcl_nn29"></a>37.4 Further details on the Tcl class interface</H2>
  1519. <p>
  1520. In the previous section, a high-level view of Tcl wrapping was
  1521. presented. A key component of this wrapping is that structures and
  1522. classes are wrapped by Tcl class-like objects. This provides a very
  1523. natural Tcl interface and allows SWIG to support a number of
  1524. advanced features such as operator overloading. However, a number
  1525. of low-level details were omitted. This section provides a brief overview
  1526. of how the proxy classes work.
  1527. </p>
  1528. <H3><a name="Tcl_nn30"></a>37.4.1 Proxy classes</H3>
  1529. <p>
  1530. In the <a href="SWIG.html#SWIG">"SWIG basics"</a> and <a href="SWIGPlus.html#SWIGPlus">"SWIG and C++"</a> chapters,
  1531. details of low-level structure and class wrapping are described. To summarize those chapters, if you
  1532. have a class like this
  1533. </p>
  1534. <div class="code">
  1535. <pre>
  1536. class Foo {
  1537. public:
  1538. int x;
  1539. int spam(int);
  1540. ...
  1541. </pre>
  1542. </div>
  1543. <p>
  1544. then SWIG transforms it into a set of low-level procedural wrappers. For example:
  1545. </p>
  1546. <div class="code">
  1547. <pre>
  1548. Foo *new_Foo() {
  1549. return new Foo();
  1550. }
  1551. void delete_Foo(Foo *f) {
  1552. delete f;
  1553. }
  1554. int Foo_x_get(Foo *f) {
  1555. return f-&gt;x;
  1556. }
  1557. void Foo_x_set(Foo *f, int value) {
  1558. f-&gt;x = value;
  1559. }
  1560. int Foo_spam(Foo *f, int arg1) {
  1561. return f-&gt;spam(arg1);
  1562. }
  1563. </pre>
  1564. </div>
  1565. <p>
  1566. These wrappers are actually found in the Tcl extension module. For example, you can certainly do this:
  1567. </p>
  1568. <div class="code">
  1569. <pre>
  1570. % load ./example.so
  1571. % set f [new_Foo]
  1572. % Foo_x_get $f
  1573. 0
  1574. % Foo_spam $f 3
  1575. 1
  1576. %
  1577. </pre>
  1578. </div>
  1579. <p>
  1580. However, in addition to this, the classname <tt>Foo</tt> is used as an object constructor
  1581. function. This allows objects to be encapsulated objects that look a lot like Tk widgets
  1582. as shown in the last section.
  1583. </p>
  1584. <H3><a name="Tcl_nn31"></a>37.4.2 Memory management</H3>
  1585. <p>
  1586. Associated with each wrapped object, is an ownership flag <tt>thisown</tt> The value of this
  1587. flag determines who is responsible for deleting the underlying C++ object. If set to 1,
  1588. the Tcl interpreter destroys the C++ object when the proxy class is
  1589. garbage collected. If set to 0 (or if the attribute is missing), then the destruction
  1590. of the proxy class has no effect on the C++ object.
  1591. </p>
  1592. <p>
  1593. When an object is created by a constructor or returned by value, Tcl automatically takes
  1594. ownership of the result. For example:
  1595. </p>
  1596. <div class="code">
  1597. <pre>
  1598. class Foo {
  1599. public:
  1600. Foo();
  1601. Foo bar();
  1602. };
  1603. </pre>
  1604. </div>
  1605. <p>
  1606. In Tcl:
  1607. </p>
  1608. <div class="code">
  1609. <pre>
  1610. % Foo f
  1611. % f cget -thisown
  1612. 1
  1613. % set g [f bar]
  1614. % $g cget -thisown
  1615. 1
  1616. </pre>
  1617. </div>
  1618. <p>
  1619. On the other hand, when pointers are returned to Tcl, there is often no way to know where
  1620. they came from. Therefore, the ownership is set to zero. For example:
  1621. </p>
  1622. <div class="code">
  1623. <pre>
  1624. class Foo {
  1625. public:
  1626. ...
  1627. Foo *spam();
  1628. ...
  1629. };
  1630. </pre>
  1631. </div>
  1632. <br>
  1633. <div class="code">
  1634. <pre>
  1635. % Foo f
  1636. % set s [f spam]
  1637. % $s cget -thisown
  1638. 0
  1639. %
  1640. </pre>
  1641. </div>
  1642. <p>
  1643. This behavior is especially important for classes that act as
  1644. containers. For example, if a method returns a pointer to an object
  1645. that is contained inside another object, you definitely don't want
  1646. Tcl to assume ownership and destroy it!
  1647. </p>
  1648. <p>
  1649. Related to containers, ownership issues can arise whenever an object is assigned to a member
  1650. or global variable. For example, consider this interface:
  1651. </p>
  1652. <div class="code">
  1653. <pre>
  1654. %module example
  1655. struct Foo {
  1656. int value;
  1657. Foo *next;
  1658. };
  1659. Foo *head = 0;
  1660. </pre>
  1661. </div>
  1662. <p>
  1663. When wrapped in Tcl, careful observation will reveal that ownership changes whenever an object
  1664. is assigned to a global variable. For example:
  1665. </p>
  1666. <div class="code">
  1667. <pre>
  1668. % Foo f
  1669. % f cget -thisown
  1670. 1
  1671. % set head f
  1672. % f cget -thisown
  1673. 0
  1674. </pre>
  1675. </div>
  1676. <p>
  1677. In this case, C is now holding a reference to the object---you probably don't want Tcl to destroy it.
  1678. Similarly, this occurs for members. For example:
  1679. </p>
  1680. <div class="code">
  1681. <pre>
  1682. % Foo f
  1683. % Foo g
  1684. % f cget -thisown
  1685. 1
  1686. % g cget -thisown
  1687. 1
  1688. % f configure -next g
  1689. % g cget -thisown
  1690. 0
  1691. %
  1692. </pre>
  1693. </div>
  1694. <p>
  1695. For the most part, memory management issues remain hidden. However,
  1696. there are occasionally situations where you might have to manually
  1697. change the ownership of an object. For instance, consider code like this:
  1698. </p>
  1699. <div class="code">
  1700. <pre>
  1701. class Node {
  1702. Object *value;
  1703. public:
  1704. void set_value(Object *v) { value = v; }
  1705. ...
  1706. };
  1707. </pre>
  1708. </div>
  1709. <p>
  1710. Now, consider the following Tcl code:
  1711. </p>
  1712. <div class="code">
  1713. <pre>
  1714. % Object v # Create an object
  1715. % Node n # Create a node
  1716. % n setvalue v # Set value
  1717. % v cget -thisown
  1718. 1
  1719. %
  1720. </pre>
  1721. </div>
  1722. <p>
  1723. In this case, the object <tt>n</tt> is holding a reference to
  1724. <tt>v</tt> internally. However, SWIG has no way to know that this
  1725. has occurred. Therefore, Tcl still thinks that it has ownersh…

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