PageRenderTime 68ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/tags/ttn-post-libtool-1-4-3-upgrade/SWIG/Doc/Manual/Tcl.html

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