Initial commit of OpenSPARC T2 design and verification files.
[OpenSPARC-T2-DV] / tools / src / nas,5.n2.os.2 / lib / python / html / swig / Python.html
CommitLineData
86530b38
AT
1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2<html>
3<head>
4<title>SWIG and Python</title>
5<link rel="stylesheet" type="text/css" href="style.css">
6</head>
7
8<body bgcolor="#ffffff">
9<H1><a name="Python"></a>26 SWIG and Python</H1>
10<!-- INDEX -->
11<div class="sectiontoc">
12<ul>
13<li><a href="#Python_nn2">Overview</a>
14<li><a href="#Python_nn3">Preliminaries</a>
15<ul>
16<li><a href="#Python_nn4">Running SWIG</a>
17<li><a href="#Python_nn5">Getting the right header files</a>
18<li><a href="#Python_nn6">Compiling a dynamic module</a>
19<li><a href="#Python_nn7">Using distutils</a>
20<li><a href="#Python_nn8">Static linking</a>
21<li><a href="#Python_nn9">Using your module</a>
22<li><a href="#Python_nn10">Compilation of C++ extensions</a>
23<li><a href="#Python_nn11">Compiling for 64-bit platforms</a>
24<li><a href="#Python_nn12">Building Python Extensions under Windows</a>
25</ul>
26<li><a href="#Python_nn13">A tour of basic C/C++ wrapping</a>
27<ul>
28<li><a href="#Python_nn14">Modules</a>
29<li><a href="#Python_nn15">Functions</a>
30<li><a href="#Python_nn16">Global variables</a>
31<li><a href="#Python_nn17">Constants and enums</a>
32<li><a href="#Python_nn18">Pointers</a>
33<li><a href="#Python_nn19">Structures</a>
34<li><a href="#Python_nn20">C++ classes</a>
35<li><a href="#Python_nn21">C++ inheritance</a>
36<li><a href="#Python_nn22">Pointers, references, values, and arrays</a>
37<li><a href="#Python_nn23">C++ overloaded functions</a>
38<li><a href="#Python_nn24">C++ operators</a>
39<li><a href="#Python_nn25">C++ namespaces</a>
40<li><a href="#Python_nn26">C++ templates</a>
41<li><a href="#Python_nn27">C++ Smart Pointers</a>
42<li><a href="#Python_nn27a">C++ Reference Counted Objects (ref/unref)</a>
43</ul>
44<li><a href="#Python_nn28">Further details on the Python class interface</a>
45<ul>
46<li><a href="#Python_nn29">Proxy classes</a>
47<li><a href="#Python_nn30">Memory management</a>
48<li><a href="#Python_nn31">Python 2.2 and classic classes</a>
49</ul>
50<li><a href="#directors">Cross language polymorphism</a>
51<ul>
52<li><a href="#Python_nn33">Enabling directors</a>
53<li><a href="#Python_nn34">Director classes</a>
54<li><a href="#Python_nn35">Ownership and object destruction</a>
55<li><a href="#Python_nn36">Exception unrolling</a>
56<li><a href="#Python_nn37">Overhead and code bloat</a>
57<li><a href="#Python_nn38">Typemaps</a>
58<li><a href="#Python_nn39">Miscellaneous</a>
59</ul>
60<li><a href="#Python_nn40">Common customization features</a>
61<ul>
62<li><a href="#Python_nn41">C/C++ helper functions</a>
63<li><a href="#Python_nn42">Adding additional Python code</a>
64<li><a href="#Python_nn43">Class extension with %extend</a>
65<li><a href="#Python_nn44">Exception handling with %exception</a>
66</ul>
67<li><a href="#Python_nn45">Tips and techniques</a>
68<ul>
69<li><a href="#Python_nn46">Input and output parameters</a>
70<li><a href="#Python_nn47">Simple pointers</a>
71<li><a href="#Python_nn48">Unbounded C Arrays</a>
72<li><a href="#Python_nn49">String handling</a>
73<li><a href="#Python_nn50">Arrays</a>
74<li><a href="#Python_nn51">String arrays</a>
75<li><a href="#Python_nn52">STL wrappers</a>
76</ul>
77<li><a href="#Python_nn53">Typemaps</a>
78<ul>
79<li><a href="#Python_nn54">What is a typemap?</a>
80<li><a href="#Python_nn55">Python typemaps</a>
81<li><a href="#Python_nn56">Typemap variables</a>
82<li><a href="#Python_nn57">Useful Python Functions</a>
83</ul>
84<li><a href="#Python_nn58">Typemap Examples</a>
85<ul>
86<li><a href="#Python_nn59">Converting Python list to a char ** </a>
87<li><a href="#Python_nn60">Expanding a Python object into multiple arguments</a>
88<li><a href="#Python_nn61">Using typemaps to return arguments</a>
89<li><a href="#Python_nn62">Mapping Python tuples into small arrays</a>
90<li><a href="#Python_nn63">Mapping sequences to C arrays</a>
91<li><a href="#Python_nn64">Pointer handling</a>
92</ul>
93<li><a href="#Python_nn65">Docstring Features</a>
94<ul>
95<li><a href="#Python_nn66">Module docstring</a>
96<li><a href="#Python_nn67">%feature("autodoc")</a>
97<ul>
98<li><a href="#Python_nn68">%feature("autodoc", "0")</a>
99<li><a href="#Python_nn69">%feature("autodoc", "1")</a>
100<li><a href="#Python_nn70">%feature("autodoc", "docstring")</a>
101</ul>
102<li><a href="#Python_nn71">%feature("docstring")</a>
103</ul>
104<li><a href="#Python_nn72">Python Packages</a>
105</ul>
106</div>
107<!-- INDEX -->
108
109
110
111<p>
112<b>Caution: This chapter is under repair!</b>
113</p>
114
115<p>
116This chapter describes SWIG's support of Python. SWIG is compatible
117with most recent Python versions including Python 2.2 as well as older
118versions dating back to Python 1.5.2. For the best results, consider using Python
1192.0 or newer.
120</p>
121
122<p>
123This chapter covers most SWIG features, but certain low-level details
124are covered in less depth than in earlier chapters. At the
125very least, make sure you read the "<a href="SWIG.html#SWIG">SWIG
126Basics</a>" chapter.
127</p>
128
129<H2><a name="Python_nn2"></a>26.1 Overview</H2>
130
131
132<p>
133To build Python extension modules, SWIG uses a layered approach in which
134parts of the extension module are defined in C and other parts are
135defined in Python. The C layer contains low-level wrappers whereas Python code
136is used to define high-level features.
137</p>
138
139<p>
140This layered approach recognizes the fact that certain aspects of
141extension building are better accomplished in each language (instead
142of trying to do everything in C or C++). Furthermore, by generating code in both
143languages, you get a lot more flexibility since you can enhance the extension
144module with support code in either language.
145</p>
146
147<p>
148In describing the Python interface, this chapter starts by covering the
149basics of configuration, compiling, and installing Python modules.
150Next, the Python interface to common C and C++ programming features is
151described. Advanced customization features such as typemaps are then
152described followed by a discussion of low-level implementation
153details.
154</p>
155
156<H2><a name="Python_nn3"></a>26.2 Preliminaries</H2>
157
158
159<H3><a name="Python_nn4"></a>26.2.1 Running SWIG</H3>
160
161
162<p>
163Suppose that you defined a SWIG module such as the following:
164</p>
165
166<div class="code">
167<pre>
168%module example
169%{
170#include "header.h"
171%}
172int fact(int n);
173</pre>
174</div>
175
176<p>
177To build a Python module, run SWIG using the <tt>-python</tt> option :
178</p>
179
180<div class="shell"><pre>
181$ swig -python example.i
182</pre></div>
183
184<p>
185If building a C++ extension, add the <tt>-c++</tt> option:
186</p>
187
188<div class="shell"><pre>
189$ swig -c++ -python example.i
190</pre></div>
191
192<p>
193This creates two different files; a C/C++ source file <tt>example_wrap.c</tt> or
194<tt>example_wrap.cxx</tt> and a Python source file <tt>example.py</tt>. The generated
195C source file contains the low-level wrappers that need to be compiled and linked with the
196rest of your C/C++ application to create an extension module. The Python source file contains
197high-level support code. This is the file that you will import to use the module.
198</p>
199
200<p>
201The name of the wrapper file is derived from the name of the input file. For example, if the
202input file is <tt>example.i</tt>, the name of the wrapper file is <tt>example_wrap.c</tt>.
203To change this, you can use the <tt>-o</tt> option. The name of the Python file is derived
204from the module name specified with <tt>%module</tt>. If the module name is <tt>example</tt>, then
205a file <tt>example.py</tt> is created.
206</p>
207
208<H3><a name="Python_nn5"></a>26.2.2 Getting the right header files</H3>
209
210
211<p>
212In order to compile the C/C++ wrappers, the compiler needs the <tt>Python.h</tt> header file.
213This file is usually contained in a directory such as
214</p>
215
216<div class="diagram"><pre>
217/usr/local/include/python2.0
218</pre></div>
219
220<p>
221The exact location may vary on your machine, but the above location is
222typical. If you are not entirely sure where Python is installed, you
223can run Python to find out. For example:
224</p>
225
226<div class="targetlang">
227<pre>
228$ python
229Python 2.1.1 (#1, Jul 23 2001, 14:36:06)
230[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
231Type "copyright", "credits" or "license" for more information.
232&gt;&gt;&gt; import sys
233&gt;&gt;&gt; print sys.prefix
234/usr/local
235&gt;&gt;&gt;
236</pre>
237</div>
238
239<H3><a name="Python_nn6"></a>26.2.3 Compiling a dynamic module</H3>
240
241
242<p>
243The preferred approach to building an extension module is to compile it into
244a shared object file or DLL. To do this, you need to compile your program
245using commands like this (shown for Linux):
246</p>
247
248<div class="shell"><pre>
249$ swig -python example.i
250$ gcc -c -fPIC example.c
251$ gcc -c -fPIC example_wrap.c -I/usr/local/include/python2.0
252$ gcc -shared example.o example_wrap.o -o _example.so
253</pre></div>
254
255<p>
256The exact commands for doing this vary from platform to platform.
257However, SWIG tries to guess the right options when it is installed. Therefore,
258you may want to start with one of the examples in the <tt>SWIG/Examples/python</tt>
259directory. If that doesn't work, you will need to read the man-pages for
260your compiler and linker to get the right set of options. You might also
261check the <a href="http://swig.cs.uchicago.edu/cgi-bin/wiki.pl">SWIG Wiki</a> for
262additional information.
263</p>
264
265<p>
266When linking the module, <b>the name of the output file has to match the name
267of the module prefixed by an underscore</b>. If the name of your module is "<tt>example</tt>", then the
268name of the corresponding object file should be
269"<tt>_example.so</tt>" or "<tt>_examplemodule.so</tt>".
270The name of the module is specified using the <tt>%module</tt> directive or the
271<tt> -module</tt> command line option.
272</p>
273
274<p>
275<b>Compatibility Note:</b> In SWIG-1.3.13 and earlier releases, module
276names did not include the leading underscore. This is because modules
277were normally created as C-only extensions without the extra Python
278support file (instead, creating Python code was supported as an optional
279feature). This has been changed in SWIG-1.3.14 and is consistent with
280other Python extension modules. For example, the <tt>socket</tt>
281module actually consists of two files; <tt>socket.py</tt> and
282<tt>_socket.so</tt>. Many other built-in Python modules follow a similar convention.
283</p>
284
285<H3><a name="Python_nn7"></a>26.2.4 Using distutils</H3>
286
287
288<H3><a name="Python_nn8"></a>26.2.5 Static linking</H3>
289
290
291<p>
292An alternative approach to dynamic linking is to rebuild the Python
293interpreter with your extension module added to it. In the past,
294this approach was sometimes necessary due to limitations in dynamic loading
295support on certain machines. However, the situation has improved greatly
296over the last few years and you should not consider this approach
297unless there is really no other option.
298</p>
299
300<p>
301The usual procedure for adding a new module to Python involves finding
302the Python source, adding an entry to the <tt>Modules/Setup</tt> file,
303and rebuilding the interpreter using the Python Makefile. However,
304newer Python versions have changed the build process. You may need to edit
305the 'setup.py' file in the Python distribution instead.
306</p>
307
308<p>
309In earlier versions of SWIG, the <tt>embed.i</tt> library file could be used to
310rebuild the interpreter. For example:
311</p>
312
313<div class="code"><pre>
314%module example
315
316%inline %{
317extern int fact(int);
318extern int mod(int, int);
319extern double My_variable;
320%}
321
322%include embed.i // Include code for a static version of Python
323
324</pre></div>
325
326<p>
327The <tt>embed.i</tt> library file includes supporting code that
328contains everything needed to rebuild Python. To rebuild the interpreter,
329you simply do something like this:
330</p>
331
332<div class="shell"><pre>
333$ swig -python example.i
334$ gcc example.c example_wrap.c \
335 -Xlinker -export-dynamic \
336 -DHAVE_CONFIG_H -I/usr/local/include/python2.1 \
337 -I/usr/local/lib/python2.1/config \
338 -L/usr/local/lib/python2.1/config -lpython2.1 -lm -ldl \
339 -o mypython
340
341</pre></div>
342<p>
343You will need to supply the same libraries that were used to build Python the first
344time. This may include system libraries such as <tt>-lsocket</tt>, <tt>-lnsl</tt>,
345and <tt>-lpthread</tt>. Assuming this actually works, the new version of Python
346should be identical to the default version except that your extension module will be
347a built-in part of the interpreter.
348</p>
349
350<p>
351<b>Comment:</b> In practice, you should probably try to avoid static
352linking if possible. Some programmers may be inclined
353to use static linking in the interest of getting better performance.
354However, the performance gained by static linking tends to be rather
355minimal in most situations (and quite frankly not worth the extra
356hassle in the opinion of this author).
357</p>
358
359<p>
360<b>Compatibility note:</b> The <tt>embed.i</tt> library file is
361deprecated and has not been maintained for several years. Even though it
362appears to "work" with Python 2.1, no future support is guaranteed.
363If using static linking, you might want to rely on a different approach
364(perhaps using distutils).
365</p>
366
367<H3><a name="Python_nn9"></a>26.2.6 Using your module</H3>
368
369
370<p>
371To use your module, simply use the Python <tt>import</tt> statement. If
372all goes well, you will be able to this:
373</p>
374
375<div class="targetlang"><pre>
376$ python
377&gt;&gt;&gt; import example
378&gt;&gt;&gt; example.fact(4)
37924
380&gt;&gt;&gt;
381</pre></div>
382
383<p>
384A common error received by first-time users is the following:
385</p>
386
387<div class="targetlang">
388<pre>
389&gt;&gt;&gt; import example
390Traceback (most recent call last):
391 File "&lt;stdin&gt;", line 1, in ?
392 File "example.py", line 2, in ?
393 import _example
394ImportError: No module named _example
395</pre>
396</div>
397
398<p>
399If you get this message, it means that you either forgot to compile the wrapper
400code into an extension module or you didn't give the extension module the right
401name. Make sure that you compiled the wrappers into a module called <tt>_example.so</tt>. And
402don't forget the leading underscore (_).
403</p>
404
405<p>
406Another possible error is the following:
407</p>
408
409<div class="targetlang">
410<pre>
411&gt;&gt;&gt; import example
412Traceback (most recent call last):
413 File "&lt;stdin&gt;", line 1, in ?
414ImportError: dynamic module does not define init function (init_example)
415&gt;&gt;&gt;
416</pre>
417</div>
418
419<p>
420This error is almost always caused when a bad name is given to the shared object file.
421For example, if you created a file <tt>example.so</tt> instead of <tt>_example.so</tt> you would
422get this error. Alternatively, this error could arise if the name of the module is
423inconsistent with the module name supplied with the <tt>%module</tt> directive.
424Double-check the interface to make sure the module name and the shared object
425filename match. Another possible cause of this error is forgetting to link the SWIG-generated
426wrapper code with the rest of your application when creating the extension module.
427</p>
428
429<p>
430Another common error is something similar to the following:
431</p>
432
433<div class="targetlang">
434<pre>
435Traceback (most recent call last):
436 File "example.py", line 3, in ?
437 import example
438ImportError: ./_example.so: undefined symbol: fact
439</pre>
440</div>
441
442<p>
443This error usually indicates that you forgot to include some object
444files or libraries in the linking of the shared library file. Make
445sure you compile both the SWIG wrapper file and your original program
446into a shared library file. Make sure you pass all of the required libraries
447to the linker.
448</p>
449
450<p>
451Sometimes unresolved symbols occur because a wrapper has been created
452for a function that doesn't actually exist in a library. This usually
453occurs when a header file includes a declaration for a function that
454was never actually implemented or it was removed from a library
455without updating the header file. To fix this, you can either edit
456the SWIG input file to remove the offending declaration or you can use
457the <tt>%ignore</tt> directive to ignore the declaration.
458</p>
459
460<p>
461Finally, suppose that your extension module is linked with another library like this:
462</p>
463
464<div class="shell">
465<pre>
466$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib <b>-lfoo</b> \
467 -o _example.so
468</pre>
469</div>
470
471<p>
472If the <tt>foo</tt> library is compiled as a shared library, you might encounter the following
473problem when you try to use your module:
474</p>
475
476<div class="targetlang">
477<pre>
478&gt;&gt;&gt; import example
479Traceback (most recent call last):
480 File "&lt;stdin&gt;", line 1, in ?
481ImportError: libfoo.so: cannot open shared object file: No such file or directory
482&gt;&gt;&gt;
483</pre>
484</div>
485
486<p>
487This error is generated because the dynamic linker can't locate the
488<tt>libfoo.so</tt> library. When shared libraries are loaded, the
489system normally only checks a few standard locations such as
490<tt>/usr/lib</tt> and <tt>/usr/local/lib</tt>. To fix this problem,
491there are several things you can do. First, you can recompile your extension
492module with extra path information. For example, on Linux you can do this:
493</p>
494
495<div class="shell">
496<pre>
497$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
498 <b>-Xlinker -rpath /home/beazley/projects/lib </b> \
499 -o _example.so
500</pre>
501</div>
502
503<p>
504Alternatively, you can set the <tt>LD_LIBRARY_PATH</tt> environment variable to
505include the directory with your shared libraries.
506If setting <tt>LD_LIBRARY_PATH</tt>, be aware that setting this variable can introduce
507a noticeable performance impact on all other applications that you run.
508To set it only for Python, you might want to do this instead:
509</p>
510
511<div class="shell">
512<pre>
513$ env LD_LIBRARY_PATH=/home/beazley/projects/lib python
514</pre>
515</div>
516
517<p>
518Finally, you can use a command such as <tt>ldconfig</tt> (Linux) or
519<tt>crle</tt> (Solaris) to add additional search paths to the default
520system configuration (this requires root access and you will need to
521read the man pages).
522</p>
523
524<H3><a name="Python_nn10"></a>26.2.7 Compilation of C++ extensions</H3>
525
526
527<p>
528Compilation of C++ extensions has traditionally been a tricky problem.
529Since the Python interpreter is written in C, you need to take steps to
530make sure C++ is properly initialized and that modules are compiled
531correctly.
532</p>
533
534<p>
535On most machines, C++ extension modules should be linked using the C++
536compiler. For example:
537</p>
538
539<div class="shell"><pre>
540$ swig -c++ -python example.i
541$ g++ -c example.cxx
542$ g++ -c example_wrap.cxx -I/usr/local/include/python2.0
543$ g++ -shared example.o example_wrap.o -o _example.so
544</pre></div>
545
546<p>
547On some platforms, you could also need to generate
548position-independent code (PIC), by using a compiler option such as -fPIC.
549Notably, the x86_64 (Opteron and EM64T) platform requires it, and when
550using the GNU Compiler Suite, you will need to modify the previous example
551as follows:
552</p>
553
554<div class="shell"><pre>
555$ swig -c++ -python example.i
556$ g++ -fPIC -c example.cxx
557$ g++ -fPIC -c example_wrap.cxx -I/usr/local/include/python2.0
558$ g++ -shared example.o example_wrap.o -o _example.so
559</pre></div>
560
561<p>
562In addition to this, you may need to include additional library
563files to make it work. For example, if you are using the Sun C++ compiler on
564Solaris, you often need to add an extra library <tt>-lCrun</tt> like this:
565</p>
566
567<div class="shell"><pre>
568$ swig -c++ -python example.i
569$ CC -c example.cxx
570$ CC -c example_wrap.cxx -I/usr/local/include/python2.0
571$ CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o _example.so -lCrun
572</pre></div>
573
574<p>
575Of course, the extra libraries to use are completely non-portable---you will
576probably need to do some experimentation.
577</p>
578
579<p>
580Sometimes people have suggested that it is necessary to relink the
581Python interpreter using the C++ compiler to make C++ extension modules work.
582In the experience of this author, this has never actually appeared to be
583necessary. Relinking the interpreter with C++ really only includes the
584special run-time libraries described above---as long as you link your extension
585modules with these libraries, it should not be necessary to rebuild Python.
586</p>
587
588<p>
589If you aren't entirely sure about the linking of a C++ extension, you
590might look at an existing C++ program. On many Unix machines, the
591<tt>ldd</tt> command will list library dependencies. This should give
592you some clues about what you might have to include when you link your
593extension module. For example:
594</p>
595
596<div class="shell">
597<pre>
598$ ldd swig
599 libstdc++-libc6.1-1.so.2 =&gt; /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
600 libm.so.6 =&gt; /lib/libm.so.6 (0x4005b000)
601 libc.so.6 =&gt; /lib/libc.so.6 (0x40077000)
602 /lib/ld-linux.so.2 =&gt; /lib/ld-linux.so.2 (0x40000000)
603</pre>
604</div>
605
606<p>
607As a final complication, a major weakness of C++ is that it does not
608define any sort of standard for binary linking of libraries. This
609means that C++ code compiled by different compilers will not link
610together properly as libraries nor is the memory layout of classes and
611data structures implemented in any kind of portable manner. In a
612monolithic C++ program, this problem may be unnoticed. However, in Python, it
613is possible for different extension modules to be compiled with
614different C++ compilers. As long as these modules are self-contained,
615this probably won't matter. However, if these modules start sharing data,
616you will need to take steps to avoid segmentation faults and other
617erratic program behavior. If working with lots of software components, you
618might want to investigate using a more formal standard such as COM.
619</p>
620
621<H3><a name="Python_nn11"></a>26.2.8 Compiling for 64-bit platforms</H3>
622
623
624<p>
625On platforms that support 64-bit applications (Solaris, Irix, etc.),
626special care is required when building extension modules. On these
627machines, 64-bit applications are compiled and linked using a different
628set of compiler/linker options. In addition, it is not generally possible to mix
62932-bit and 64-bit code together in the same application.
630</p>
631
632<p>
633To utilize 64-bits, the Python executable will need to be recompiled
634as a 64-bit application. In addition, all libraries, wrapper code,
635and every other part of your application will need to be compiled for
63664-bits. If you plan to use other third-party extension modules, they
637will also have to be recompiled as 64-bit extensions.
638</p>
639
640<p>
641If you are wrapping commercial software for which you have no source
642code, you will be forced to use the same linking standard as used by
643that software. This may prevent the use of 64-bit extensions. It may
644also introduce problems on platforms that support more than one
645linking standard (e.g., -o32 and -n32 on Irix).
646</p>
647
648<p> On the Linux x86_64 platform (Opteron or EM64T), besides of the
649required compiler option -fPIC discussed above, you will need to be
650careful about the libraries you link with or the library path you
651use. In general, a Linux distribution will have two set of libraries,
652one for native x86_64 programs (under /usr/lib64), and another for 32
653bits compatibility (under /usr/lib). Also, the compiler options -m32
654and -m64 allow you to choose the desired binary format for your python
655extension.
656</p>
657
658<H3><a name="Python_nn12"></a>26.2.9 Building Python Extensions under Windows</H3>
659
660
661<p>
662Building a SWIG extension to Python under Windows is roughly
663similar to the process used with Unix. You will need to create a
664DLL that can be loaded into the interpreter. This section briefly
665describes the use of SWIG with Microsoft Visual C++. As a starting
666point, many of SWIG's examples include project files. You might want to
667take a quick look at these in addition to reading this section.
668</p>
669
670<p>
671In Developer Studio, SWIG should be invoked as a custom build option.
672This is usually done as follows:
673</p>
674
675<ul>
676<li>Open up a new workspace and use the AppWizard to select a DLL
677project.
678
679<li>Add both the SWIG interface file (the .i file), any supporting C
680files, and the name of the wrapper file that will be created by SWIG
681(ie. <tt>example_wrap.c</tt>). Note : If using C++, choose a
682different suffix for the wrapper file such as
683<tt>example_wrap.cxx</tt>. Don't worry if the wrapper file doesn't
684exist yet--Developer Studio keeps a reference to it.
685
686<li>Select the SWIG interface file and go to the settings menu. Under
687settings, select the "Custom Build" option.
688
689<li>Enter "SWIG" in the description field.
690
691<li>Enter "<tt>swig -python -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)</tt>" in the "Build command(s) field"
692
693<li>Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>" in the "Output files(s) field".
694
695<li>Next, select the settings for the entire project and go to
696"C++:Preprocessor". Add the include directories for your Python
697installation under "Additional include directories".
698
699<li>Define the symbol __WIN32__ under preprocessor options.
700
701<li>Finally, select the settings for the entire project and go to
702"Link Options". Add the Python library file to your link libraries.
703For example "python21.lib". Also, set the name of the output file to
704match the name of your Python module (ie. _example.dll).
705
706<li>Build your project.
707</ul>
708
709<p>
710If all went well, SWIG will be automatically invoked whenever
711you build your project. Any changes made to the interface file will
712result in SWIG being automatically executed to produce a new version of
713the wrapper file.
714</p>
715
716<p>
717To run your new Python extension, simply run Python
718and use the <tt>import</tt> command as normal. For example :
719</p>
720
721<div class="targetlang"><pre>
722$ python
723&gt;&gt;&gt; import example
724&gt;&gt;&gt; print example.fact(4)
72524
726&gt;&gt;&gt;
727</pre></div>
728
729<p>
730If you get an <tt>ImportError</tt> exception when importing the module, you may
731have forgotten to include aditional library files when you built your module.
732If you get an access violation or some kind of general protection fault
733immediately upon import, you have a more serious problem. This
734is often caused by linking your extension module against the wrong
735set of Win32 debug or thread libraries. You will have to fiddle around with
736the build options of project to try and track this down.
737</p>
738
739<p>
740Some users have reported success in building extension modules using Cygwin
741and other compilers. However, the problem of building usable DLLs with these
742compilers tends to be rather problematic. For the latest information,
743you may want to consult the <a href="http://swig.cs.uchicago.edu/cgi-bin/wiki.pl">
744SWIG Wiki</a>.
745</p>
746
747<H2><a name="Python_nn13"></a>26.3 A tour of basic C/C++ wrapping</H2>
748
749
750<p>
751By default, SWIG tries to build a very natural Python interface
752to your C/C++ code. Functions are wrapped as functions, classes are wrapped as classes, and so forth.
753This section briefly covers the essential aspects of this wrapping.
754</p>
755
756<H3><a name="Python_nn14"></a>26.3.1 Modules</H3>
757
758
759<p>
760The SWIG <tt>%module</tt> directive specifies the name of the Python
761module. If you specify `<tt>%module example</tt>', then everything is
762wrapped into a Python '<tt>example</tt>' module. Underneath the covers,
763this module consists of a Python source file <tt>example.py</tt> and a low-level
764extension module <tt>_example.so</tt>. When choosing a
765module name, make sure you don't use the same name as a built-in
766Python command or standard module name.
767</p>
768
769<H3><a name="Python_nn15"></a>26.3.2 Functions</H3>
770
771
772<p>
773Global functions are wrapped as new Python built-in functions. For example,
774</p>
775
776<div class="code"><pre>
777%module example
778int fact(int n);
779</pre></div>
780
781<p>
782creates a built-in function <tt>example.fact(n)</tt> that works exactly
783like you think it does:
784</p>
785
786<div class="targetlang"><pre>
787&gt;&gt;&gt; import example
788&gt;&gt;&gt; print example.fact(4)
78924
790&gt;&gt;&gt;
791</pre></div>
792
793<H3><a name="Python_nn16"></a>26.3.3 Global variables</H3>
794
795
796<p>
797C/C++ global variables are fully supported by SWIG. However, the underlying
798mechanism is somewhat different than you might expect due to the way that
799Python assignment works. When you type the following in Python
800</p>
801
802<div class="targetlang"><pre>
803a = 3.4
804</pre></div>
805
806<p>
807"a" becomes a name for an object containing the value 3.4. If you later type
808</p>
809
810<div class="targetlang"><pre>
811b = a
812</pre></div>
813
814<p>
815then "a" and "b" are both names for the object containing the value
8163.4. Thus, there is only one object containing 3.4 and "a"
817and "b" are both names that refer to it. This is quite
818different than C where a variable name refers to a memory location in which
819a value is stored (and assignment copies data into that location).
820Because of this, there is no direct way to map variable
821assignment in C to variable assignment in Python.
822</p>
823
824<p>
825To provide access to C global variables, SWIG creates a special
826object called `<tt>cvar</tt>' that is added to each SWIG generated
827module. Global variables are then accessed as attributes of this object.
828For example, consider this interface
829</p>
830
831<div class="code"><pre>
832// SWIG interface file with global variables
833%module example
834...
835%inline %{
836extern int My_variable;
837extern double density;
838%}
839...
840</pre></div>
841<p>
842Now look at the Python interface:
843</p>
844
845<div class="targetlang"><pre>
846&gt;&gt;&gt; import example
847&gt;&gt;&gt; # Print out value of a C global variable
848&gt;&gt;&gt; print example.cvar.My_variable
8494
850&gt;&gt;&gt; # Set the value of a C global variable
851&gt;&gt;&gt; example.cvar.density = 0.8442
852&gt;&gt;&gt; # Use in a math operation
853&gt;&gt;&gt; example.cvar.density = example.cvar.density*1.10
854</pre></div>
855
856<p>
857If you make an error in variable assignment, you will receive an
858error message. For example:
859</p>
860
861<div class="targetlang"><pre>
862&gt;&gt;&gt; example.cvar.density = "Hello"
863Traceback (most recent call last):
864 File "&lt;stdin&gt;", line 1, in ?
865TypeError: C variable 'density (double )'
866&gt;&gt;&gt;
867</pre></div>
868
869<p>
870If a variable is declared as <tt>const</tt>, it is wrapped as a
871read-only variable. Attempts to modify its value will result in an
872error.
873</p>
874
875<p>
876To make ordinary variables read-only, you can use the <tt>%immutable</tt> directive. For example:
877</p>
878
879<div class="code">
880<pre>
881%{
882extern char *path;
883%}
884%immutable;
885extern char *path;
886%mutable;
887</pre>
888</div>
889
890<p>
891The <tt>%immutable</tt> directive stays in effect until it is explicitly disabled or cleared using
892<tt>%mutable</tt>.
893See the <a href="SWIG.html#SWIG_readonly_variables">Creatng read-only variables</a> section for further details.
894</p>
895
896<p>
897If you just want to make a specific variable immutable, supply a declaration name. For example:
898</p>
899
900<div class="code">
901<pre>
902%{
903extern char *path;
904%}
905%immutable path;
906...
907extern char *path; // Read-only (due to %immutable)
908</pre>
909</div>
910
911<p>
912If you would like to access variables using a name other than "<tt>cvar</tt>", it can be
913changed using the <tt>-globals</tt> option :
914</p>
915
916<div class="shell"><pre>
917$ swig -python -globals myvar example.i
918</pre></div>
919
920<p>
921Some care is in order when importing multiple SWIG modules.
922If you use the "<tt>from &lt;file&gt; import *</tt>" style of
923importing, you will get a name clash on the variable `<tt>cvar</tt>'
924and you will only be able to access global variables from the last
925module loaded. To prevent this, you might consider renaming
926<tt>cvar</tt> or making it private to the module by giving it a name
927that starts with a leading underscore. SWIG does not create <tt>cvar</tt>
928if there are no global variables in a module.
929</p>
930
931<H3><a name="Python_nn17"></a>26.3.4 Constants and enums</H3>
932
933
934<p>
935C/C++ constants are installed as Python objects containing the
936appropriate value. To create a constant, use <tt>#define</tt>, <tt>enum</tt>, or the
937<tt>%constant</tt> directive. For example:
938</p>
939
940<div class="code">
941<pre>
942#define PI 3.14159
943#define VERSION "1.0"
944
945enum Beverage { ALE, LAGER, STOUT, PILSNER };
946
947%constant int FOO = 42;
948%constant const char *path = "/usr/local";
949</pre>
950</div>
951
952<p>
953For enums, make sure that the definition of the enumeration actually appears in a header
954file or in the wrapper file somehow---if you just stick an enum in a SWIG interface without
955also telling the C compiler about it, the wrapper code won't compile.
956</p>
957
958<p>
959Note: declarations declared as <tt>const</tt> are wrapped as read-only variables and
960will be accessed using the <tt>cvar</tt> object described in the previous section. They
961are not wrapped as constants. For further discussion about this, see the <a href="SWIG.html#SWIG">SWIG Basics</a> chapter.
962</p>
963
964<p>
965Constants are not guaranteed to remain constant in Python---the name
966of the constant could be accidentally reassigned to refer to some
967other object. Unfortunately, there is no easy way for SWIG to
968generate code that prevents this. You will just have to be careful.
969</p>
970
971<H3><a name="Python_nn18"></a>26.3.5 Pointers</H3>
972
973
974<p>
975C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no
976problem working with incomplete type information. Here is a rather
977simple interface:
978</p>
979
980<div class="code">
981<pre>
982%module example
983
984FILE *fopen(const char *filename, const char *mode);
985int fputs(const char *, FILE *);
986int fclose(FILE *);
987</pre>
988</div>
989
990<p>
991When wrapped, you will be able to use the functions in a natural way from Python. For example:
992</p>
993
994<div class="targetlang">
995<pre>
996&gt;&gt;&gt; import example
997&gt;&gt;&gt; f = example.fopen("junk","w")
998&gt;&gt;&gt; example.fputs("Hello World\n", f)
999&gt;&gt;&gt; example.fclose(f)
1000</pre>
1001</div>
1002
1003<p>
1004If this makes you uneasy, rest assured that there is no
1005deep magic involved. Underneath the covers, pointers to C/C++ objects are
1006simply represented as opaque values using an especial python container object:
1007</p>
1008
1009<div class="targetlang"><pre>
1010&gt;&gt;&gt; print f
1011&lt;Swig Object at _08a71808_p_FILE&gt;
1012</pre></div>
1013
1014<p>
1015This pointer value can be freely passed around to different C functions that
1016expect to receive an object of type <tt>FILE *</tt>. The only thing you can't do is
1017dereference the pointer from Python. Of course, that isn't much of a concern in this example.
1018</p>
1019
1020<p>
1021In older versions of Swig (1.3.22 or older), pointers were represented
1022using a plain string object. If you have an old package that still
1023requires that representation, or you just feel nostalgic, you can
1024always retreive it by casting the pointer object to a string:
1025</p>
1026
1027<div class="targetlang"><pre>
1028&gt;&gt;&gt; print str(f)
1029_c0671108_p_FILE
1030</pre></div>
1031
1032<p>
1033Also, if you need to pass the raw pointer value to some external
1034python library, you can do it by casting the pointer object to an
1035integer:
1036</p>
1037
1038<div class="targetlang"><pre>
1039&gt;&gt;&gt; print int(f)
1040135833352
1041</pre></div>
1042
1043<p>
1044However, the inverse operation is not possible, i.e., you can't build
1045a Swig pointer object from a raw integer value.
1046</p>
1047
1048<p>
1049Note also that the '0' or NULL pointer is always represented by
1050<tt>None</tt>, no matter what type swig is addressing. In the
1051previous example, you can call:
1052</p>
1053
1054<div class="targetlang">
1055<pre>
1056&gt;&gt;&gt; example.fclose(None)
1057</pre>
1058</div>
1059
1060<p>
1061and that will be equivalent to the following, but not really useful, C
1062code:
1063</p>
1064
1065<div class="code">
1066<pre>
1067FILE *f = NULL;
1068fclose(f);
1069</pre>
1070</div>
1071
1072<p>
1073As much as you might be inclined to modify a pointer value directly
1074from Python, don't. The hexadecimal encoding is not necessarily the
1075same as the logical memory address of the underlying object. Instead
1076it is the raw byte encoding of the pointer value. The encoding will
1077vary depending on the native byte-ordering of the platform (i.e.,
1078big-endian vs. little-endian). Similarly, don't try to manually cast
1079a pointer to a new type by simply replacing the type-string. This may
1080not work like you expect, it is particularly dangerous when casting
1081C++ objects. If you need to cast a pointer or change its value,
1082consider writing some helper functions instead. For example:
1083</p>
1084
1085<div class="code">
1086<pre>
1087%inline %{
1088/* C-style cast */
1089Bar *FooToBar(Foo *f) {
1090 return (Bar *) f;
1091}
1092
1093/* C++-style cast */
1094Foo *BarToFoo(Bar *b) {
1095 return dynamic_cast&lt;Foo*&gt;(b);
1096}
1097
1098Foo *IncrFoo(Foo *f, int i) {
1099 return f+i;
1100}
1101%}
1102</pre>
1103</div>
1104
1105<p>
1106Also, if working with C++, you should always try
1107to use the new C++ style casts. For example, in the above code, the
1108C-style cast may return a bogus result whereas as the C++-style cast will return
1109<tt>None</tt> if the conversion can't be performed.
1110</p>
1111
1112<H3><a name="Python_nn19"></a>26.3.6 Structures</H3>
1113
1114
1115<p>
1116If you wrap a C structure, it is wrapped by a Python class. This provides
1117a very natural interface. For example,
1118</p>
1119
1120<div class="code"><pre>
1121struct Vector {
1122 double x,y,z;
1123};
1124
1125</pre></div>
1126
1127<p>
1128is used as follows:
1129</p>
1130
1131<div class="targetlang"><pre>
1132&gt;&gt;&gt; v = example.Vector()
1133&gt;&gt;&gt; v.x = 3.5
1134&gt;&gt;&gt; v.y = 7.2
1135&gt;&gt;&gt; print v.x, v.y, v.z
11367.8 -4.5 0.0
1137&gt;&gt;&gt;
1138</pre></div>
1139
1140<p>
1141Similar access is provided for unions and the data members of C++ classes.
1142</p>
1143
1144<p>
1145If you print out the value of <tt>v</tt> in the above example, you will see
1146something like this:
1147</p>
1148
1149<div class="targetlang">
1150<pre>
1151&gt;&gt;&gt; print v
1152&lt;C Vector instance at _18e31408_p_Vector&gt;
1153</pre>
1154</div>
1155
1156<p>
1157This object is actually a Python instance that has been wrapped around a pointer to the low-level
1158C structure. This instance doesn't actually do anything--it just serves as a proxy.
1159The pointer to the C object can be found in the the <tt>.this</tt>
1160attribute. For example:
1161</p>
1162
1163<div class="targetlang">
1164<pre>
1165&gt;&gt;&gt; print v.this
1166_18e31408_p_Vector
1167&gt;&gt;&gt;
1168</pre>
1169</div>
1170
1171<p>
1172Further details about the Python proxy class are covered a little later.
1173</p>
1174
1175<p>
1176<tt>const</tt> members of a structure are read-only. Data members
1177can also be forced to be read-only using the <tt>%immutable</tt> directive. For example:
1178</p>
1179
1180<div class="code">
1181<pre>
1182struct Foo {
1183 ...
1184 %immutable;
1185 int x; /* Read-only members */
1186 char *name;
1187 %mutable;
1188 ...
1189};
1190</pre>
1191</div>
1192
1193<p>
1194When <tt>char *</tt> members of a structure are wrapped, the contents are assumed to be
1195dynamically allocated using <tt>malloc</tt> or <tt>new</tt> (depending on whether or not
1196SWIG is run with the -c++ option). When the structure member is set, the old contents will be
1197released and a new value created. If this is not the behavior you want, you will have to use
1198a typemap (described later).
1199</p>
1200
1201<p>
1202If a structure contains arrays, access to those arrays is managed through pointers. For
1203example, consider this:
1204</p>
1205
1206<div class="code">
1207<pre>
1208struct Bar {
1209 int x[16];
1210};
1211</pre>
1212</div>
1213
1214<p>
1215If accessed in Python, you will see behavior like this:
1216</p>
1217
1218<div class="targetlang">
1219<pre>
1220&gt;&gt;&gt; b = example.Bar()
1221&gt;&gt;&gt; print b.x
1222_801861a4_p_int
1223&gt;&gt;&gt;
1224</pre>
1225</div>
1226
1227<p>
1228This pointer can be passed around to functions that expect to receive
1229an <tt>int *</tt> (just like C). You can also set the value of an array member using
1230another pointer. For example:
1231</p>
1232
1233<div class="targetlang">
1234<pre>
1235&gt;&gt;&gt; c = example.Bar()
1236&gt;&gt;&gt; c.x = b.x # Copy contents of b.x to c.x
1237</pre>
1238</div>
1239
1240<p>
1241For array assignment, SWIG copies the entire contents of the array starting with the data pointed
1242to by <tt>b.x</tt>. In this example, 16 integers would be copied. Like C, SWIG makes
1243no assumptions about bounds checking---if you pass a bad pointer, you may get a segmentation
1244fault or access violation.
1245</p>
1246
1247<p>
1248When a member of a structure is itself a structure, it is handled as a
1249pointer. For example, suppose you have two structures like this:
1250</p>
1251
1252<div class="code">
1253<pre>
1254struct Foo {
1255 int a;
1256};
1257
1258struct Bar {
1259 Foo f;
1260};
1261</pre>
1262</div>
1263
1264<p>
1265Now, suppose that you access the <tt>f</tt> attribute of <tt>Bar</tt> like this:
1266</p>
1267
1268<div class="targetlang">
1269<pre>
1270&gt;&gt;&gt; b = Bar()
1271&gt;&gt;&gt; x = b.f
1272</pre>
1273</div>
1274
1275<p>
1276In this case, <tt>x</tt> is a pointer that points to the <tt>Foo</tt> that is inside <tt>b</tt>.
1277This is the same value as generated by this C code:
1278</p>
1279
1280<div class="code">
1281<pre>
1282Bar b;
1283Foo *x = &amp;b-&gt;f; /* Points inside b */
1284</pre>
1285</div>
1286
1287<p>
1288Because the pointer points inside the structure, you can modify the contents and
1289everything works just like you would expect. For example:
1290</p>
1291
1292<div class="targetlang">
1293<pre>
1294&gt;&gt;&gt; b = Bar()
1295&gt;&gt;&gt; b.f.a = 3 # Modify attribute of structure member
1296&gt;&gt;&gt; x = b.f
1297&gt;&gt;&gt; x.a = 3 # Modifies the same structure
1298</pre>
1299</div>
1300
1301<H3><a name="Python_nn20"></a>26.3.7 C++ classes</H3>
1302
1303
1304<p>
1305C++ classes are wrapped by Python classes as well. For example, if you have this class,
1306</p>
1307
1308<div class="code"><pre>
1309class List {
1310public:
1311 List();
1312 ~List();
1313 int search(char *item);
1314 void insert(char *item);
1315 void remove(char *item);
1316 char *get(int n);
1317 int length;
1318};
1319</pre></div>
1320
1321<p>
1322you can use it in Python like this:
1323</p>
1324
1325<div class="targetlang"><pre>
1326&gt;&gt;&gt; l = example.List()
1327&gt;&gt;&gt; l.insert("Ale")
1328&gt;&gt;&gt; l.insert("Stout")
1329&gt;&gt;&gt; l.insert("Lager")
1330&gt;&gt;&gt; l.get(1)
1331'Stout'
1332&gt;&gt;&gt; print l.length
13333
1334&gt;&gt;&gt;
1335</pre></div>
1336
1337<p>
1338Class data members are accessed in the same manner as C structures.
1339</p>
1340
1341<p>
1342Static class members present a special problem for Python. Prior to Python-2.2,
1343Python classes had no support for static methods and no version of Python
1344supports static member variables in a manner that SWIG can utilize. Therefore,
1345SWIG generates wrappers that try to work around some of these issues. To illustrate,
1346suppose you have a class like this:
1347</p>
1348
1349<div class="code">
1350<pre>
1351class Spam {
1352public:
1353 static void foo();
1354 static int bar;
1355
1356};
1357</pre>
1358</div>
1359
1360<p>
1361In Python, the static member can be access in three different ways:
1362</p>
1363
1364<div class="targetlang">
1365<pre>
1366&gt;&gt;&gt; example.Spam_foo() # Spam::foo()
1367&gt;&gt;&gt; s = example.Spam()
1368&gt;&gt;&gt; s.foo() # Spam::foo() via an instance
1369&gt;&gt;&gt; example.Spam.foo() # Spam::foo(). Python-2.2 only
1370</pre>
1371</div>
1372
1373<p>
1374The first two methods of access are supported in all versions of Python. The
1375last technique is only available in Python-2.2 and later versions.
1376</p>
1377
1378<p>
1379Static member variables are currently accessed as global variables. This means,
1380they are accessed through <tt>cvar</tt> like this:
1381</p>
1382
1383<div class="targetlang">
1384<pre>
1385&gt;&gt;&gt; print example.cvar.Spam_bar
13867
1387</pre>
1388</div>
1389
1390<H3><a name="Python_nn21"></a>26.3.8 C++ inheritance</H3>
1391
1392
1393<p>
1394SWIG is fully aware of issues related to C++ inheritance. Therefore, if you have
1395classes like this
1396</p>
1397
1398<div class="code">
1399<pre>
1400class Foo {
1401...
1402};
1403
1404class Bar : public Foo {
1405...
1406};
1407</pre>
1408</div>
1409
1410<p>
1411those classes are wrapped into a hierarchy of Python classes that reflect the same inheritance
1412structure. All of the usual Python utility functions work normally:
1413</p>
1414
1415<div class="targetlang">
1416<pre>
1417&gt;&gt;&gt; b = Bar()
1418&gt;&gt;&gt; instance(b,Foo)
14191
1420&gt;&gt;&gt; issubclass(Bar,Foo)
14211
1422&gt;&gt;&gt; issubclass(Foo,Bar)
14230
1424</pre>
1425</div>
1426
1427<p>
1428Furthermore, if you have functions like this
1429</p>
1430
1431<div class="code">
1432<pre>
1433void spam(Foo *f);
1434</pre>
1435</div>
1436
1437<p>
1438then the function <tt>spam()</tt> accepts <tt>Foo *</tt> or a pointer to any class derived from <tt>Foo</tt>.
1439</p>
1440
1441<p>
1442It is safe to use multiple inheritance with SWIG.
1443</p>
1444
1445<H3><a name="Python_nn22"></a>26.3.9 Pointers, references, values, and arrays</H3>
1446
1447
1448<p>
1449In C++, there are many different ways a function might receive
1450and manipulate objects. For example:
1451</p>
1452
1453<div class="code">
1454<pre>
1455void spam1(Foo *x); // Pass by pointer
1456void spam2(Foo &amp;x); // Pass by reference
1457void spam3(const Foo &amp;x);// Pass by const reference
1458void spam4(Foo x); // Pass by value
1459void spam5(Foo x[]); // Array of objects
1460</pre>
1461</div>
1462
1463<p>
1464In Python, there is no detailed distinction like this--specifically,
1465there are only "objects". There are no pointers, references, arrays,
1466and so forth. Because of this, SWIG unifies all of these types
1467together in the wrapper code. For instance, if you actually had the
1468above functions, it is perfectly legal to do this:
1469</p>
1470
1471<div class="targetlang">
1472<pre>
1473&gt;&gt;&gt; f = Foo() # Create a Foo
1474&gt;&gt;&gt; spam1(f) # Ok. Pointer
1475&gt;&gt;&gt; spam2(f) # Ok. Reference
1476&gt;&gt;&gt; spam3(f) # Ok. Const reference
1477&gt;&gt;&gt; spam4(f) # Ok. Value.
1478&gt;&gt;&gt; spam5(f) # Ok. Array (1 element)
1479</pre>
1480</div>
1481
1482<p>
1483Similar behavior occurs for return values. For example, if you had
1484functions like this,
1485</p>
1486
1487<div class="code">
1488<pre>
1489Foo *spam6();
1490Foo &amp;spam7();
1491Foo spam8();
1492const Foo &amp;spam9();
1493</pre>
1494</div>
1495
1496<p>
1497then all three functions will return a pointer to some <tt>Foo</tt> object.
1498Since the third function (spam8) returns a value, newly allocated memory is used
1499to hold the result and a pointer is returned (Python will release this memory
1500when the return value is garbage collected). The fourth case (spam9)
1501which returns a const reference, in most of the cases will be
1502treated as a returning value, and it will follow the same
1503allocation/deallocation process.
1504</p>
1505
1506<H3><a name="Python_nn23"></a>26.3.10 C++ overloaded functions</H3>
1507
1508
1509<p>
1510C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example,
1511if you have two functions like this:
1512</p>
1513
1514<div class="code">
1515<pre>
1516void foo(int);
1517void foo(char *c);
1518</pre>
1519</div>
1520
1521<p>
1522You can use them in Python in a straightforward manner:
1523</p>
1524
1525<div class="targetlang">
1526<pre>
1527&gt;&gt;&gt; foo(3) # foo(int)
1528&gt;&gt;&gt; foo("Hello") # foo(char *c)
1529</pre>
1530</div>
1531
1532<p>
1533Similarly, if you have a class like this,
1534</p>
1535
1536<div class="code">
1537<pre>
1538class Foo {
1539public:
1540 Foo();
1541 Foo(const Foo &amp;);
1542 ...
1543};
1544</pre>
1545</div>
1546
1547<p>
1548you can write Python code like this:
1549</p>
1550
1551<div class="targetlang">
1552<pre>
1553&gt;&gt;&gt; f = Foo() # Create a Foo
1554&gt;&gt;&gt; g = Foo(f) # Copy f
1555</pre>
1556</div>
1557
1558<p>
1559Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG
1560can't disambiguate. For example:
1561</p>
1562
1563<div class="code">
1564<pre>
1565void spam(int);
1566void spam(short);
1567</pre>
1568</div>
1569
1570<p>
1571or
1572</p>
1573
1574<div class="code">
1575<pre>
1576void foo(Bar *b);
1577void foo(Bar &amp;b);
1578</pre>
1579</div>
1580
1581<p>
1582If declarations such as these appear, you will get a warning message like this:
1583</p>
1584
1585<div class="shell">
1586<pre>
1587example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)
1588at example.i:11.
1589</pre>
1590</div>
1591
1592<p>
1593To fix this, you either need to ignore or rename one of the methods. For example:
1594</p>
1595
1596<div class="code">
1597<pre>
1598%rename(spam_short) spam(short);
1599...
1600void spam(int);
1601void spam(short); // Accessed as spam_short
1602</pre>
1603</div>
1604
1605<p>
1606or
1607</p>
1608
1609<div class="code">
1610<pre>
1611%ignore spam(short);
1612...
1613void spam(int);
1614void spam(short); // Ignored
1615</pre>
1616</div>
1617
1618<p>
1619SWIG resolves overloaded functions and methods using a disambiguation scheme that ranks and sorts
1620declarations according to a set of type-precedence rules. The order in which declarations appear
1621in the input does not matter except in situations where ambiguity arises--in this case, the
1622first declaration takes precedence.
1623</p>
1624
1625<p>
1626Please refer to the "SWIG and C++" chapter for more information about overloading.
1627</p>
1628
1629<H3><a name="Python_nn24"></a>26.3.11 C++ operators</H3>
1630
1631
1632<p>
1633Certain C++ overloaded operators can be handled automatically by SWIG. For example,
1634consider a class like this:
1635</p>
1636
1637<div class="code">
1638<pre>
1639class Complex {
1640private:
1641 double rpart, ipart;
1642public:
1643 Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
1644 Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
1645 Complex &amp;operator=(const Complex &amp;c);
1646
1647 Complex operator+=(const Complex &amp;c) const;
1648 Complex operator+(const Complex &amp;c) const;
1649 Complex operator-(const Complex &amp;c) const;
1650 Complex operator*(const Complex &amp;c) const;
1651 Complex operator-() const;
1652
1653 double re() const { return rpart; }
1654 double im() const { return ipart; }
1655};
1656</pre>
1657</div>
1658
1659<p>
1660When wrapped, it works like you expect:
1661</p>
1662
1663<div class="targetlang">
1664<pre>
1665&gt;&gt;&gt; c = Complex(3,4)
1666&gt;&gt;&gt; d = Complex(7,8)
1667&gt;&gt;&gt; e = c + d
1668&gt;&gt;&gt; e.re()
166910.0
1670&gt;&gt;&gt; e.im()
167112.0
1672&gt;&gt;&gt; c += d
1673&gt;&gt;&gt; c.re()
167410.0
1675&gt;&gt;&gt; c.im()
167612.0
1677
1678</pre>
1679</div>
1680
1681<p>
1682One restriction with operator overloading support is that SWIG is not
1683able to fully handle operators that aren't defined as part of the class.
1684For example, if you had code like this
1685</p>
1686
1687<div class="code">
1688<pre>
1689class Complex {
1690...
1691friend Complex operator+(double, const Complex &amp;c);
1692...
1693};
1694</pre>
1695</div>
1696
1697<p>
1698then SWIG ignores it and issues a warning. You can still wrap the operator,
1699but you may have to encapsulate it in a special function. For example:
1700</p>
1701
1702<div class="code">
1703<pre>
1704%rename(Complex_add_dc) operator+(double, const Complex &amp;);
1705</pre>
1706</div>
1707
1708<p>
1709There are ways to make this operator appear as part of the class using the <tt>%extend</tt> directive.
1710Keep reading.
1711</p>
1712
1713<p>
1714Also, be aware that certain operators don't map cleanly to Python. For instance,
1715overloaded assignment operators don't map to Python semantics and will be ignored.
1716</p>
1717
1718<H3><a name="Python_nn25"></a>26.3.12 C++ namespaces</H3>
1719
1720
1721<p>
1722SWIG is aware of C++ namespaces, but namespace names do not appear in
1723the module nor do namespaces result in a module that is broken up into
1724submodules or packages. For example, if you have a file like this,
1725</p>
1726
1727<div class="code">
1728<pre>
1729%module example
1730
1731namespace foo {
1732 int fact(int n);
1733 struct Vector {
1734 double x,y,z;
1735 };
1736};
1737</pre>
1738</div>
1739
1740<p>
1741it works in Python as follows:
1742</p>
1743
1744<div class="targetlang">
1745<pre>
1746&gt;&gt;&gt; import example
1747&gt;&gt;&gt; example.fact(3)
17486
1749&gt;&gt;&gt; v = example.Vector()
1750&gt;&gt;&gt; v.x = 3.4
1751&gt;&gt;&gt; print v.y
17520.0
1753&gt;&gt;&gt;
1754</pre>
1755</div>
1756
1757<p>
1758If your program has more than one namespace, name conflicts (if any) can be resolved using <tt>%rename</tt>
1759For example:
1760</p>
1761
1762<div class="code">
1763<pre>
1764%rename(Bar_spam) Bar::spam;
1765
1766namespace Foo {
1767 int spam();
1768}
1769
1770namespace Bar {
1771 int spam();
1772}
1773</pre>
1774</div>
1775
1776<p>
1777If you have more than one namespace and your want to keep their
1778symbols separate, consider wrapping them as separate SWIG modules.
1779For example, make the module name the same as the namespace and create
1780extension modules for each namespace separately. If your program
1781utilizes thousands of small deeply nested namespaces each with
1782identical symbol names, well, then you get what you deserve.
1783</p>
1784
1785<H3><a name="Python_nn26"></a>26.3.13 C++ templates</H3>
1786
1787
1788<p>
1789C++ templates don't present a huge problem for SWIG. However, in order
1790to create wrappers, you have to tell SWIG to create wrappers for a particular
1791template instantiation. To do this, you use the <tt>%template</tt> directive.
1792For example:
1793</p>
1794
1795<div class="code">
1796<pre>
1797%module example
1798%{
1799#include "pair.h"
1800%}
1801
1802template&lt;class T1, class T2&gt;
1803struct pair {
1804 typedef T1 first_type;
1805 typedef T2 second_type;
1806 T1 first;
1807 T2 second;
1808 pair();
1809 pair(const T1&amp;, const T2&amp;);
1810 ~pair();
1811};
1812
1813%template(pairii) pair&lt;int,int&gt;;
1814</pre>
1815</div>
1816
1817<p>
1818In Python:
1819</p>
1820
1821<div class="targetlang">
1822<pre>
1823&gt;&gt;&gt; import example
1824&gt;&gt;&gt; p = example.pairii(3,4)
1825&gt;&gt;&gt; p.first
18263
1827&gt;&gt;&gt; p.second
18284
1829</pre>
1830</div>
1831
1832<p>
1833Obviously, there is more to template wrapping than shown in this example.
1834More details can be found in the <a href="SWIGPlus.html#SWIGPlus">SWIG and C++</a> chapter. Some more complicated
1835examples will appear later.
1836</p>
1837
1838<H3><a name="Python_nn27"></a>26.3.14 C++ Smart Pointers</H3>
1839
1840
1841<p>
1842In certain C++ programs, it is common to use classes that have been wrapped by
1843so-called "smart pointers." Generally, this involves the use of a template class
1844that implements <tt>operator-&gt;()</tt> like this:
1845</p>
1846
1847<div class="code">
1848<pre>
1849template&lt;class T&gt; class SmartPtr {
1850 ...
1851 T *operator-&gt;();
1852 ...
1853}
1854</pre>
1855</div>
1856
1857<p>
1858Then, if you have a class like this,
1859</p>
1860
1861<div class="code">
1862<pre>
1863class Foo {
1864public:
1865 int x;
1866 int bar();
1867};
1868</pre>
1869</div>
1870
1871<p>
1872A smart pointer would be used in C++ as follows:
1873</p>
1874
1875<div class="code">
1876<pre>
1877SmartPtr&lt;Foo&gt; p = CreateFoo(); // Created somehow (not shown)
1878...
1879p-&gt;x = 3; // Foo::x
1880int y = p-&gt;bar(); // Foo::bar
1881</pre>
1882</div>
1883
1884<p>
1885To wrap this in Python, simply tell SWIG about the <tt>SmartPtr</tt> class and the low-level
1886<tt>Foo</tt> object. Make sure you instantiate <tt>SmartPtr</tt> using <tt>%template</tt> if necessary.
1887For example:
1888</p>
1889
1890<div class="code">
1891<pre>
1892%module example
1893...
1894%template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
1895...
1896</pre>
1897</div>
1898
1899<p>
1900Now, in Python, everything should just "work":
1901</p>
1902
1903<div class="targetlang">
1904<pre>
1905&gt;&gt;&gt; p = example.CreateFoo() # Create a smart-pointer somehow
1906&gt;&gt;&gt; p.x = 3 # Foo::x
1907&gt;&gt;&gt; p.bar() # Foo::bar
1908</pre>
1909</div>
1910
1911<p>
1912If you ever need to access the underlying pointer returned by <tt>operator-&gt;()</tt> itself,
1913simply use the <tt>__deref__()</tt> method. For example:
1914</p>
1915
1916<div class="targetlang">
1917<pre>
1918&gt;&gt;&gt; f = p.__deref__() # Returns underlying Foo *
1919</pre>
1920</div>
1921
1922
1923<H3><a name="Python_nn27a"></a>26.3.15 C++ Reference Counted Objects (ref/unref)</H3>
1924
1925
1926<p>
1927Another usual idiom in C++ is the use of reference counted
1928objects. Consider for example:
1929
1930<div class="code">
1931<pre>
1932class RCObj {
1933 // implement the ref counting mechanism
1934 int add_ref();
1935 int del_ref();
1936 int ref_count();
1937
1938public:
1939 virtual ~RCObj() = 0;
1940
1941 int ref() const {
1942 return add_ref();
1943 }
1944
1945 int unref() const {
1946 if (ref_count() == 0 || del_ref() == 0 ) {
1947 delete this;
1948 return 0;
1949 }
1950 return ref_count();
1951 }
1952};
1953
1954
1955class A : RCObj {
1956public:
1957 A();
1958 int foo();
1959};
1960
1961
1962class B {
1963 A *_a;
1964
1965public:
1966 B(A *a) : _a(a) {
1967 a-&gt;ref();
1968 }
1969
1970 ~B() {
1971 a-&gt;unref();
1972 }
1973};
1974
1975int main() {
1976 A *a = new A();
1977 a->ref(); // 'a' is ref here
1978
1979 B *b1 = new B(a); // 'a' is ref here
1980 if (1 + 1 == 2) {
1981 B *b2 = new B(a); // 'a' is ref here
1982 delete b2; // 'a' is unref, but not deleted
1983 }
1984
1985 delete b1; // 'a' is unref, but not deleted
1986 a->unref(); // 'a' is unref and deleted
1987}
1988</pre>
1989</div>
1990
1991<p>
1992In the example above, the 'A' class instance 'a' is a reference counted
1993object, which can't be deleted arbitrarily since it is shared between
1994the objects 'b1' and 'b2'. 'A' is derived from an Reference Counted
1995Object 'RCObj', which implements the ref/unref idiom.
1996</p>
1997
1998<p>
1999To tell SWIG that 'RCObj' and all its derived classes are reference
2000counted objects, you use the "ref" and "unref" features. For example:
2001</p>
2002
2003
2004<div class="code">
2005<pre>
2006%module example
2007...
2008
2009%feature("ref") RCObj "$this->ref();"
2010%feature("unref") RCObj "$this->unref();"
2011
2012%include "rcobj.h"
2013%include "A.h"
2014...
2015</pre>
2016</div>
2017
2018<p>
2019where the code passed to the "ref" and "unref" methods will be
2020executed as needed whenever a new object is passed to python, or when
2021python tries to release the shadow object instance, respectively.
2022</p>
2023
2024<p>
2025In the python side, the use of a reference counted object is not
2026different than any other regular instance:
2027</p>
2028
2029<div class="targetlang">
2030<pre>
2031def create_A():
2032 a = A() # SWIG ref 'a' (new object is passed to python)
2033 b1 = B(a) # C++ ref 'a'
2034 if 1 + 1 == 2:
2035 b2 = B(a) # C++ ref 'a'
2036 return a # 'b1' and 'b2' are released, C++ unref 'a' twice
2037
2038a = create_A()
2039exit # 'a' is released, SWIG unref 'a'
2040</pre>
2041</div>
2042
2043<p>
2044Note that the user doens't explicitly need to call 'a->ref()' nor 'a->unref()'
2045(as neither 'delete a'). Instead, SWIG take cares of executing the "ref"
2046and "unref" codes as needed. If the user doesn't specify the
2047"ref/unref" features, SWIG will produce a code equivalent to define
2048them as:
2049</p>
2050
2051<div class="code">
2052<pre>
2053%feature("ref") ""
2054%feature("unref") "delete $this;"
2055</pre>
2056</div>
2057
2058<p>
2059In other words, SWIG will not do anything special when a new object
2060is passed to python, and it will always 'delete' the object when
2061python releases the shadow instance.
2062</p>
2063
2064
2065<H2><a name="Python_nn28"></a>26.4 Further details on the Python class interface</H2>
2066
2067
2068<p>
2069In the previous section, a high-level view of Python wrapping was
2070presented. A key component of this wrapping is that structures and
2071classes are wrapped by Python proxy classes. This provides a very
2072natural Python interface and allows SWIG to support a number of
2073advanced features such as operator overloading. However, a number
2074of low-level details were omitted. This section provides a brief overview
2075of how the proxy classes work.
2076</p>
2077
2078<H3><a name="Python_nn29"></a>26.4.1 Proxy classes</H3>
2079
2080
2081<p>
2082In the <a href="SWIG.html#SWIG">"SWIG basics"</a> and <a href="SWIGPlus.html#SWIGPlus">"SWIG and C++"</a> chapters,
2083details of low-level structure and class wrapping are described. To summarize those chapters, if you
2084have a class like this
2085</p>
2086
2087<div class="code">
2088<pre>
2089class Foo {
2090public:
2091 int x;
2092 int spam(int);
2093 ...
2094</pre>
2095</div>
2096
2097<p>
2098then SWIG transforms it into a set of low-level procedural wrappers. For example:
2099</p>
2100
2101<div class="code">
2102<pre>
2103Foo *new_Foo() {
2104 return new Foo();
2105}
2106void delete_Foo(Foo *f) {
2107 delete f;
2108}
2109int Foo_x_get(Foo *f) {
2110 return f-&gt;x;
2111}
2112void Foo_x_set(Foo *f, int value) {
2113 f-&gt;x = value;
2114}
2115int Foo_spam(Foo *f, int arg1) {
2116 return f-&gt;spam(arg1);
2117}
2118</pre>
2119</div>
2120
2121<p>
2122These wrappers can be found in the low-level extension module (e.g., <tt>_example</tt>).
2123</p>
2124
2125<p>
2126Using these wrappers, SWIG generates a high-level Python proxy class (also known as a shadow class) like this (shown
2127for Python 2.2):
2128</p>
2129
2130<div class="targetlang">
2131<pre>
2132import _example
2133
2134class Foo(object):
2135 def __init__(self):
2136 self.this = _example.new_Foo()
2137 self.thisown = 1
2138 def __del__(self):
2139 if self.thisown:
2140 _example.delete_Foo(self.this)
2141 def spam(self,arg1):
2142 return _example.Foo_spam(self.this,arg1)
2143 x = property(_example.Foo_x_get, _example.Foo_x_set)
2144</pre>
2145</div>
2146
2147<p>
2148This class merely holds a pointer to the underlying C++ object (<tt>.this</tt>) and dispatches methods and
2149member variable access to that object using the low-level accessor functions. From a user's point of
2150view, it makes the class work normally:
2151</p>
2152
2153<div class="targetlang">
2154<pre>
2155&gt;&gt;&gt; f = example.Foo()
2156&gt;&gt;&gt; f.x = 3
2157&gt;&gt;&gt; y = f.spam(5)
2158</pre>
2159</div>
2160
2161<p>
2162The fact that the class has been wrapped by a real Python class offers certain advantages. For instance,
2163you can attach new Python methods to the class and you can even inherit from it (something not supported
2164by Python built-in types until Python 2.2).
2165</p>
2166
2167<H3><a name="Python_nn30"></a>26.4.2 Memory management</H3>
2168
2169
2170<p>
2171Associated with proxy object, is an ownership flag <tt>.thisown</tt> The value of this
2172flag determines who is responsible for deleting the underlying C++ object. If set to 1,
2173the Python interpreter will destroy the C++ object when the proxy class is
2174garbage collected. If set to 0 (or if the attribute is missing), then the destruction
2175of the proxy class has no effect on the C++ object.
2176</p>
2177
2178<p>
2179When an object is created by a constructor or returned by value, Python automatically takes
2180ownership of the result. For example:
2181</p>
2182
2183<div class="code">
2184<pre>
2185class Foo {
2186public:
2187 Foo();
2188 Foo bar();
2189};
2190</pre>
2191</div>
2192
2193<p>
2194In Python:
2195</p>
2196
2197<div class="targetlang">
2198<pre>
2199&gt;&gt;&gt; f = Foo()
2200&gt;&gt;&gt; f.thisown
22011
2202&gt;&gt;&gt; g = f.bar()
2203&gt;&gt;&gt; g.thisown
22041
2205</pre>
2206</div>
2207
2208<p>
2209On the other hand, when pointers are returned to Python, there is often no way to know where
2210they came from. Therefore, the ownership is set to zero. For example:
2211</p>
2212
2213<div class="code">
2214<pre>
2215class Foo {
2216public:
2217 ...
2218 Foo *spam();
2219 ...
2220};
2221</pre>
2222</div>
2223
2224<br>
2225
2226<div class="targetlang">
2227<pre>
2228&gt;&gt;&gt; f = Foo()
2229&gt;&gt;&gt; s = f.spam()
2230&gt;&gt;&gt; print s.thisown
22310
2232&gt;&gt;&gt;
2233</pre>
2234</div>
2235
2236<p>
2237This behavior is especially important for classes that act as
2238containers. For example, if a method returns a pointer to an object
2239that is contained inside another object, you definitely don't want
2240Python to assume ownership and destroy it!
2241</p>
2242
2243<p>
2244Related to containers, ownership issues can arise whenever an object is assigned to a member
2245or global variable. For example, consider this interface:
2246</p>
2247
2248<div class="code">
2249<pre>
2250%module example
2251
2252struct Foo {
2253 int value;
2254 Foo *next;
2255};
2256
2257Foo *head = 0;
2258</pre>
2259</div>
2260
2261<p>
2262When wrapped in Python, careful observation will reveal that ownership changes whenever an object
2263is assigned to a global variable. For example:
2264</p>
2265
2266<div class="targetlang">
2267<pre>
2268&gt;&gt;&gt; f = example.Foo()
2269&gt;&gt;&gt; f.thisown
22701
2271&gt;&gt;&gt; example.cvar.head = f
2272&gt;&gt;&gt; f.thisown
22730
2274&gt;&gt;&gt;
2275</pre>
2276</div>
2277
2278<p>
2279In this case, C is now holding a reference to the object---you probably don't want Python to destroy it.
2280Similarly, this occurs for members. For example:
2281</p>
2282
2283<div class="targetlang">
2284<pre>
2285&gt;&gt;&gt; f = example.Foo()
2286&gt;&gt;&gt; g = example.Foo()
2287&gt;&gt;&gt; f.thisown
22881
2289&gt;&gt;&gt; g.thisown
22901
2291&gt;&gt;&gt; f.next = g
2292&gt;&gt;&gt; g.thisown
22930
2294&gt;&gt;&gt;
2295</pre>
2296</div>
2297
2298<p>
2299For the most part, memory management issues remain hidden. However,
2300there are occasionally situations where you might have to manually
2301change the ownership of an object. For instance, consider code like this:
2302</p>
2303
2304<div class="code">
2305<pre>
2306class Node {
2307 Object *value;
2308public:
2309 void set_value(Object *v) { value = v; }
2310 ...
2311};
2312</pre>
2313</div>
2314
2315<p>
2316Now, consider the following Python code:
2317</p>
2318
2319<div class="targetlang">
2320<pre>
2321&gt;&gt;&gt; v = Object() # Create an object
2322&gt;&gt;&gt; n = Node() # Create a node
2323&gt;&gt;&gt; n.set_value(v) # Set value
2324&gt;&gt;&gt; v.thisown
23251
2326&gt;&gt;&gt; del v
2327</pre>
2328</div>
2329
2330<p>
2331In this case, the object <tt>n</tt> is holding a reference to
2332<tt>v</tt> internally. However, SWIG has no way to know that this
2333has occurred. Therefore, Python still thinks that it has ownership of the
2334object. Should the proxy object be destroyed, then the C++ destructor
2335will be invoked and <tt>n</tt> will be holding a stale-pointer. If
2336you're lucky, you will only get a segmentation fault.
2337</p>
2338
2339<p>
2340To work around this, it is always possible to flip the ownership flag. For example,
2341</p>
2342
2343<div class="targetlang">
2344<pre>
2345&gt;&gt;&gt; v.thisown = 0
2346</pre>
2347</div>
2348
2349<p>
2350It is also possible to deal with situations like this using
2351typemaps--an advanced topic discussed later.
2352</p>
2353
2354<H3><a name="Python_nn31"></a>26.4.3 Python 2.2 and classic classes</H3>
2355
2356
2357<p>
2358SWIG makes every attempt to preserve backwards compatibility with
2359older versions of Python to the extent that it is possible. However,
2360in Python-2.2, an entirely new type of class system was introduced.
2361This new-style class system offers many enhancements including static
2362member functions, properties (managed attributes), and class methods.
2363Details about all of these changes can be found on <a
2364href="//www.python.org">www.python.org</a> and is not repeated here.
2365</p>
2366
2367<p>
2368To address differences between Python versions, SWIG currently emits
2369dual-mode proxy class wrappers. In Python-2.2 and newer releases,
2370these wrappers encapsulate C++ objects in new-style classes that take
2371advantage of new features (static methods and properties). However,
2372if these very same wrappers are imported into an older version of Python,
2373old-style classes are used instead.
2374</p>
2375
2376<p>
2377This dual-nature of the wrapper code means that you can create extension
2378modules with SWIG and those modules will work with all versions of Python
2379ranging from Python-1.4 to the very latest release. Moreover, the wrappers take
2380advantage of Python-2.2 features when available.
2381</p>
2382
2383<p>
2384For the most part, the interface presented to users is the same regardless
2385of what version of Python is used. The only incompatibility lies in the handling
2386of static member functions. In Python-2.2, they can be accessed via the
2387class itself. In Python-2.1 and earlier, they have to be accessed as a global
2388function or through an instance (see the earlier section).
2389</p>
2390
2391<H2><a name="directors"></a>26.5 Cross language polymorphism</H2>
2392
2393
2394<p>
2395Proxy classes provide a more natural, object-oriented way to access
2396extension classes. As described above, each proxy instance has an
2397associated C++ instance, and method calls to the proxy are passed to the
2398C++ instance transparently via C wrapper functions.
2399</p>
2400
2401<p>
2402This arrangement is asymmetric in the sense that no corresponding
2403mechanism exists to pass method calls down the inheritance chain from
2404C++ to Python. In particular, if a C++ class has been extended in Python
2405(by extending the proxy class), these extensions will not be visible
2406from C++ code. Virtual method calls from C++ are thus not able access
2407the lowest implementation in the inheritance chain.
2408</p>
2409
2410<p>
2411Changes have been made to SWIG 1.3.18 to address this problem and
2412make the relationship between C++ classes and proxy classes more
2413symmetric. To achieve this goal, new classes called directors are
2414introduced at the bottom of the C++ inheritance chain. The job of the
2415directors is to route method calls correctly, either to C++
2416implementations higher in the inheritance chain or to Python
2417implementations lower in the inheritance chain. The upshot is that C++
2418classes can be extended in Python and from C++ these extensions look
2419exactly like native C++ classes. Neither C++ code nor Python code needs
2420to know where a particular method is implemented: the combination of
2421proxy classes, director classes, and C wrapper functions takes care of
2422all the cross-language method routing transparently.
2423</p>
2424
2425<H3><a name="Python_nn33"></a>26.5.1 Enabling directors</H3>
2426
2427
2428<p>
2429The director feature is disabled by default. To use directors you
2430must make two changes to the interface file. First, add the "directors"
2431option to the %module directive, like this:
2432</p>
2433
2434<div class="code">
2435<pre>
2436%module(directors="1") modulename
2437</pre>
2438</div>
2439
2440<p>
2441Without this option no director code will be generated. Second, you
2442must use the %feature("director") directive to tell SWIG which classes
2443and methods should get directors. The %feature directive can be applied
2444globally, to specific classes, and to specific methods, like this:
2445</p>
2446
2447<div class="code">
2448<pre>
2449// generate directors for all classes that have virtual methods
2450%feature("director");
2451
2452// genarate directors for all virtual methods in class Foo
2453%feature("director") Foo;
2454
2455// generate a director for just Foo::bar()
2456%feature("director") Foo::bar;
2457</pre>
2458</div>
2459
2460<p>
2461You can use the %feature("nodirector") directive to turn off
2462directors for specific classes or methods. So for example,
2463</p>
2464
2465<div class="code">
2466<pre>
2467%feature("director") Foo;
2468%feature("nodirector") Foo::bar;
2469</pre>
2470</div>
2471
2472<p>
2473will generate directors for all virtual methods of class Foo except
2474bar().
2475</p>
2476
2477<p>
2478Directors can also be generated implicitly through inheritance.
2479In the following, class Bar will get a director class that handles
2480the methods one() and two() (but not three()):
2481</p>
2482
2483<div class="code">
2484<pre>
2485%feature("director") Foo;
2486class Foo {
2487public:
2488 Foo(int foo);
2489 virtual void one();
2490 virtual void two();
2491};
2492
2493class Bar: public Foo {
2494public:
2495 virtual void three();
2496};
2497</pre>
2498</div>
2499
2500<p>
2501then at the python side you can define
2502</p>
2503
2504<div class="targetlang">
2505<pre>
2506import mymodule
2507
2508class MyFoo(mymodule.Foo):
2509 def __init__(self, foo):
2510 mymodule.Foo(self, foo)
2511
2512 def one(self):
2513 print "one from python"
2514</pre>
2515</div>
2516
2517
2518<H3><a name="Python_nn34"></a>26.5.2 Director classes</H3>
2519
2520
2521
2522
2523
2524<p>
2525For each class that has directors enabled, SWIG generates a new class
2526that derives from both the class in question and a special
2527<tt>Swig::Director</tt> class. These new classes, referred to as director
2528classes, can be loosely thought of as the C++ equivalent of the Python
2529proxy classes. The director classes store a pointer to their underlying
2530Python object and handle various issues related to object ownership.
2531Indeed, this is quite similar to the "this" and "thisown" members of the
2532Python proxy classes.
2533</p>
2534
2535<p>
2536For simplicity let's ignore the <tt>Swig::Director</tt> class and refer to the
2537original C++ class as the director's base class. By default, a director
2538class extends all virtual methods in the inheritance chain of its base
2539class (see the preceding section for how to modify this behavior).
2540Thus all virtual method calls, whether they originate in C++ or in
2541Python via proxy classes, eventually end up in at the implementation in
2542the director class. The job of the director methods is to route these
2543method calls to the appropriate place in the inheritance chain. By
2544"appropriate place" we mean the method that would have been called if
2545the C++ base class and its extensions in Python were seamlessly
2546integrated. That seamless integration is exactly what the director
2547classes provide, transparently skipping over all the messy extension API
2548glue that binds the two languages together.
2549</p>
2550
2551<p>
2552In reality, the "appropriate place" is one of only two possibilities:
2553C++ or Python. Once this decision is made, the rest is fairly easy. If
2554the correct implementation is in C++, then the lowest implementation of
2555the method in the C++ inheritance chain is called explicitly. If the
2556correct implementation is in Python, the Python API is used to call the
2557method of the underlying Python object (after which the usual virtual
2558method resolution in Python automatically finds the right
2559implementation).
2560</p>
2561
2562<p>
2563Now how does the director decide which language should handle the method call?
2564The basic rule is to handle the method in Python, unless there's a good
2565reason not to. The reason for this is simple: Python has the most
2566"extended" implementation of the method. This assertion is guaranteed,
2567since at a minimum the Python proxy class implements the method. If the
2568method in question has been extended by a class derived from the proxy
2569class, that extended implementation will execute exactly as it should.
2570If not, the proxy class will route the method call into a C wrapper
2571function, expecting that the method will be resolved in C++. The wrapper
2572will call the virtual method of the C++ instance, and since the director
2573extends this the call will end up right back in the director method. Now
2574comes the "good reason not to" part. If the director method were to blindly
2575call the Python method again, it would get stuck in an infinite loop. We avoid this
2576situation by adding special code to the C wrapper function that tells
2577the director method to not do this. The C wrapper function compares the
2578pointer to the Python object that called the wrapper function to the
2579pointer stored by the director. If these are the same, then the C
2580wrapper function tells the director to resolve the method by calling up
2581the C++ inheritance chain, preventing an infinite loop.
2582</p>
2583
2584<p>
2585One more point needs to be made about the relationship between director
2586classes and proxy classes. When a proxy class instance is created in
2587Python, SWIG creates an instance of the original C++ class and assigns
2588it to <tt>.this</tt>. This is exactly what happens without directors and
2589is true even if directors are enabled for the particular class in
2590question. When a class <i>derived</i> from a proxy class is created,
2591however, SWIG then creates an instance of the corresponding C++ director
2592class. The reason for this difference is that user-defined subclasses
2593may override or extend methods of the original class, so the director
2594class is needed to route calls to these methods correctly. For
2595unmodified proxy classes, all methods are ultimately implemented in C++
2596so there is no need for the extra overhead involved with routing the
2597calls through Python.
2598</p>
2599
2600<H3><a name="Python_nn35"></a>26.5.3 Ownership and object destruction</H3>
2601
2602
2603<p>
2604Memory management issues are slightly more complicated with directors
2605than for proxy classes alone. Python instances hold a pointer to the
2606associated C++ director object, and the director in turn holds a pointer
2607back to the Python object. By default, proxy classes own their C++
2608director object and take care of deleting it when they are garbage
2609collected.
2610</p>
2611
2612<p>
2613This relationship can be reversed by calling the special
2614<tt>__disown__()</tt> method of the proxy class. After calling this
2615method, the <tt>.thisown</tt> flag is set to zero, and the director
2616class increments the reference count of the Python object. When the
2617director class is deleted it decrements the reference count. Assuming no
2618outstanding references to the Python object remain, the Python object
2619will be destroyed at the same time. This is a good thing, since
2620directors and proxies refer to each other and so must be created and
2621destroyed together. Destroying one without destroying the other will
2622likely cause your program to segfault.
2623</p>
2624
2625<p>
2626To help ensure that no references to the Python object remain after
2627calling <tt>__disown__()</tt>, this method returns a weak reference to
2628the Python object. Weak references are only available in Python versions
26292.1 and higher, so for older versions you must exclicitly delete all
2630references. Here is an example:
2631</p>
2632
2633<div class="code">
2634<pre>
2635class Foo {
2636public:
2637 ...
2638};
2639class FooContainer {
2640public:
2641 void addFoo(Foo *);
2642 ...
2643};
2644</pre>
2645</div>
2646
2647<br>
2648
2649<div class="targetlang">
2650<pre>
2651&gt;&gt;&gt; c = FooContainer()
2652&gt;&gt;&gt; a = Foo().__disown()__
2653&gt;&gt;&gt; c.addFoo(a)
2654&gt;&gt;&gt; b = Foo()
2655&gt;&gt;&gt; b = b.__disown()__
2656&gt;&gt;&gt; c.addFoo(b)
2657&gt;&gt;&gt; c.addFoo(Foo().__disown()__)
2658</pre>
2659</div>
2660
2661<p>
2662In this example, we are assuming that FooContainer will take care of
2663deleting all the Foo pointers it contains at some point. Note that no hard
2664references to the Foo objects remain in Python.
2665</p>
2666
2667<H3><a name="Python_nn36"></a>26.5.4 Exception unrolling</H3>
2668
2669
2670<p>
2671With directors routing method calls to Python, and proxies routing them
2672to C++, the handling of exceptions is an important concern. By default, the
2673directors ignore exceptions that occur during method calls that are
2674resolved in Python. To handle such exceptions correctly, it is necessary
2675to temporarily translate them into C++ exceptions. This can be done with
2676the %feature("director:except") directive. The following code should
2677suffice in most cases:
2678</p>
2679
2680<div class="code">
2681<pre>
2682%feature("director:except") {
2683 if ($error != NULL) {
2684 throw Swig::DirectorMethodException();
2685 }
2686}
2687</pre>
2688</div>
2689
2690<p>
2691This code will check the Python error state after each method call from
2692a director into Python, and throw a C++ exception if an error occured.
2693This exception can be caught in C++ to implement an error handler.
2694Currently no information about the Python error is stored in the
2695Swig::DirectorMethodException object, but this will likely change in
2696the future.
2697</p>
2698
2699<p>
2700It may be the case that a method call originates in Python, travels up
2701to C++ through a proxy class, and then back into Python via a director
2702method. If an exception occurs in Python at this point, it would be nice
2703for that exception to find its way back to the original caller. This can
2704be done by combining a normal %exception directive with the
2705<tt>director:except</tt> handler shown above. Here is an example of a
2706suitable exception handler:
2707</p>
2708
2709<div class="code">
2710<pre>
2711%exception {
2712 try { $action }
2713 catch (Swig::DirectorException &amp;e) { SWIG_fail; }
2714}
2715</pre>
2716</div>
2717
2718<p>
2719The class Swig::DirectorException used in this example is actually a
2720base class of Swig::DirectorMethodException, so it will trap this
2721exception. Because the Python error state is still set when
2722Swig::DirectorMethodException is thrown, Python will register the
2723exception as soon as the C wrapper function returns.
2724</p>
2725
2726<H3><a name="Python_nn37"></a>26.5.5 Overhead and code bloat</H3>
2727
2728
2729<p>
2730Enabling directors for a class will generate a new director method for
2731every virtual method in the class' inheritance chain. This alone can
2732generate a lot of code bloat for large hierarchies. Method arguments
2733that require complex conversions to and from target language types can
2734result in large director methods. For this reason it is recommended that
2735you selectively enable directors only for specific classes that are
2736likely to be extended in Python and used in C++.
2737</p>
2738
2739<p>
2740Compared to classes that do not use directors, the call routing in the
2741director methods does add some overhead. In particular, at least one
2742dynamic cast and one extra function call occurs per method call from
2743Python. Relative to the speed of Python execution this is probably
2744completely negligible. For worst case routing, a method call that
2745ultimately resolves in C++ may take one extra detour through Python in
2746order to ensure that the method does not have an extended Python
2747implementation. This could result in a noticible overhead in some cases.
2748</p>
2749
2750<p>
2751Although directors make it natural to mix native C++ objects with Python
2752objects (as director objects) via a common base class pointer, one
2753should be aware of the obvious fact that method calls to Python objects
2754will be much slower than calls to C++ objects. This situation can be
2755optimized by selectively enabling director methods (using the %feature
2756directive) for only those methods that are likely to be extended in
2757Python.
2758</p>
2759
2760<H3><a name="Python_nn38"></a>26.5.6 Typemaps</H3>
2761
2762
2763<p>
2764Typemaps for input and output of most of the basic types from director
2765classes have been written. These are roughly the reverse of the usual
2766input and output typemaps used by the wrapper code. The typemap
2767operation names are 'directorin', 'directorout', and 'directorargout'.
2768The director code does not currently use any of the other kinds of typemaps.
2769It is not clear at this point which kinds are appropriate and
2770need to be supported.
2771</p>
2772
2773
2774<H3><a name="Python_nn39"></a>26.5.7 Miscellaneous</H3>
2775
2776
2777<p>
2778Director typemaps for STL classes are in place, and hence you should
2779be able to use std::vector, std::string, etc., as you would any other type.
2780</p>
2781
2782<p>
2783<b>Note:</b> The director typemaps for return types based in const
2784references, such as
2785
2786<div class="code">
2787<pre>
2788class Foo {
2789&hellip;
2790 virtual const int&amp; bar();
2791&hellip;
2792};
2793</pre>
2794</div>
2795
2796<p>
2797will work only for simple call scenarios. Usually the resulting code
2798is neither thread or reentrant safe. Hence, the user is advised to
2799avoid returning const references in director methods. For example,
2800the user could modify the method interface to use lvalue return
2801types, wherever possible, for example
2802</p>
2803
2804<div class="code">
2805<pre>
2806class Foo {
2807&hellip;
2808 virtual int bar();
2809&hellip;
2810};
2811</pre>
2812</div>
2813
2814<p>
2815If that is not possible, the user should avoid enabling the
2816director feature for reentrant, recursive or threaded member
2817methods that return const references.
2818</p>
2819
2820
2821<H2><a name="Python_nn40"></a>26.6 Common customization features</H2>
2822
2823
2824<p>
2825The last section presented the absolute basics of C/C++ wrapping. If
2826you do nothing but feed SWIG a header file, you will get an interface
2827that mimics the behavior described. However, sometimes this isn't
2828enough to produce a nice module. Certain types of functionality might
2829be missing or the interface to certain functions might be awkward.
2830This section describes some common SWIG features that are used to
2831improve your the interface to an extension module.
2832</p>
2833
2834<H3><a name="Python_nn41"></a>26.6.1 C/C++ helper functions</H3>
2835
2836
2837<p>
2838Sometimes when you create a module, it is missing certain bits of functionality. For
2839example, if you had a function like this
2840</p>
2841
2842<div class="code">
2843<pre>
2844void set_transform(Image *im, double m[4][4]);
2845</pre>
2846</div>
2847
2848<p>
2849it would be accessible from Python, but there may be no easy way to call it.
2850For example, you might get errors like this:
2851</p>
2852
2853<div class="targetlang">
2854<pre>
2855&gt;&gt;&gt; a = [
2856... [1,0,0,0],
2857... [0,1,0,0],
2858... [0,0,1,0],
2859... [0,0,0,1]]
2860&gt;&gt;&gt; set_transform(im,a)
2861Traceback (most recent call last):
2862 File "&lt;stdin&gt;", line 1, in ?
2863TypeError: Type error. Expected _p_a_4__double
2864</pre>
2865</div>
2866
2867<p>
2868The problem here is that there is no easy way to construct and manipulate a suitable
2869<tt>double [4][4]</tt> value to use. To fix this, you can write some extra C helper
2870functions. Just use the <tt>%inline</tt> directive. For example:
2871</p>
2872
2873<div class="code">
2874<pre>
2875%inline %{
2876/* Note: double[4][4] is equivalent to a pointer to an array double (*)[4] */
2877double (*new_mat44())[4] {
2878 return (double (*)[4]) malloc(16*sizeof(double));
2879}
2880void free_mat44(double (*x)[4]) {
2881 free(x);
2882}
2883void mat44_set(double x[4][4], int i, int j, double v) {
2884 x[i][j] = v;
2885}
2886double mat44_get(double x[4][4], int i, int j) {
2887 return x[i][j];
2888}
2889%}
2890</pre>
2891</div>
2892
2893<p>
2894From Python, you could then write code like this:
2895</p>
2896
2897<div class="targetlang">
2898<pre>
2899&gt;&gt;&gt; a = new_mat44()
2900&gt;&gt;&gt; mat44_set(a,0,0,1.0)
2901&gt;&gt;&gt; mat44_set(a,1,1,1.0)
2902&gt;&gt;&gt; mat44_set(a,2,2,1.0)
2903...
2904&gt;&gt;&gt; set_transform(im,a)
2905&gt;&gt;&gt;
2906</pre>
2907</div>
2908
2909<p>
2910Admittedly, this is not the most elegant looking approach. However, it works and it wasn't too
2911hard to implement. It is possible to clean this up using Python code, typemaps, and other
2912customization features as covered in later sections.
2913</p>
2914
2915<H3><a name="Python_nn42"></a>26.6.2 Adding additional Python code</H3>
2916
2917
2918<p>
2919If writing support code in C isn't enough, it is also possible to write code in
2920Python. This code gets inserted in to the <tt>.py</tt> file created by SWIG. One
2921use of Python code might be to supply a high-level interface to certain functions.
2922For example:
2923</p>
2924
2925<div class="code">
2926<pre>
2927void set_transform(Image *im, double x[4][4]);
2928
2929...
2930/* Rewrite the high level interface to set_transform */
2931%pythoncode %{
2932def set_transform(im,x):
2933 a = new_mat44()
2934 for i in range(4):
2935 for j in range(4):
2936 mat44_set(a,i,j,x[i][j])
2937 _example.set_transform(im,a)
2938 free_mat44(a)
2939%}
2940</pre>
2941</div>
2942
2943<p>
2944In this example, <tt>set_transform()</tt> provides a high-level Python interface built on top of
2945low-level helper functions. For example, this code now seems to work:
2946</p>
2947
2948<div class="targetlang">
2949<pre>
2950&gt;&gt;&gt; a = [
2951... [1,0,0,0],
2952... [0,1,0,0],
2953... [0,0,1,0],
2954... [0,0,0,1]]
2955&gt;&gt;&gt; set_transform(im,a)
2956&gt;&gt;&gt;
2957</pre>
2958</div>
2959
2960<p>
2961Admittedly, this whole scheme for wrapping the two-dimension array
2962argument is rather ad-hoc. Besides, shouldn't a Python list or a
2963Numeric Python array just work normally? We'll get to those examples
2964soon enough. For now, think of this example as an illustration of
2965what can be done without having to rely on any of the more advanced
2966customization features.
2967</p>
2968
2969<H3><a name="Python_nn43"></a>26.6.3 Class extension with %extend</H3>
2970
2971
2972<p>
2973One of the more interesting features of SWIG is that it can extend
2974structures and classes with new methods--at least in the Python interface.
2975Here is a simple example:
2976</p>
2977
2978<div class="code">
2979<pre>
2980%module example
2981%{
2982#include "someheader.h"
2983%}
2984
2985struct Vector {
2986 double x,y,z;
2987};
2988
2989%extend Vector {
2990 char *__str__() {
2991 static char tmp[1024];
2992 sprintf(tmp,"Vector(%g,%g,%g)", self-&gt;x,self-&gt;y,self-&gt;z);
2993 return tmp;
2994 }
2995 Vector(double x, double y, double z) {
2996 Vector *v = (Vector *) malloc(sizeof(Vector));
2997 v-&gt;x = x;
2998 v-&gt;y = y;
2999 v-&gt;z = z;
3000 return v;
3001 }
3002};
3003</pre>
3004</div>
3005
3006<p>
3007Now, in Python
3008</p>
3009
3010<div class="targetlang">
3011<pre>
3012&gt;&gt;&gt; v = example.Vector(2,3,4)
3013&gt;&gt;&gt; print v
3014Vector(2,3,4)
3015&gt;&gt;&gt;
3016</pre>
3017</div>
3018
3019<p>
3020<tt>%extend</tt> can be used for many more tasks than this.
3021For example, if you wanted to overload a Python operator, you might do this:
3022</p>
3023
3024<div class="code">
3025<pre>
3026%extend Vector {
3027 Vector __add__(Vector *other) {
3028 Vector v;
3029 v.x = self-&gt;x + other-&gt;x;
3030 v.y = self-&gt;y + other-&gt;y;
3031 v.z = self-&gt;z + other-&gt;z;
3032 return v;
3033 }
3034};
3035</pre>
3036</div>
3037
3038<p>
3039Use it like this:
3040</p>
3041
3042<div class="targetlang">
3043<pre>
3044&gt;&gt;&gt; import example
3045&gt;&gt;&gt; v = example.Vector(2,3,4)
3046&gt;&gt;&gt; w = example.Vector(10,11,12)
3047&gt;&gt;&gt; print v+w
3048Vector(12,14,16)
3049&gt;&gt;&gt;
3050</pre>
3051</div>
3052
3053<p>
3054<tt>%extend</tt> works with both C and C++ code. It does not modify the underlying object
3055in any way---the extensions only show up in the Python interface.
3056</p>
3057
3058<H3><a name="Python_nn44"></a>26.6.4 Exception handling with %exception</H3>
3059
3060
3061<p>
3062If a C or C++ function throws an error, you may want to convert that error into a Python
3063exception. To do this, you can use the <tt>%exception</tt> directive. <tt>%exception</tt>
3064simply lets you rewrite part of the generated wrapper code to include an error check.
3065</p>
3066
3067<p>
3068In C, a function often indicates an error by returning a status code (a negative number
3069or a NULL pointer perhaps). Here is a simple example of how you might handle that:
3070</p>
3071
3072<div class="code">
3073<pre>
3074%exception malloc {
3075 $action
3076 if (!result) {
3077 PyErr_SetString(PyExc_MemoryError,"Not enough memory");
3078 return NULL;
3079 }
3080}
3081void *malloc(size_t nbytes);
3082</pre>
3083</div>
3084
3085<p>
3086In Python,
3087</p>
3088
3089<div class="targetlang">
3090<pre>
3091&gt;&gt;&gt; a = example.malloc(2000000000)
3092Traceback (most recent call last):
3093 File "&lt;stdin&gt;", line 1, in ?
3094MemoryError: Not enough memory
3095&gt;&gt;&gt;
3096</pre>
3097</div>
3098
3099<p>
3100If a library provides some kind of general error handling framework, you can also use
3101that. For example:
3102</p>
3103
3104<div class="code">
3105<pre>
3106%exception {
3107 $action
3108 if (err_occurred()) {
3109 PyErr_SetString(PyExc_RuntimeError, err_message());
3110 return NULL;
3111 }
3112}
3113</pre>
3114</div>
3115
3116<p>
3117No declaration name is given to <tt>%exception</tt>, it is applied to all wrapper functions.
3118</p>
3119
3120<p>
3121C++ exceptions are also easy to handle. For example, you can write code like this:
3122</p>
3123
3124<div class="code">
3125<pre>
3126%exception getitem {
3127 try {
3128 $action
3129 } catch (std::out_of_range &amp;e) {
3130 PyErr_SetString(PyExc_IndexError, const_cast&lt;char*&gt;(e.what()));
3131 return NULL;
3132 }
3133}
3134
3135class Base {
3136public:
3137 Foo *getitem(int index); // Exception handled added
3138 ...
3139};
3140</pre>
3141</div>
3142
3143<p>
3144When raising a Python exception from C, use the <tt>PyErr_SetString()</tt>
3145function as shown above. The following exception types can be used as the first argument.
3146</p>
3147
3148<div class="code">
3149<pre>
3150PyExc_ArithmeticError
3151PyExc_AssertionError
3152PyExc_AttributeError
3153PyExc_EnvironmentError
3154PyExc_EOFError
3155PyExc_Exception
3156PyExc_FloatingPointError
3157PyExc_ImportError
3158PyExc_IndexError
3159PyExc_IOError
3160PyExc_KeyError
3161PyExc_KeyboardInterrupt
3162PyExc_LookupError
3163PyExc_MemoryError
3164PyExc_NameError
3165PyExc_NotImplementedError
3166PyExc_OSError
3167PyExc_OverflowError
3168PyExc_RuntimeError
3169PyExc_StandardError
3170PyExc_SyntaxError
3171PyExc_SystemError
3172PyExc_TypeError
3173PyExc_UnicodeError
3174PyExc_ValueError
3175PyExc_ZeroDivisionError
3176</pre>
3177</div>
3178
3179<p>
3180The language-independent <tt>exception.i</tt> library file can also be used
3181to raise exceptions. See the <a href="Library.html#Library">SWIG Library</a> chapter.
3182</p>
3183
3184<H2><a name="Python_nn45"></a>26.7 Tips and techniques</H2>
3185
3186
3187<p>
3188Although SWIG is largely automatic, there are certain types of wrapping problems that
3189require additional user input. Examples include dealing with output parameters,
3190strings, binary data, and arrays. This chapter discusses the common techniques for
3191solving these problems.
3192</p>
3193
3194<H3><a name="Python_nn46"></a>26.7.1 Input and output parameters</H3>
3195
3196
3197<p>
3198A common problem in some C programs is handling parameters passed as simple pointers. For
3199example:
3200</p>
3201
3202<div class="code">
3203<pre>
3204void add(int x, int y, int *result) {
3205 *result = x + y;
3206}
3207</pre>
3208</div>
3209
3210<p>
3211or perhaps
3212</p>
3213
3214<div class="code">
3215<pre>
3216int sub(int *x, int *y) {
3217 return *x-*y;
3218}
3219</pre>
3220</div>
3221
3222<p>
3223The easiest way to handle these situations is to use the <tt>typemaps.i</tt> file. For example:
3224</p>
3225
3226<div class="code">
3227<pre>
3228%module example
3229%include "typemaps.i"
3230
3231void add(int, int, int *OUTPUT);
3232int sub(int *INPUT, int *INPUT);
3233</pre>
3234</div>
3235
3236<p>
3237In Python, this allows you to pass simple values. For example:
3238</p>
3239
3240<div class="targetlang">
3241<pre>
3242&gt;&gt;&gt; a = add(3,4)
3243&gt;&gt;&gt; print a
32447
3245&gt;&gt;&gt; b = sub(7,4)
3246&gt;&gt;&gt; print b
32473
3248&gt;&gt;&gt;
3249</pre>
3250</div>
3251
3252<p>
3253Notice how the <tt>INPUT</tt> parameters allow integer values to be passed instead of pointers
3254and how the <tt>OUTPUT</tt> parameter creates a return result.
3255</p>
3256
3257<p>
3258If you don't want to use the names <tt>INPUT</tt> or <tt>OUTPUT</tt>, use the <tt>%apply</tt>
3259directive. For example:
3260</p>
3261
3262<div class="code">
3263<pre>
3264%module example
3265%include "typemaps.i"
3266
3267%apply int *OUTPUT { int *result };
3268%apply int *INPUT { int *x, int *y};
3269
3270void add(int x, int y, int *result);
3271int sub(int *x, int *y);
3272</pre>
3273</div>
3274
3275<p>
3276If a function mutates one of its parameters like this,
3277</p>
3278
3279<div class="code">
3280<pre>
3281void negate(int *x) {
3282 *x = -(*x);
3283}
3284</pre>
3285</div>
3286
3287<p>
3288you can use <tt>INOUT</tt> like this:
3289</p>
3290
3291<div class="code">
3292<pre>
3293%include "typemaps.i"
3294...
3295void negate(int *INOUT);
3296</pre>
3297</div>
3298
3299<p>
3300In Python, a mutated parameter shows up as a return value. For example:
3301</p>
3302
3303<div class="targetlang">
3304<pre>
3305&gt;&gt;&gt; a = negate(3)
3306&gt;&gt;&gt; print a
3307-3
3308&gt;&gt;&gt;
3309</pre>
3310</div>
3311
3312<p>
3313Note: Since most primitive Python objects are immutable, it is not possible to
3314perform in-place modification of a Python object passed as a parameter.
3315</p>
3316
3317<p>
3318The most common use of these special typemap rules is to handle functions that
3319return more than one value. For example, sometimes a function returns a result
3320as well as a special error code:
3321</p>
3322
3323<div class="code">
3324<pre>
3325/* send message, return number of bytes sent, along with success code */
3326int send_message(char *text, int len, int *success);
3327</pre>
3328</div>
3329
3330<p>
3331To wrap such a function, simply use the <tt>OUTPUT</tt> rule above. For example:
3332</p>
3333
3334<div class="code">
3335<pre>
3336%module example
3337%include "typemaps.i"
3338%apply int *OUTPUT { int *success };
3339...
3340int send_message(char *text, int *success);
3341</pre>
3342</div>
3343
3344<p>
3345When used in Python, the function will return multiple values.
3346</p>
3347
3348<div class="targetlang">
3349<pre>
3350bytes, success = send_message("Hello World")
3351if not success:
3352 print "Whoa!"
3353else:
3354 print "Sent", bytes
3355</pre>
3356</div>
3357
3358<p>
3359Another common use of multiple return values are in query functions. For example:
3360</p>
3361
3362<div class="code">
3363<pre>
3364void get_dimensions(Matrix *m, int *rows, int *columns);
3365</pre>
3366</div>
3367
3368<p>
3369To wrap this, you might use the following:
3370</p>
3371
3372<div class="code">
3373<pre>
3374%module example
3375%include "typemaps.i"
3376%apply int *OUTPUT { int *rows, int *columns };
3377...
3378void get_dimensions(Matrix *m, int *rows, *columns);
3379</pre>
3380</div>
3381
3382<p>
3383Now, in Python:
3384</p>
3385
3386<div class="targetlang">
3387<pre>
3388&gt;&gt;&gt; r,c = get_dimensions(m)
3389</pre>
3390</div>
3391
3392<p>
3393Be aware that the primary purpose of the <tt>typemaps.i</tt> file is to support primitive datatypes.
3394Writing a function like this
3395</p>
3396
3397<div class="code">
3398<pre>
3399void foo(Bar *OUTPUT);
3400</pre>
3401</div>
3402
3403<p>
3404may not have the intended effect since <tt>typemaps.i</tt> does not define an OUTPUT rule for <tt>Bar</tt>.
3405</p>
3406
3407<H3><a name="Python_nn47"></a>26.7.2 Simple pointers</H3>
3408
3409
3410<p>
3411If you must work with simple pointers such as <tt>int *</tt> or <tt>double *</tt> and you don't want to use
3412<tt>typemaps.i</tt>, consider using the <tt>cpointer.i</tt> library file. For example:
3413</p>
3414
3415<div class="code">
3416<pre>
3417%module example
3418%include "cpointer.i"
3419
3420%inline %{
3421extern void add(int x, int y, int *result);
3422%}
3423
3424%pointer_functions(int, intp);
3425</pre>
3426</div>
3427
3428<p>
3429The <tt>%pointer_functions(type,name)</tt> macro generates five helper functions that can be used to create,
3430destroy, copy, assign, and dereference a pointer. In this case, the functions are as follows:
3431</p>
3432
3433<div class="code">
3434<pre>
3435int *new_intp();
3436int *copy_intp(int *x);
3437void delete_intp(int *x);
3438void intp_assign(int *x, int value);
3439int intp_value(int *x);
3440</pre>
3441</div>
3442
3443<p>
3444In Python, you would use the functions like this:
3445</p>
3446
3447<div class="targetlang">
3448<pre>
3449&gt;&gt;&gt; result = new_intp()
3450&gt;&gt;&gt; print result
3451_108fea8_p_int
3452&gt;&gt;&gt; add(3,4,result)
3453&gt;&gt;&gt; print intp_value(result)
34547
3455&gt;&gt;&gt;
3456</pre>
3457</div>
3458
3459<p>
3460If you replace <tt>%pointer_functions()</tt> by <tt>%pointer_class(type,name)</tt>, the interface is more class-like.
3461</p>
3462
3463<div class="targetlang">
3464<pre>
3465&gt;&gt;&gt; result = intp()
3466&gt;&gt;&gt; add(3,4,result)
3467&gt;&gt;&gt; print result.value()
34687
3469</pre>
3470</div>
3471
3472<p>
3473See the <a href="Library.html#Library">SWIG Library</a> chapter for further details.
3474</p>
3475
3476<H3><a name="Python_nn48"></a>26.7.3 Unbounded C Arrays</H3>
3477
3478
3479<p>
3480Sometimes a C function expects an array to be passed as a pointer. For example,
3481</p>
3482
3483<div class="code">
3484<pre>
3485int sumitems(int *first, int nitems) {
3486 int i, sum = 0;
3487 for (i = 0; i &lt; nitems; i++) {
3488 sum += first[i];
3489 }
3490 return sum;
3491}
3492</pre>
3493</div>
3494
3495<p>
3496To wrap this into Python, you need to pass an array pointer as the first argument.
3497A simple way to do this is to use the <tt>carrays.i</tt> library file. For example:
3498</p>
3499
3500<div class="code">
3501<pre>
3502%include "carrays.i"
3503%array_class(int, intArray);
3504</pre>
3505</div>
3506
3507<p>
3508The <tt>%array_class(type, name)</tt> macro creates wrappers for an unbounded array object that
3509can be passed around as a simple pointer like <tt>int *</tt> or <tt>double *</tt>.
3510For instance, you will be able to do this in Python:
3511</p>
3512
3513<div class="targetlang">
3514<pre>
3515&gt;&gt;&gt; a = intArray(10000000) # Array of 10-million integers
3516&gt;&gt;&gt; for i in xrange(10000): # Set some values
3517... a[i] = i
3518&gt;&gt;&gt; sumitems(a,10000)
351949995000
3520&gt;&gt;&gt;
3521</pre>
3522</div>
3523
3524<p>
3525The array "object" created by <tt>%array_class()</tt> does not
3526encapsulate pointers inside a special array object. In fact, there is
3527no bounds checking or safety of any kind (just like in C). Because of
3528this, the arrays created by this library are extremely low-level
3529indeed. You can't iterate over them nor can you even query their
3530length. In fact, any valid memory address can be accessed if you want
3531(negative indices, indices beyond the end of the array, etc.).
3532Needless to say, this approach is not going to suit all applications.
3533On the other hand, this low-level approach is extremely efficient and
3534well suited for applications in which you need to create buffers,
3535package binary data, etc.
3536</p>
3537
3538<H3><a name="Python_nn49"></a>26.7.4 String handling</H3>
3539
3540
3541<p>
3542If a C function has an argument of <tt>char *</tt>, then a Python string
3543can be passed as input. For example:
3544</p>
3545
3546<div class="code">
3547<pre>
3548// C
3549void foo(char *s);
3550</pre>
3551</div>
3552
3553<div class="targetlang">
3554<pre>
3555# Python
3556&gt;&gt;&gt; foo("Hello")
3557</pre>
3558</div>
3559
3560<p>
3561When a Python string is passed as a parameter, the C function receives a pointer to the raw
3562data contained in the string. Since Python strings are immutable, it is illegal
3563for your program to change the value. In fact, doing so will probably crash the Python
3564interpreter.
3565</p>
3566
3567<p>
3568If your program modifies the input parameter or uses it to return data, consider
3569using the <tt>cstring.i</tt> library file described in the <a href="Library.html#Library">SWIG Library</a> chapter.
3570</p>
3571
3572<p>
3573When functions return a <tt>char *</tt>, it is assumed to be a NULL-terminated string.
3574Data is copied into a new Python string and returned.
3575</p>
3576
3577<p>
3578If your program needs to work with binary data, you can use a typemap
3579to expand a Python string into a pointer/length argument pair. As luck would have it,
3580just such a typemap is already defined. Just do this:
3581</p>
3582
3583<div class="code">
3584<pre>
3585%apply (char *STRING, int LENGTH) { (char *data, int size) };
3586...
3587int parity(char *data, int size, int initial);
3588</pre>
3589</div>
3590
3591<p>
3592Now in Python:
3593</p>
3594
3595<div class="targetlang">
3596<pre>
3597&gt;&gt;&gt; parity("e\x09ffss\x00\x00\x01\nx", 0)
3598</pre>
3599</div>
3600
3601<p>
3602If you need to return binary data, you might use the
3603<tt>cstring.i</tt> library file. The <tt>cdata.i</tt> library can
3604also be used to extra binary data from arbitrary pointers.
3605</p>
3606
3607<H3><a name="Python_nn50"></a>26.7.5 Arrays</H3>
3608
3609
3610<H3><a name="Python_nn51"></a>26.7.6 String arrays</H3>
3611
3612
3613<H3><a name="Python_nn52"></a>26.7.7 STL wrappers</H3>
3614
3615
3616<H2><a name="Python_nn53"></a>26.8 Typemaps</H2>
3617
3618
3619<p>
3620This section describes how you can modify SWIG's default wrapping behavior
3621for various C/C++ datatypes using the <tt>%typemap</tt> directive. This
3622is an advanced topic that assumes familiarity with the Python C API as well
3623as the material in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
3624</p>
3625
3626<p>
3627Before proceeding, it should be stressed that typemaps are not a required
3628part of using SWIG---the default wrapping behavior is enough in most cases.
3629Typemaps are only used if you want to change some aspect of the primitive
3630C-Python interface or if you want to elevate your guru status.
3631</p>
3632
3633<H3><a name="Python_nn54"></a>26.8.1 What is a typemap?</H3>
3634
3635
3636<p>
3637A typemap is nothing more than a code generation rule that is attached to
3638a specific C datatype. For example, to convert integers from Python to C,
3639you might define a typemap like this:
3640</p>
3641
3642<div class="code"><pre>
3643%module example
3644
3645%typemap(in) int {
3646 $1 = (int) PyLong_AsLong($input);
3647 printf("Received an integer : %d\n",$1);
3648}
3649%inline %{
3650extern int fact(int n);
3651%}
3652</pre></div>
3653
3654<p>
3655Typemaps are always associated with some specific aspect of code generation.
3656In this case, the "in" method refers to the conversion of input arguments
3657to C/C++. The datatype <tt>int</tt> is the datatype to which the typemap
3658will be applied. The supplied C code is used to convert values. In this
3659code a number of special variable prefaced by a <tt>$</tt> are used. The
3660<tt>$1</tt> variable is placeholder for a local variable of type <tt>int</tt>.
3661The <tt>$input</tt> variable is the input object of type <tt>PyObject *</tt>.
3662</p>
3663
3664<p>
3665When this example is compiled into a Python module, it operates as follows:
3666</p>
3667
3668<div class="targetlang"><pre>
3669&gt;&gt;&gt; from example import *
3670&gt;&gt;&gt; fact(6)
3671Received an integer : 6
3672720
3673</pre></div>
3674
3675<p>
3676In this example, the typemap is applied to all occurrences of the <tt>int</tt> datatype.
3677You can refine this by supplying an optional parameter name. For example:
3678</p>
3679
3680<div class="code"><pre>
3681%module example
3682
3683%typemap(in) int nonnegative {
3684 $1 = (int) PyLong_AsLong($input);
3685 if ($1 &lt; 0) {
3686 PyErr_SetString(PyExc_ValueError,"Expected a nonnegative value.");
3687 return NULL;
3688 }
3689}
3690%inline %{
3691extern int fact(int nonnegative);
3692%}
3693</pre></div>
3694
3695<p>
3696In this case, the typemap code is only attached to arguments that exactly match <tt>int nonnegative</tt>.
3697</p>
3698
3699<p>
3700The application of a typemap to specific datatypes and argument names involves
3701more than simple text-matching--typemaps are fully integrated into the
3702SWIG C++ type-system. When you define a typemap for <tt>int</tt>, that typemap
3703applies to <tt>int</tt> and qualified variations such as <tt>const int</tt>. In addition,
3704the typemap system follows <tt>typedef</tt> declarations. For example:
3705</p>
3706
3707<div class="code">
3708<pre>
3709%typemap(in) int n {
3710 $1 = (int) PyLong_AsLong($input);
3711 printf("n = %d\n",$1);
3712}
3713%inline %{
3714typedef int Integer;
3715extern int fact(Integer n); // Above typemap is applied
3716%}
3717</pre>
3718</div>
3719
3720<p>
3721Typemaps can also be defined for groups of consecutive arguments. For example:
3722</p>
3723
3724<div class="code">
3725<pre>
3726%typemap(in) (char *str, int len) {
3727 $1 = PyString_AsString($input);
3728 $2 = PyString_Size($input);
3729};
3730
3731int count(char c, char *str, int len);
3732</pre>
3733</div>
3734
3735<p>
3736When a multi-argument typemap is defined, the arguments are always handled as a single
3737Python object. This allows the function to be used like this (notice how the length
3738parameter is omitted):
3739</p>
3740
3741<div class="targetlang">
3742<pre>
3743&gt;&gt;&gt; example.count('e','Hello World')
37441
3745&gt;&gt;&gt;
3746</pre>
3747</div>
3748
3749<H3><a name="Python_nn55"></a>26.8.2 Python typemaps</H3>
3750
3751
3752<p>
3753The previous section illustrated an "in" typemap for converting Python objects to C.
3754A variety of different typemap methods are defined by the Python module. For example,
3755to convert a C integer back into a Python object, you might define an "out" typemap
3756like this:
3757</p>
3758
3759<div class="code">
3760<pre>
3761%typemap(out) int {
3762 $result = PyInt_FromLong((long) $1);
3763}
3764</pre>
3765</div>
3766
3767<p>
3768A detailed list of available methods can be found in the "<a
3769href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
3770</p>
3771
3772<p>
3773However, the best source of typemap information (and examples) is
3774probably the Python module itself. In fact, all of SWIG's default
3775type handling is defined by typemaps. You can view these typemaps by
3776looking at the files in the SWIG library. Just take into account that
3777in the latest versions of swig (1.3.22+), the library files are not
3778very pristine clear for the casual reader, as they used to be. The
3779extensive use of macros and other ugly techniques in the latest
3780version produce a very powerful and consistent python typemap library,
3781but at the cost of simplicity and pedagogic value.
3782</p>
3783
3784<p>
3785To learn how to write a simple or your first typemap, you better take
3786a look at the SWIG library version 1.3.20 or so.
3787</p>
3788
3789
3790<H3><a name="Python_nn56"></a>26.8.3 Typemap variables</H3>
3791
3792
3793<p>
3794Within typemap code, a number of special variables prefaced with a <tt>$</tt> may appear.
3795A full list of variables can be found in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
3796This is a list of the most common variables:
3797</p>
3798
3799<p>
3800<tt>$1</tt>
3801</p>
3802
3803<div class="indent">
3804A C local variable corresponding to the actual type specified in the
3805<tt>%typemap</tt> directive. For input values, this is a C local variable
3806that's supposed to hold an argument value. For output values, this is
3807the raw result that's supposed to be returned to Python.
3808</div>
3809
3810<p>
3811<tt>$input</tt>
3812</p>
3813
3814<div class="indent">
3815 A <tt>PyObject *</tt> holding a raw Python object with an argument or variable value.
3816</div>
3817
3818<p>
3819<tt>$result</tt>
3820</p>
3821
3822<div class="indent">
3823A <tt>PyObject *</tt> that holds the result to be returned to Python.
3824</div>
3825
3826<p>
3827<tt>$1_name</tt>
3828</p>
3829
3830<div class="indent">
3831The parameter name that was matched.
3832</div>
3833
3834<p>
3835<tt>$1_type</tt>
3836</p>
3837
3838<div class="indent">
3839The actual C datatype matched by the typemap.
3840</div>
3841
3842<p>
3843<tt>$1_ltype</tt>
3844</p>
3845
3846<div class="indent">
3847An assignable version of the datatype matched by the typemap (a type that can appear on the left-hand-side of
3848a C assignment operation). This type is stripped of qualifiers and may be an altered version of <tt>$1_type</tt>.
3849All arguments and local variables in wrapper functions are declared using this type so that their values can be
3850properly assigned.
3851</div>
3852
3853<p>
3854<tt>$symname</tt>
3855</p>
3856
3857<div class="indent">
3858The Python name of the wrapper function being created.
3859</div>
3860
3861<H3><a name="Python_nn57"></a>26.8.4 Useful Python Functions</H3>
3862
3863
3864<p>
3865When you write a typemap, you usually have to work directly with Python objects.
3866The following functions may prove to be useful.
3867</p>
3868
3869<p>
3870<b>Python Integer Functions</b>
3871</p>
3872
3873<div class="code">
3874<pre>
3875PyObject *PyInt_FromLong(long l);
3876long PyInt_AsLong(PyObject *);
3877int PyInt_Check(PyObject *);
3878</pre>
3879</div>
3880
3881<p>
3882<b>Python Floating Point Functions</b>
3883</p>
3884
3885<div class="code">
3886<pre>
3887PyObject *PyFloat_FromDouble(double);
3888double PyFloat_AsDouble(PyObject *);
3889int PyFloat_Check(PyObject *);
3890</pre>
3891</div>
3892
3893<p>
3894<b>Python String Functions</b>
3895</p>
3896
3897<div class="code">
3898<pre>
3899PyObject *PyString_FromString(char *);
3900PyObject *PyString_FromStringAndSize(char *, lint len);
3901int PyString_Size(PyObject *);
3902char *PyString_AsString(PyObject *);
3903int PyString_Check(PyObject *);
3904</pre>
3905</div>
3906
3907<p>
3908<b>Python List Functions</b>
3909</p>
3910
3911<div class="code">
3912<pre>
3913PyObject *PyList_New(int size);
3914int PyList_Size(PyObject *list);
3915PyObject *PyList_GetItem(PyObject *list, int i);
3916int PyList_SetItem(PyObject *list, int i, PyObject *item);
3917int PyList_Insert(PyObject *list, int i, PyObject *item);
3918int PyList_Append(PyObject *list, PyObject *item);
3919PyObject *PyList_GetSlice(PyObject *list, int i, int j);
3920int PyList_SetSlice(PyObject *list, int i, int , PyObject *list2);
3921int PyList_Sort(PyObject *list);
3922int PyList_Reverse(PyObject *list);
3923PyObject *PyList_AsTuple(PyObject *list);
3924int PyList_Check(PyObject *);
3925</pre>
3926</div>
3927
3928<p>
3929<b>Python Tuple Functions</b>
3930</p>
3931
3932<div class="code">
3933<pre>
3934PyObject *PyTuple_New(int size);
3935int PyTuple_Size(PyObject *);
3936PyObject *PyTuple_GetItem(PyObject *, int i);
3937int PyTuple_SetItem(PyObject *, int i, pyObject *item);
3938PyObject *PyTuple_GetSlice(PyObject *t, int i, int j);
3939int PyTuple_Check(PyObject *);
3940</pre>
3941</div>
3942
3943<p>
3944<b>Python Dictionary Functions</b>
3945</p>
3946
3947<div class="code">
3948<pre>
3949write me
3950</pre>
3951</div>
3952
3953<p>
3954<b>Python File Conversion Functions</b>
3955</p>
3956
3957<div class="code">
3958<pre>
3959PyObject *PyFile_FromFile(FILE *f);
3960FILE *PyFile_AsFile(PyObject *);
3961int PyFile_Check(PyObject *);
3962</pre>
3963</div>
3964
3965<p>
3966<b>Abstract Object Interface</b>
3967</p>
3968
3969<div class="code">
3970<pre>
3971write me
3972</pre>
3973</div>
3974
3975<H2><a name="Python_nn58"></a>26.9 Typemap Examples</H2>
3976
3977
3978<p>
3979This section includes a few examples of typemaps. For more examples, you
3980might look at the files "<tt>python.swg</tt>" and "<tt>typemaps.i</tt>" in
3981the SWIG library.
3982</p>
3983
3984<H3><a name="Python_nn59"></a>26.9.1 Converting Python list to a char ** </H3>
3985
3986
3987<p>
3988A common problem in many C programs is the processing of command line
3989arguments, which are usually passed in an array of NULL terminated
3990strings. The following SWIG interface file allows a Python list
3991object to be used as a <tt>char **</tt> object.
3992</p>
3993
3994<div class="code"><pre>
3995%module argv
3996
3997// This tells SWIG to treat char ** as a special case
3998%typemap(in) char ** {
3999 /* Check if is a list */
4000 if (PyList_Check($input)) {
4001 int size = PyList_Size($input);
4002 int i = 0;
4003 $1 = (char **) malloc((size+1)*sizeof(char *));
4004 for (i = 0; i &lt; size; i++) {
4005 PyObject *o = PyList_GetItem($input,i);
4006 if (PyString_Check(o))
4007 $1[i] = PyString_AsString(PyList_GetItem($input,i));
4008 else {
4009 PyErr_SetString(PyExc_TypeError,"list must contain strings");
4010 free($1);
4011 return NULL;
4012 }
4013 }
4014 $1[i] = 0;
4015 } else {
4016 PyErr_SetString(PyExc_TypeError,"not a list");
4017 return NULL;
4018 }
4019}
4020
4021// This cleans up the char ** array we malloc'd before the function call
4022%typemap(freearg) char ** {
4023 free((char *) $1);
4024}
4025
4026// Now a test function
4027%inline %{
4028int print_args(char **argv) {
4029 int i = 0;
4030 while (argv[i]) {
4031 printf("argv[%d] = %s\n", i,argv[i]);
4032 i++;
4033 }
4034 return i;
4035}
4036%}
4037
4038</pre></div>
4039
4040<p>
4041When this module is compiled, the wrapped C function now operates as
4042follows :
4043</p>
4044
4045<div class="targetlang"><pre>
4046&gt;&gt;&gt; from argv import *
4047&gt;&gt;&gt; print_args(["Dave","Mike","Mary","Jane","John"])
4048argv[0] = Dave
4049argv[1] = Mike
4050argv[2] = Mary
4051argv[3] = Jane
4052argv[4] = John
40535
4054</pre></div>
4055
4056<p>
4057In the example, two different typemaps are used. The "in" typemap is
4058used to receive an input argument and convert it to a C array. Since dynamic
4059memory allocation is used to allocate memory for the array, the
4060"freearg" typemap is used to later release this memory after the execution of
4061the C function.
4062</p>
4063
4064<H3><a name="Python_nn60"></a>26.9.2 Expanding a Python object into multiple arguments</H3>
4065
4066
4067<p>
4068Suppose that you had a collection of C functions with arguments
4069such as the following:
4070</p>
4071
4072<div class="code">
4073<pre>
4074int foo(int argc, char **argv);
4075</pre>
4076</div>
4077
4078<p>
4079In the previous example, a typemap was written to pass a Python list as the <tt>char **argv</tt>. This
4080allows the function to be used from Python as follows:
4081</p>
4082
4083<div class="targetlang">
4084<pre>
4085&gt;&gt;&gt; foo(4, ["foo","bar","spam","1"])
4086</pre>
4087</div>
4088
4089<p>
4090Although this works, it's a little awkward to specify the argument count. To fix this, a multi-argument
4091typemap can be defined. This is not very difficult--you only have to make slight modifications to the
4092previous example:
4093</p>
4094
4095<div class="code">
4096<pre>
4097%typemap(in) (int argc, char **argv) {
4098 /* Check if is a list */
4099 if (PyList_Check($input)) {
4100 int i;
4101 $1 = PyList_Size($input);
4102 $2 = (char **) malloc(($1+1)*sizeof(char *));
4103 for (i = 0; i &lt; $1; i++) {
4104 PyObject *o = PyList_GetItem($input,i);
4105 if (PyString_Check(o))
4106 $2[i] = PyString_AsString(PyList_GetItem($input,i));
4107 else {
4108 PyErr_SetString(PyExc_TypeError,"list must contain strings");
4109 free($2);
4110 return NULL;
4111 }
4112 }
4113 $2[i] = 0;
4114 } else {
4115 PyErr_SetString(PyExc_TypeError,"not a list");
4116 return NULL;
4117 }
4118}
4119
4120%typemap(freearg) (int argc, char **argv) {
4121 free((char *) $2);
4122}
4123</pre>
4124</div>
4125
4126<p>
4127When writing a multiple-argument typemap, each of the types is referenced by a variable such
4128as <tt>$1</tt> or <tt>$2</tt>. The typemap code simply fills in the appropriate values from
4129the supplied Python object.
4130</p>
4131
4132<p>
4133With the above typemap in place, you will find it no longer necessary
4134to supply the argument count. This is automatically set by the typemap code. For example:
4135</p>
4136
4137<div class="targetlang">
4138<pre>
4139&gt;&gt;&gt; foo(["foo","bar","spam","1"])
4140</pre>
4141</div>
4142
4143<H3><a name="Python_nn61"></a>26.9.3 Using typemaps to return arguments</H3>
4144
4145
4146<p>
4147A common problem in some C programs is that values may be returned in
4148arguments rather than in the return value of a function. For example:
4149</p>
4150
4151<div class="code"><pre>
4152/* Returns a status value and two values in out1 and out2 */
4153int spam(double a, double b, double *out1, double *out2) {
4154 ... Do a bunch of stuff ...
4155 *out1 = result1;
4156 *out2 = result2;
4157 return status;
4158};
4159
4160</pre></div>
4161
4162<p>
4163A typemap can be used to handle this case as follows :
4164</p>
4165
4166<div class="code"><pre>
4167%module outarg
4168
4169// This tells SWIG to treat an double * argument with name 'OutValue' as
4170// an output value. We'll append the value to the current result which
4171// is guaranteed to be a List object by SWIG.
4172
4173%typemap(argout) double *OutValue {
4174 PyObject *o, *o2, *o3;
4175 o = PyFloat_FromDouble(*$1);
4176 if ((!$result) || ($result == Py_None)) {
4177 $result = o;
4178 } else {
4179 if (!PyTuple_Check($result)) {
4180 PyObject *o2 = $result;
4181 $result = PyTuple_New(1);
4182 PyTuple_SetItem(target,0,o2);
4183 }
4184 o3 = PyTuple_New(1);
4185 PyTuple_SetItem(o3,0,o);
4186 o2 = $result;
4187 $result = PySequence_Concat(o2,o3);
4188 Py_DECREF(o2);
4189 Py_DECREF(o3);
4190 }
4191}
4192
4193int spam(double a, double b, double *OutValue, double *OutValue);
4194
4195</pre></div>
4196
4197<p>
4198The typemap works as follows. First, a check is made to see if any previous result
4199exists. If so, it is turned into a tuple and the new output value is concatenated to it.
4200Otherwise, the result is returned normally. For the sample function <tt>spam()</tt>, there
4201are three output values--meaning that the function will return a 3-tuple of the results.
4202</p>
4203
4204<p>
4205As written, the function must accept 4 arguments as input values,
4206last two being pointers to doubles. If these arguments are only used to hold output values (and have
4207no meaningful input value), an additional typemap can be written. For example:
4208</p>
4209
4210<div class="code"><pre>
4211%typemap(in,numinputs=0) double *OutValue(double temp) {
4212 $1 = &amp;temp;
4213}
4214
4215</pre></div>
4216
4217<p>
4218By specifying numinputs=0, the input value is ignored. However, since the argument still has to be set to
4219some meaningful value before calling C, it is set to point to a local variable <tt>temp</tt>. When the function
4220stores its output value, it will simply be placed in this local variable. As a result, the
4221function can now be used as follows:
4222</p>
4223
4224<div class="targetlang"><pre>
4225&gt;&gt;&gt; a = spam(4,5)
4226&gt;&gt;&gt; print a
4227(0, 2.45, 5.0)
4228&gt;&gt;&gt; x,y,z = spam(4,5)
4229&gt;&gt;&gt;
4230</pre></div>
4231
4232<H3><a name="Python_nn62"></a>26.9.4 Mapping Python tuples into small arrays</H3>
4233
4234
4235<p>
4236In some applications, it is sometimes desirable to pass small arrays
4237of numbers as arguments. For example :
4238</p>
4239
4240<div class="code"><pre>
4241extern void set_direction(double a[4]); // Set direction vector
4242</pre></div>
4243
4244<p>
4245This too, can be handled used typemaps as follows :
4246</p>
4247
4248<div class="code"><pre>
4249// Grab a 4 element array as a Python 4-tuple
4250%typemap(in) double[4](double temp[4]) { // temp[4] becomes a local variable
4251 int i;
4252 if (PyTuple_Check($input)) {
4253 if (!PyArg_ParseTuple($input,"dddd",temp,temp+1,temp+2,temp+3)) {
4254 PyErr_SetString(PyExc_TypeError,"tuple must have 4 elements");
4255 return NULL;
4256 }
4257 $1 = &amp;temp[0];
4258 } else {
4259 PyErr_SetString(PyExc_TypeError,"expected a tuple.");
4260 return NULL;
4261 }
4262}
4263
4264</pre></div>
4265
4266<p>
4267This allows our <tt>set_direction</tt> function to be called from
4268Python as follows :
4269</p>
4270
4271<div class="targetlang"><pre>
4272&gt;&gt;&gt; set_direction((0.5,0.0,1.0,-0.25))
4273</pre></div>
4274
4275<p>
4276Since our mapping copies the contents of a Python tuple into a C
4277array, such an approach would not be recommended for huge arrays, but
4278for small structures, this approach works fine.
4279</p>
4280
4281<H3><a name="Python_nn63"></a>26.9.5 Mapping sequences to C arrays</H3>
4282
4283
4284<p>
4285Suppose that you wanted to generalize the previous example to handle C
4286arrays of different sizes. To do this, you might write a typemap as follows:
4287</p>
4288
4289<div class="code"><pre>
4290// Map a Python sequence into any sized C double array
4291%typemap(in) double[ANY](double temp[$1_dim0]) {
4292 int i;
4293 if (!PySequence_Check($input)) {
4294 PyErr_SetString(PyExc_TypeError,"Expecting a sequence");
4295 return NULL;
4296 }
4297 if (PyObject_Length($input) != $1_dim0) {
4298 PyErr_SetString(PyExc_ValueError,"Expecting a sequence with $1_dim0 elements");
4299 return NULL;
4300 }
4301 for (i =0; i &lt; $1_dim0; i++) {
4302 PyObject *o = PySequence_GetItem($input,i);
4303 if (!PyFloat_Check(o)) {
4304 PyErr_SetString(PyExc_ValueError,"Expecting a sequence of floats");
4305 return NULL;
4306 }
4307 temp[i] = PyFloat_AsDouble(o);
4308 }
4309 $1 = &amp;temp[0];
4310}
4311</pre>
4312</div>
4313
4314<p>
4315In this case, the variable <tt>$1_dim0</tt> is expanded to match the
4316array dimensions actually used in the C code. This allows the typemap
4317to be applied to types such as:
4318</p>
4319
4320<div class="code">
4321<pre>
4322void foo(double x[10]);
4323void bar(double a[4], double b[8]);
4324</pre>
4325</div>
4326
4327<p>
4328Since the above typemap code gets inserted into every wrapper function where used, it might make sense
4329to use a helper function instead. This will greatly reduce the amount of wrapper code. For example:
4330</p>
4331
4332<div class="code">
4333<pre>
4334%{
4335static int convert_darray(PyObject *input, double *ptr, int size) {
4336 int i;
4337 if (!PySequence_Check(input)) {
4338 PyErr_SetString(PyExc_TypeError,"Expecting a sequence");
4339 return 0;
4340 }
4341 if (PyObject_Length(input) != size) {
4342 PyErr_SetString(PyExc_ValueError,"Sequence size mismatch");
4343 return 0;
4344 }
4345 for (i =0; i &lt; size; i++) {
4346 PyObject *o = PySequence_GetItem(input,i);
4347 if (!PyFloat_Check(o)) {
4348 PyErr_SetString(PyExc_ValueError,"Expecting a sequence of floats");
4349 return 0;
4350 }
4351 ptr[i] = PyFloat_AsDouble(o);
4352 }
4353 return 1;
4354}
4355%}
4356
4357%typemap(in) double [ANY](double temp[$1_dim0]) {
4358 if (!convert_darray($input,temp,$1_dim0))) {
4359 return NULL;
4360 }
4361 $1 = &amp;temp[0];
4362}
4363</pre>
4364</div>
4365
4366<H3><a name="Python_nn64"></a>26.9.6 Pointer handling</H3>
4367
4368
4369<p>
4370Occasionally, it might be necessary to convert pointer values that have
4371been stored using the SWIG typed-pointer representation. Since there are
4372several ways in which pointers can be represented, the following two
4373functions are used to safely perform this conversion:
4374</p>
4375
4376<p>
4377<tt>
4378int SWIG_ConvertPtr(PyObject *obj, void **ptr, swig_type_info *ty, int flags)</tt>
4379</p>
4380
4381<div class="indent">
4382Converts a Python object <tt>obj</tt> to a C pointer. The result of the conversion is placed
4383into the pointer located at <tt>ptr</tt>. <tt>ty</tt> is a SWIG type descriptor structure.
4384<tt>flags</tt> is used to handle error checking and other aspects of conversion. It is the
4385bitwise-or of several flag values including <tt>SWIG_POINTER_EXCEPTION</tt> and <tt>SWIG_POINTER_DISOWN</tt>. The first flag makes the function raise an exception on type error. The second flag additionally
4386steals ownership of an object. Returns 0 on success and -1 on error.
4387</div>
4388
4389<p>
4390<tt>
4391PyObject *Swig_NewPointerObj(void *ptr, swig_type_info *ty, int own)</tt>
4392</p>
4393
4394<div class="indent">
4395Creates a new Python pointer object. <tt>ptr</tt> is the pointer to convert, <tt>ty</tt> is the SWIG type descriptor structure that
4396describes the type, and <tt>own</tt> is a flag that indicates whether or not Python should take ownership of the
4397pointer.
4398</div>
4399
4400<p>
4401Both of these functions require the use of a special SWIG
4402type-descriptor structure. This structure contains information about
4403the mangled name of the datatype, type-equivalence information, as
4404well as information about converting pointer values under C++
4405inheritance. For a type of <tt>Foo *</tt>, the type descriptor structure
4406is usually accessed as follows:
4407</p>
4408
4409<div class="code">
4410<pre>
4411Foo *f;
4412if (SWIG_ConvertPtr($input, (void **) &amp;f, SWIGTYPE_p_Foo, SWIG_POINTER_EXCEPTION) == -1)
4413 return NULL;
4414
4415PyObject *obj;
4416obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
4417</pre>
4418</div>
4419
4420<p>
4421In a typemap, the type descriptor should always be accessed using the special typemap
4422variable <tt>$1_descriptor</tt>. For example:
4423</p>
4424
4425<div class="code">
4426<pre>
4427%typemap(in) Foo * {
4428if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $1_descriptor,SWIG_POINTER_EXCEPTION)) == -1)
4429 return NULL;
4430}
4431</pre>
4432</div>
4433
4434<p>
4435If necessary, the descriptor for any type can be obtained using the <tt>$descriptor()</tt> macro in a typemap.
4436For example:
4437</p>
4438
4439<div class="code">
4440<pre>
4441%typemap(in) Foo * {
4442if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $descriptor(Foo *),
4443 SWIG_POINTER_EXCEPTION)) == -1)
4444 return NULL;
4445}
4446</pre>
4447</div>
4448
4449<p>
4450Although the pointer handling functions are primarily intended for
4451manipulating low-level pointers, both functions are fully aware of
4452Python proxy classes. Specifically,
4453<tt>SWIG_ConvertPtr()</tt> will retrieve a pointer from any object
4454that has a <tt>this</tt> attribute. In addition,
4455<tt>SWIG_NewPointerObj()</tt> can automatically generate a proxy
4456class object (if applicable).
4457</p>
4458
4459
4460
4461<H2><a name="Python_nn65"></a>26.10 Docstring Features</H2>
4462
4463
4464<p>
4465Usign docstrings in Python code is becoming more and more important
4466ans more tools are coming on the scene that take advantage of them,
4467everything from full-blown documentaiton generators to class browsers
4468and popup call-tips in Python-aware IDEs. Given the way that SWIG
4469generates the proxy code by default, your users will normally get
4470something like <tt>"function_name(*args)"</tt> in the popup calltip of
4471their IDE which is next to useless when the real function prototype
4472might be something like this:
4473</p>
4474
4475<div class="code">
4476<pre>
4477bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
4478</pre>
4479</div>
4480
4481<p>
4482The features described in this section make it easy for you to add
4483docstrings to your modules, functions and methods that can then be
4484used by the various tools out there to make the programming experience
4485of your users much simpler.
4486</p>
4487
4488
4489<H3><a name="Python_nn66"></a>26.10.1 Module docstring</H3>
4490
4491
4492<p>
4493Python allows a docstring at the begining of the <tt>.py</tt> file
4494before any other statements, and it is typically used to give a
4495general description of the entire module. SWIG supports this by
4496setting an option of the <tt>%module</tt> directive. For example:
4497</p>
4498
4499<div class="code">
4500<pre>
4501%module(docstring="This is the example module's docstring") example
4502</pre>
4503</div>
4504
4505<p>
4506When you have more than just a line or so then you can retain the easy
4507readability of the <tt>%module</tt> directive by using a macro. For
4508example:
4509</p>
4510
4511<div class="code">
4512<pre>
4513%define DOCSTRING
4514"The `XmlResource` class allows program resources defining menus,
4515layout of controls on a panel, etc. to be loaded from an XML file."
4516%enddef
4517
4518%module(docstring=DOCSTRING) xrc
4519</pre>
4520</div>
4521
4522
4523<H3><a name="Python_nn67"></a>26.10.2 %feature("autodoc")</H3>
4524
4525
4526<p>
4527As alluded to above SWIG will generate all the function and method
4528proxy wrappers with just "*args" (or "*args, **kwargs" if the -keyword
4529option is used) for a parameter list and will then sort out the
4530individual parameters in the C wrapper code. This is nice and simple
4531for the wrapper code, but makes it difficult to be programmer and tool
4532friendly as anyone looking at the <tt>.py</tt> file will not be able
4533to find out anything about the parameters that the fuctions accept.
4534</p>
4535
4536<p>But since SWIG does know everything about the fucntion it is
4537possible to generate a docstring containing the parameter types, names
4538and default values. Since many of the doctring tools are adopting a
4539standard of recognizing if the first thing in the docstring is a
4540function prototype then using that instead of what they found from
4541introspeciton, then life is good once more.
4542
4543<p>SWIG's Python module provides support for the "autodoc" feature,
4544which when attached to a node in the parse tree will cause a docstring
4545to be generated that includes the name of the funciton, parameter
4546names, default values if any, and return type if any. There are also
4547three options for autodoc controlled by the value given to the
4548feature, described below.
4549
4550<H4><a name="Python_nn68"></a>26.10.2.1 %feature("autodoc", "0")</H4>
4551
4552
4553<p>
4554When the "0" option is given then the types of the parameters will
4555<em>not</em> be included in the autodoc string. For example, given
4556this function prototype:
4557</p>
4558
4559<div class="code">
4560<pre>
4561%feature("autodoc", "0");
4562bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
4563</pre>
4564</div>
4565
4566<p>
4567Then Python code like this will be generated:
4568</p>
4569
4570<div class="targetlang">
4571<pre>
4572def function_name(*args, **kwargs):
4573 """function_name(x, y, foo=None, bar=None) -&gt; bool"""
4574 ...
4575</pre>
4576</div>
4577
4578
4579<H4><a name="Python_nn69"></a>26.10.2.2 %feature("autodoc", "1")</H4>
4580
4581
4582<p>
4583When the "1" option is used then the parameter types <em>will</em> be
4584used in the autodoc string. In addition, an atempt is made to
4585simplify the type name such that it makes more sense to the Python
4586user. Pointer, reference and const info is removed,
4587<tt>%rename</tt>'s are evaluated, etc. (This is not always
4588successful, but works most of the time. See the next section for what
4589to do when it doesn't.) Given the example above, then turning on the
4590parameter types with the "1" option will result in Python code like
4591this:
4592</p>
4593
4594<div class="targetlang">
4595<pre>
4596def function_name(*args, **kwargs):
4597 """function_name(int x, int y, Foo foo=None, Bar bar=None) -&gt; bool"""
4598 ...
4599</pre>
4600</div>
4601
4602
4603
4604<H4><a name="Python_nn70"></a>26.10.2.3 %feature("autodoc", "docstring")</H4>
4605
4606
4607<p>
4608Finally, there are times when the automatically generated autodoc
4609string will make no sense for a Python programmer, particularly when a
4610typemap is involved. So if you give an explicit value for the autodoc
4611feature then that string will be used in place of the automatically
4612generated string. For example:
4613</p>
4614
4615<div class="code">
4616<pre>
4617%feature("autodoc", "GetPosition() -&gt; (x, y)") GetPosition;
4618void GetPosition(int* OUTPUT, int* OUTPUT);
4619</pre>
4620</div>
4621
4622
4623<H3><a name="Python_nn71"></a>26.10.3 %feature("docstring")</H3>
4624
4625
4626<p>
4627In addition to the autodoc strings described above, you can also
4628attach any arbitrary descriptive text to a node in the parse tree with
4629the "docstring" feature. When the proxy module is generated then any
4630docstring associated with classes, function or methods are output.
4631If an item already has an autodoc string then it is combined with the
4632docstring and they are output together. If the docstring is all on a
4633single line then it is output like this::
4634</p>
4635
4636<div class="targetlang">
4637<pre>
4638"""This is the docstring"""
4639</pre>
4640</div>
4641
4642<p>
4643Otherwise, to aid readability it is output like this:
4644</p>
4645
4646<div class="targetlang">
4647<pre>
4648"""
4649This is a multi-line docstring
4650with more than one line.
4651"""
4652</pre>
4653</div>
4654
4655<H2><a name="Python_nn72"></a>26.11 Python Packages</H2>
4656
4657
4658<p>
4659Using the <tt>package</tt> option of the <tt>%module</tt> directive
4660allows you to specify what Python package that the module will be
4661living in when installed.
4662</p>
4663
4664<div class="code">
4665<pre>
4666%module(package="wx") xrc
4667</pre>
4668</div>
4669
4670<p>
4671This is useful when the <tt>.i</tt> file is <tt>%import</tt>ed by
4672another <tt>.i</tt> file. By default SWIG will assume that the
4673importer is able to find the importee with just the module name, but
4674if they live in separate Python packages then that won't work.
4675However if the importee specifies what its package is with the
4676<tt>%module</tt> option then the Python code generated for the
4677importer will use that package name when importing the other module
4678and also in base class declarations, etc. if the pacakge name is
4679different than its own.
4680</p>
4681
4682
4683</body>
4684</html>
4685
4686<!-- LocalWords: polymorphism Typemaps STL typemap typemaps Docstring autodoc
4687 -->
4688<!-- LocalWords: docstring SWIG's cxx py GCC linux DLL gcc fPIC Wiki Xlinker
4689 -->
4690<!-- LocalWords: examplemodule DHAVE CONFIG lpython lm ldl mypython lsocket
4691 -->
4692<!-- LocalWords: lnsl lpthread distutils enums namespaces
4693 -->