PageRenderTime 49ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/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

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. </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. </blockquo…

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