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