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