Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / v9 / html / swig / Typemaps.html
CommitLineData
920dae64
AT
1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2<html>
3<head>
4<title>Typemaps</title>
5<link rel="stylesheet" type="text/css" href="style.css">
6</head>
7
8<body bgcolor="#ffffff">
9<H1><a name="Typemaps"></a>10 Typemaps</H1>
10<!-- INDEX -->
11<div class="sectiontoc">
12<ul>
13<li><a href="#Typemaps_nn2">Introduction</a>
14<ul>
15<li><a href="#Typemaps_nn3">Type conversion</a>
16<li><a href="#Typemaps_nn4">Typemaps</a>
17<li><a href="#Typemaps_nn5">Pattern matching</a>
18<li><a href="#Typemaps_nn6">Reusing typemaps</a>
19<li><a href="#Typemaps_nn7">What can be done with typemaps?</a>
20<li><a href="#Typemaps_nn8">What can't be done with typemaps?</a>
21<li><a href="#Typemaps_nn9">The rest of this chapter</a>
22</ul>
23<li><a href="#Typemaps_nn10">Typemap specifications</a>
24<ul>
25<li><a href="#Typemaps_nn11">Defining a typemap</a>
26<li><a href="#Typemaps_nn12">Typemap scope</a>
27<li><a href="#Typemaps_nn13">Copying a typemap</a>
28<li><a href="#Typemaps_nn14">Deleting a typemap</a>
29<li><a href="#Typemaps_nn15">Placement of typemaps</a>
30</ul>
31<li><a href="#Typemaps_nn16">Pattern matching rules</a>
32<ul>
33<li><a href="#Typemaps_nn17">Basic matching rules</a>
34<li><a href="#Typemaps_nn18">Typedef reductions</a>
35<li><a href="#Typemaps_nn19">Default typemaps</a>
36<li><a href="#Typemaps_mixed_default">Mixed default typemaps</a>
37<li><a href="#Typemaps_nn20">Multi-arguments typemaps</a>
38</ul>
39<li><a href="#Typemaps_nn21">Code generation rules</a>
40<ul>
41<li><a href="#Typemaps_nn22">Scope</a>
42<li><a href="#Typemaps_nn23">Declaring new local variables</a>
43<li><a href="#Typemaps_nn24">Special variables</a>
44</ul>
45<li><a href="#Typemaps_nn25">Common typemap methods</a>
46<ul>
47<li><a href="#Typemaps_nn26">"in" typemap</a>
48<li><a href="#Typemaps_nn27">"typecheck" typemap</a>
49<li><a href="#Typemaps_nn28">"out" typemap</a>
50<li><a href="#Typemaps_nn29">"arginit" typemap</a>
51<li><a href="#Typemaps_nn30">"default" typemap</a>
52<li><a href="#Typemaps_nn31">"check" typemap</a>
53<li><a href="#Typemaps_nn32">"argout" typemap</a>
54<li><a href="#Typemaps_nn33">"freearg" typemap</a>
55<li><a href="#Typemaps_nn34">"newfree" typemap</a>
56<li><a href="#Typemaps_nn35">"memberin" typemap</a>
57<li><a href="#Typemaps_nn36">"varin" typemap</a>
58<li><a href="#Typemaps_nn37">"varout" typemap</a>
59<li><a href="#throws_typemap">"throws" typemap</a>
60</ul>
61<li><a href="#Typemaps_nn39">Some typemap examples</a>
62<ul>
63<li><a href="#Typemaps_nn40">Typemaps for arrays</a>
64<li><a href="#Typemaps_nn41">Implementing constraints with typemaps</a>
65</ul>
66<li><a href="#Typemaps_nn42">Multi-argument typemaps</a>
67<li><a href="#runtime_type_checker">The run-time type checker</a>
68<ul>
69<li><a href="#Typemaps_nn45">Implementation</a>
70<li><a href="#Typemaps_nn46">Usage</a>
71</ul>
72<li><a href="#Typemaps_overloading">Typemaps and overloading</a>
73<li><a href="#Typemaps_nn48">More about <tt>%apply</tt> and <tt>%clear</tt></a>
74<li><a href="#Typemaps_nn49">Reducing wrapper code size</a>
75<li><a href="#Typemaps_nn47">Passing data between typemaps</a>
76<li><a href="#Typemaps_nn51">Where to go for more information?</a>
77</ul>
78</div>
79<!-- INDEX -->
80
81
82
83<p>
84<b>Disclaimer: This chapter is under construction!</b>
85</p>
86
87<H2><a name="Typemaps_nn2"></a>10.1 Introduction</H2>
88
89
90<p>
91Chances are, you are reading this chapter for one of two reasons; you
92either want to customize SWIG's behavior or you overheard someone
93mumbling some incomprehensible drivel about "typemaps" and you asked
94yourself "typemaps, what are those?" That said, let's start with a
95short disclaimer that "typemaps" are an advanced customization feature
96that provide direct access to SWIG's low-level code generator. Not
97only that, they are an integral part of the SWIG C++ type system (a
98non-trivial topic of its own). Typemaps are generally
99<em>not</em> a required part of using SWIG. Therefore, you might want
100to re-read the earlier chapters if you have found your way to this
101chapter with only a vaque idea of what SWIG already does by default.
102</p>
103
104<H3><a name="Typemaps_nn3"></a>10.1.1 Type conversion</H3>
105
106
107<p>
108One of the most important problems in wrapper code generation is the
109conversion of datatypes between programming languages. Specifically,
110for every C/C++ declaration, SWIG must somehow generate wrapper code
111that allows values to be passed back and forth between languages.
112Since every programming language represents data differently, this is
113not a simple of matter of simply linking code together with the
114C linker. Instead, SWIG has to know something about how data is
115represented in each language and how it can be manipulated.
116</p>
117
118<p>
119To illustrate, suppose you had a simple C function like this:
120</p>
121
122<div class="code">
123<pre>
124int factorial(int n);
125</pre>
126</div>
127
128<p>
129To access this function from Python, a pair of Python API functions
130are used to convert integer values. For example:
131</p>
132
133<div class="code">
134<pre>
135long PyInt_AsLong(PyObject *obj); /* Python --&gt; C */
136PyObject *PyInt_FromLong(long x); /* C --&gt; Python */
137</pre>
138</div>
139
140<p>
141The first function is used to convert the input argument from a Python integer object
142to C <tt>long</tt>. The second function is used to convert a value from C back into a Python integer object.
143</p>
144
145<p>
146Inside the wrapper function, you might see these functions used like this:
147</p>
148
149<div class="code">
150<pre>
151PyObject *wrap_factorial(PyObject *self, PyObject *args) {
152 int arg1;
153 int result;
154 PyObject *obj1;
155 PyObject *resultobj;
156
157 if (!PyArg_ParseTuple("O:factorial", &amp;obj1)) return NULL;
158 <b>arg1 = PyInt_AsLong(obj1);</b>
159 result = factorial(arg1);
160 <b>resultobj = PyInt_FromLong(result);</b>
161 return resultobj;
162}
163</pre>
164</div>
165
166<p>
167Every target language supported by SWIG has functions that work in a similar manner. For example, in
168Perl, the following functions are used:
169</p>
170
171<div class="code">
172<pre>
173IV SvIV(SV *sv); /* Perl --&gt; C */
174void sv_setiv(SV *sv, IV val); /* C --&gt; Perl */
175</pre>
176</div>
177
178<p>
179In Tcl:
180</p>
181
182<div class="code">
183<pre>
184int Tcl_GetLongFromObj(Tcl_Interp *interp, Tcl_Obj *obj, long *value);
185Tcl_Obj *Tcl_NewIntObj(long value);
186</pre>
187</div>
188
189<p>
190The precise details are not so important. What is important is that
191all of the underlying type conversion is handled by collections of
192utility functions and short bits of C code like this---you simply have
193to read the extension documentation for your favorite language to know
194how it works (an exercise left to the reader).
195</p>
196
197<H3><a name="Typemaps_nn4"></a>10.1.2 Typemaps</H3>
198
199
200<p>
201Since type handling is so central to wrapper code generation, SWIG
202allows it to be completely defined (or redefined) by the user. To do this,
203a special <tt>%typemap</tt> directive is used. For example:
204</p>
205
206<div class="code">
207<pre>
208/* Convert from Python --&gt; C */
209%typemap(in) int {
210 $1 = PyInt_AsLong($input);
211}
212
213/* Convert from C --&gt; Python */
214%typemap(out) int {
215 $result = PyInt_FromLong($1);
216}
217</pre>
218</div>
219
220<p>
221At first glance, this code will look a little confusing.
222However, there is really not much to it. The first typemap (the "in"
223typemap) is used to convert a value from the target language to C. The second
224typemap (the "out" typemap) is used to convert in the other
225direction. The content of each typemap is a small fragment of C code
226that is inserted directly into the SWIG generated wrapper functions. Within
227this code, a number of special variables prefixed with a $ are expanded. These are
228really just placeholders for C variables that are generated in the course
229of creating the wrapper function. In this case, <tt>$input</tt> refers to an
230input object that needs to be converted to C and <tt>$result</tt>
231refers to an object that is going to be returned by a wrapper
232function. <tt>$1</tt> refers to a C variable that has the same type as
233specified in the typemap declaration (an <tt>int</tt> in this
234example).
235</p>
236
237<p>
238A short example might make this a little more clear. If you were wrapping a
239function like this:
240</p>
241
242<div class="code">
243<pre>
244int gcd(int x, int y);
245</pre>
246</div>
247
248<p>
249A wrapper function would look approximately like this:
250</p>
251
252<div class="code">
253<pre>
254PyObject *wrap_gcd(PyObject *self, PyObject *args) {
255 int arg1;
256 int arg2;
257 int result;
258 PyObject *obj1;
259 PyObject *obj2;
260 PyObject *resultobj;
261
262 if (!PyArg_ParseTuple("OO:gcd", &amp;obj1, &amp;obj2)) return NULL;
263
264 /* "in" typemap, argument 1 */<b>
265 {
266 arg1 = PyInt_AsLong(obj1);
267 }
268</b>
269 /* "in" typemap, argument 2 */<b>
270 {
271 arg2 = PyInt_AsLong(obj2);
272 }
273</b>
274 result = gcd(arg1,arg2);
275
276 /* "out" typemap, return value */<b>
277 {
278 resultobj = PyInt_FromLong(result);
279 }
280</b>
281 return resultobj;
282}
283</pre>
284</div>
285
286<p>
287In this code, you can see how the typemap code has been inserted into
288the function. You can also see how the special $ variables have been
289expanded to match certain variable names inside the wrapper function. This is really the
290whole idea behind typemaps--they simply let you insert arbitrary code into different
291parts of the generated wrapper functions. Because arbitrary code can be inserted, it
292possible to completely change the way in which values are converted.
293</p>
294
295<H3><a name="Typemaps_nn5"></a>10.1.3 Pattern matching</H3>
296
297
298<p>
299As the name implies, the purpose of a typemap is to "map" C datatypes to
300types in the target language. Once a typemap is defined for a C datatype,
301it is applied to all future occurrences of that type in the input file. For example:
302</p>
303
304<div class="code">
305<pre>
306/* Convert from Perl --&gt; C */
307%typemap(in) <b>int</b> {
308 $1 = SvIV($input);
309}
310
311...
312int factorial(<b>int</b> n);
313int gcd(<b>int</b> x, <b>int</b> y);
314int count(char *s, char *t, <b>int</b> max);
315</pre>
316</div>
317
318<p>
319The matching of typemaps to C datatypes is more than a simple textual match. In fact,
320typemaps are fully built into the underlying type system. Therefore, typemaps are
321unaffected by <tt>typedef</tt>, namespaces, and other declarations that might hide the
322underlying type. For example, you could have code like this:
323</p>
324
325<div class="code">
326<pre>
327/* Convert from Ruby--&gt; C */
328%typemap(in) <b>int</b> {
329 $1 = NUM2INT($input);
330}
331...
332typedef int Integer;
333namespace foo {
334 typedef Integer Number;
335};
336
337int foo(<b>int</b> x);
338int bar(<b>Integer</b> y);
339int spam(<b>foo::Number</b> a, <b>foo::Number</b> b);
340</pre>
341</div>
342
343<p>
344In this case, the typemap is still applied to the proper arguments even though typenames don't always
345match the text "int". This ability to track types is a critical part of SWIG--in fact, all
346of the target language modules work merely define a set of typemaps for the basic types. Yet, it
347is never necessary to write new typemaps for typenames introduced by <tt>typedef</tt>.
348</p>
349
350<p>
351In addition to tracking typenames, typemaps may also be specialized to match against a specific argument name. For
352example, you could write a typemap like this:
353</p>
354
355<div class="code">
356<pre>
357%typemap(in) <b>double nonnegative</b> {
358 $1 = PyFloat_AsDouble($input);
359 if ($1 &lt; 0) {
360 PyErr_SetString(PyExc_ValueError,"argument must be nonnegative.");
361 return NULL;
362 }
363}
364
365...
366double sin(double x);
367double cos(double x);
368double sqrt(<b>double nonnegative</b>);
369
370typedef double Real;
371double log(<b>Real nonnegative</b>);
372...
373</pre>
374</div>
375
376<p>
377For certain tasks such as input argument conversion, typemaps can be defined for sequences of
378consecutive arguments. For example:
379</p>
380
381<div class="code">
382<pre>
383%typemap(in) (<b>char *str, int len</b>) {
384 $1 = PyString_AsString($input); /* char *str */
385 $2 = PyString_Size($input); /* int len */
386}
387...
388int count(<b>char *str, int len</b>, char c);
389</pre>
390</div>
391
392<p>
393In this case, a single input object is expanded into a pair of C arguments. This example also
394provides a hint to the unusual variable naming scheme involving <tt>$1</tt>, <tt>$2</tt>, and so forth.
395</p>
396
397<H3><a name="Typemaps_nn6"></a>10.1.4 Reusing typemaps</H3>
398
399
400<p>
401Typemaps are normally defined for specific type and argument name patterns. However, typemaps can also
402be copied and reused. One way to do this is to use assignment like this:
403</p>
404
405<div class="code">
406<pre>
407%typemap(in) Integer = int;
408%typemap(in) (char *buffer, int size) = (char *str, int len);
409</pre>
410</div>
411
412<p>
413A more general form of copying is found in the <tt>%apply</tt> directive like this:
414</p>
415
416<div class="code">
417<pre>
418%typemap(in) int {
419 /* Convert an integer argument */
420 ...
421}
422%typemap(out) int {
423 /* Return an integer value */
424 ...
425}
426
427/* Apply all of the integer typemaps to size_t */
428%apply int { size_t };
429</pre>
430</div>
431
432<p>
433<tt>%apply</tt> merely takes <em>all</em> of the typemaps that are defined for one type and
434applies them to other types. Note: you can include a comma separated set of types in the
435<tt>{ ... }</tt> part of <tt>%apply</tt>.
436</p>
437
438<p>
439It should be noted that it is not necessary to copy typemaps for types that are related by <tt>typedef</tt>.
440For example, if you have this,
441</p>
442
443<div class="code">
444<pre>
445typedef int size_t;
446</pre>
447</div>
448
449<p>
450then SWIG already knows that the <tt>int</tt> typemaps apply. You don't have to do anything.
451</p>
452
453<H3><a name="Typemaps_nn7"></a>10.1.5 What can be done with typemaps?</H3>
454
455
456<p>
457The primary use of typemaps is for defining wrapper generation behavior at the level
458of individual C/C++ datatypes. There are currently six general categories of problems that
459typemaps address:
460</p>
461
462<p>
463<b>Argument handling</b>
464</p>
465
466<div class="code">
467<pre>
468int foo(<b>int x, double y, char *s</b>);
469</pre>
470</div>
471
472<ul>
473<li>Input argument conversion ("in" typemap).</li>
474<li>Input argument type checking ("typecheck" typemap).</li>
475<li>Output argument handling ("argout" typemap).</li>
476<li>Input argument value checking ("check" typemap).</li>
477<li>Input argument initialization ("arginit" typemap).</li>
478<li>Default arguments ("default" typemap).</li>
479<li>Input argument resource management ("freearg" typemap).</li>
480</ul>
481
482<p>
483<b>Return value handling</b>
484</p>
485
486<div class="code">
487<pre>
488<b>int</b> foo(int x, double y, char *s);
489</pre>
490</div>
491
492<ul>
493<li>Function return value conversion ("out" typemap).</li>
494<li>Return value resource management ("ret" typemap).</li>
495<li>Resource management for newly allocated objects ("newfree" typemap).</li>
496</ul>
497
498<p>
499<b>Exception handling</b>
500</p>
501
502<div class="code">
503<pre>
504<b>int</b> foo(int x, double y, char *s) throw(<b>MemoryError, IndexError</b>);
505</pre>
506</div>
507
508<ul>
509<li>Handling of C++ exception specifications. ("throw" typemap).</li>
510</ul>
511
512<p>
513<b>Global variables</b>
514</p>
515
516<div class="code">
517<pre>
518<b>int foo;</b>
519</pre>
520</div>
521
522<ul>
523<li>Assignment of a global variable. ("varin" typemap).</li>
524<li>Reading a global variable. ("varout" typemap).</li>
525</ul>
526
527<p>
528<b>Member variables</b>
529</p>
530
531<div class="code">
532<pre>
533struct Foo {
534 <b>int x[20]</b>;
535};
536</pre>
537</div>
538
539<ul>
540<li>Assignment of data to a class/structure member. ("memberin" typemap).</li>
541</ul>
542
543<p>
544<b>Constant creation</b>
545</p>
546
547<div class="code">
548<pre>
549#define FOO 3
550%constant int BAR = 42;
551enum { ALE, LAGER, STOUT };
552</pre>
553</div>
554
555<ul>
556<li>Creation of constant values. ("consttab" or "constcode" typemap).</li>
557</ul>
558
559<p>
560Details of each of these typemaps will be covered shortly. Also, certain language modules may define additional
561typemaps that expand upon this list. For example, the Java module defines a variety of typemaps for controlling additional
562aspects of the Java bindings. Consult language specific documentation for further details.
563</p>
564
565<H3><a name="Typemaps_nn8"></a>10.1.6 What can't be done with typemaps?</H3>
566
567
568<p>
569Typemaps can't be used to define properties that apply to C/C++ declarations as a whole. For example,
570suppose you had a declaration like this,
571</p>
572
573<div class="code">
574<pre>
575Foo *make_Foo();
576</pre>
577</div>
578
579<p>
580and you wanted to tell SWIG that <tt>make_Foo()</tt> returned a newly
581allocated object (for the purposes of providing better memory
582management). Clearly, this property of <tt>make_Foo()</tt> is
583<em>not</em> a property that would be associated with the datatype
584<tt>Foo *</tt> by itself. Therefore, a completely different SWIG
585customization mechanism (<tt>%feature</tt>) is used for this purpose. Consult the <a
586href="Customization.html#Customization">Customization Features</a> chapter for more
587information about that.
588</p>
589
590<p>
591Typemaps also can't be used to rearrange or transform the order of arguments. For example,
592if you had a function like this:
593</p>
594
595<div class="code">
596<pre>
597void foo(int, char *);
598</pre>
599</div>
600
601<p>
602you can't use typemaps to interchange the arguments, allowing you to call the
603function like this:
604</p>
605
606<div class="targetlang">
607<pre>
608foo("hello",3) # Reversed arguments
609</pre>
610</div>
611
612<p>
613If you want to change the calling conventions of a function, write a helper
614function instead. For example:
615</p>
616
617<div class="code">
618<pre>
619%rename(foo) wrap_foo;
620%inline %{
621void wrap_foo(char *s, int x) {
622 foo(x,s);
623}
624%}
625</pre>
626</div>
627
628<H3><a name="Typemaps_nn9"></a>10.1.7 The rest of this chapter</H3>
629
630
631<p>
632The rest of this chapter provides detailed information for people who
633want to write new typemaps. This information is of particular importance to anyone
634who intends to write a new SWIG target language module. Power users can also
635use this information to write application specific type conversion rules.
636</p>
637
638<p>
639Since typemaps are strongly tied to the underlying C++ type system,
640subsequent sections assume that you are reasonably familiar with the
641basic details of values, pointers, references, arrays, type qualifiers
642(e.g., <tt>const</tt>), structures, namespaces, templates, and memory
643management in C/C++. If not, you would be well-advised to consult a copy
644of "The C Programming Language" by Kernighan and Ritchie or
645"The C++ Programming Language" by Stroustrup before going any further.
646</p>
647
648<H2><a name="Typemaps_nn10"></a>10.2 Typemap specifications</H2>
649
650
651<p>
652This section describes the behavior of the <tt>%typemap</tt> directive itself.
653</p>
654
655<H3><a name="Typemaps_nn11"></a>10.2.1 Defining a typemap</H3>
656
657
658<p>
659New typemaps are defined using the <tt>%typemap</tt> declaration. The general form of
660this declaration is as follows (parts enclosed in [ ... ] are optional):
661</p>
662
663<div class="code">
664<pre>
665%typemap(<em>method</em> [, <em>modifiers</em>]) <em>typelist</em> <em>code</em> ;
666</pre>
667</div>
668
669<p>
670<em>method</em> is a simply a name that specifies what kind of typemap is being defined. It
671is usually a name like <tt>"in"</tt>, <tt>"out"</tt>, or <tt>"argout"</tt>. The purpose of
672these methods is described later.
673</p>
674
675<p>
676<em>modifiers</em> is an optional comma separated list of <tt>name="value"</tt> values. These
677are sometimes to attach extra information to a typemap and is often target-language dependent.
678</p>
679
680<p>
681<em>typelist</em> is a list of the C++ type patterns that the typemap will match. The general form of
682this list is as follows:
683</p>
684
685<div class="diagram">
686<pre>
687typelist : typepattern [, typepattern, typepattern, ... ] ;
688
689typepattern : type [ (parms) ]
690 | type name [ (parms) ]
691 | ( typelist ) [ (parms) ]
692
693</pre>
694</div>
695
696<p>
697Each type pattern is either a simple type, a simple type and argument name, or a list of types in the
698case of multi-argument typemaps. In addition, each type pattern can be parameterized with a list of temporary
699variables (parms). The purpose of these variables will be explained shortly.
700</p>
701
702<p><em>code</em> specifies the C code used in the typemap. It can take any one of the following
703forms:
704</p>
705
706<div class="diagram">
707<pre>
708code : { ... }
709 | " ... "
710 | %{ ... %}
711</pre>
712</div>
713
714<p>
715Here are some examples of valid typemap specifications:
716</p>
717
718<div class="code">
719<pre>
720/* Simple typemap declarations */
721%typemap(in) int {
722 $1 = PyInt_AsLong($input);
723}
724%typemap(in) int "$1 = PyInt_AsLong($input);";
725%typemap(in) int %{
726 $1 = PyInt_AsLong($input);
727%}
728
729/* Typemap with extra argument name */
730%typemap(in) int nonnegative {
731 ...
732}
733
734/* Multiple types in one typemap */
735%typemap(in) int, short, long {
736 $1 = SvIV($input);
737}
738
739/* Typemap with modifiers */
740%typemap(in,doc="integer") int "$1 = gh_scm2int($input);";
741
742/* Typemap applied to patterns of multiple arguments */
743%typemap(in) (char *str, int len),
744 (char *buffer, int size)
745{
746 $1 = PyString_AsString($input);
747 $2 = PyString_Size($input);
748}
749
750/* Typemap with extra pattern parameters */
751%typemap(in, numinputs=0) int *output (int temp),
752 long *output (long temp)
753{
754 $1 = &amp;temp;
755}
756</pre>
757</div>
758
759<p>
760Admittedly, it's not the most readable syntax at first glance. However, the purpose of the
761individual pieces will become clear.
762</p>
763
764<H3><a name="Typemaps_nn12"></a>10.2.2 Typemap scope</H3>
765
766
767<p>
768Once defined, a typemap remains in effect for all of the declarations that follow. A typemap may be redefined for
769different sections of an input file. For example:
770</p>
771
772<div class="code">
773<pre>
774// typemap1
775%typemap(in) int {
776...
777}
778
779int fact(int); // typemap1
780int gcd(int x, int y); // typemap1
781
782// typemap2
783%typemap(in) int {
784...
785}
786
787int isprime(int); // typemap2
788</pre>
789</div>
790
791<p>
792One exception to the typemap scoping rules pertains to the <tt>%extend</tt> declaration. <tt>%extend</tt> is used to attach
793new declarations to a class or structure definition. Because of this, all of the declarations in an <tt>%extend</tt> block are
794subject to the typemap rules that are in effect at the point where the class itself is defined. For example:
795</p>
796
797<div class="code">
798<pre>
799class Foo {
800 ...
801};
802
803%typemap(in) int {
804 ...
805}
806
807%extend Foo {
808 int blah(int x); // typemap has no effect. Declaration is attached to Foo which
809 // appears before the %typemap declaration.
810};
811</pre>
812</div>
813
814<H3><a name="Typemaps_nn13"></a>10.2.3 Copying a typemap</H3>
815
816
817<p>
818A typemap is copied by using assignment. For example:
819</p>
820
821<div class="code">
822<pre>
823%typemap(in) Integer = int;
824</pre>
825</div>
826
827<p>
828or this:
829</p>
830
831<div class="code">
832<pre>
833%typemap(in) Integer, Number, int32_t = int;
834</pre>
835</div>
836
837<p>
838Types are often managed by a collection of different typemaps. For example:
839</p>
840
841<div class="code">
842<pre>
843%typemap(in) int { ... }
844%typemap(out) int { ... }
845%typemap(varin) int { ... }
846%typemap(varout) int { ... }
847</pre>
848</div>
849
850<p>
851To copy all of these typemaps to a new type, use <tt>%apply</tt>. For example:
852</p>
853
854<div class="code">
855<pre>
856%apply int { Integer }; // Copy all int typemaps to Integer
857%apply int { Integer, Number }; // Copy all int typemaps to both Integer and Number
858</pre>
859</div>
860
861<p>
862The patterns for <tt>%apply</tt> follow the same rules as for <tt>%typemap</tt>. For example:
863</p>
864
865<div class="code">
866<pre>
867%apply int *output { Integer *output }; // Typemap with name
868%apply (char *buf, int len) { (char *buffer, int size) }; // Multiple arguments
869</pre>
870</div>
871
872<H3><a name="Typemaps_nn14"></a>10.2.4 Deleting a typemap</H3>
873
874
875<p>
876A typemap can be deleted by simply defining no code. For example:
877</p>
878
879<div class="code">
880<pre>
881%typemap(in) int; // Clears typemap for int
882%typemap(in) int, long, short; // Clears typemap for int, long, short
883%typemap(in) int *output;
884</pre>
885</div>
886
887<p>
888The <tt>%clear</tt> directive clears all typemaps for a given type.
889For example:
890</p>
891
892<div class="code">
893<pre>
894%clear int; // Removes all types for int
895%clear int *output, long *output;
896</pre>
897</div>
898
899<p>
900<b>Note:</b> Since SWIG's default behavior is defined by typemaps, clearing a fundamental type like
901<tt>int</tt> will make that type unusable unless you also define a new set of typemaps immediately
902after the clear operation.
903</p>
904
905<H3><a name="Typemaps_nn15"></a>10.2.5 Placement of typemaps</H3>
906
907
908<p>
909Typemap declarations can be declared in the global scope, within a C++ namespace, and within a C++ class. For
910example:
911</p>
912
913<div class="code">
914<pre>
915%typemap(in) int {
916 ...
917}
918
919namespace std {
920 class string;
921 %typemap(in) string {
922 ...
923 }
924}
925
926class Bar {
927public:
928 typedef const int &amp; const_reference;
929 %typemap(out) const_reference {
930 ...
931 }
932};
933</pre>
934</div>
935
936<p>
937When a typemap appears inside a namespace or class, it stays in effect until the end of the SWIG input
938(just like before). However, the typemap takes the local scope into account. Therefore, this
939code
940</p>
941
942<div class="code">
943<pre>
944namespace std {
945 class string;
946 %typemap(in) string {
947 ...
948 }
949}
950</pre>
951</div>
952
953<p>
954is really defining a typemap for the type <tt>std::string</tt>. You could have code like this:
955</p>
956
957<div class="code">
958<pre>
959namespace std {
960 class string;
961 %typemap(in) string { /* std::string */
962 ...
963 }
964}
965
966namespace Foo {
967 class string;
968 %typemap(in) string { /* Foo::string */
969 ...
970 }
971}
972</pre>
973</div>
974
975<p>
976In this case, there are two completely distinct typemaps that apply to two completely different
977types (<tt>std::string</tt> and <tt>Foo::string</tt>).
978</p>
979
980<p>
981It should be noted that for scoping to work, SWIG has to know that <tt>string</tt> is a typename defined
982within a particular namespace. In this example, this is done using the class declaration <tt>class string</tt>.
983</p>
984
985<H2><a name="Typemaps_nn16"></a>10.3 Pattern matching rules</H2>
986
987
988<p>
989The section describes the pattern matching rules by which C datatypes are associated with typemaps.
990</p>
991
992<H3><a name="Typemaps_nn17"></a>10.3.1 Basic matching rules</H3>
993
994
995<p>
996Typemaps are matched using both a type and a name (typically the name of a argument). For a given
997<tt>TYPE NAME</tt> pair, the following rules are applied, in order, to find a match. The first typemap found
998is used.
999</p>
1000
1001<ul>
1002<li>Typemaps that exactly match <tt>TYPE</tt> and <tt>NAME</tt>.
1003<li>Typemaps that exactly match <tt>TYPE</tt> only.
1004</ul>
1005
1006<p>
1007If <tt>TYPE</tt> includes qualifiers (const, volatile, etc.), they are stripped and the following
1008checks are made:
1009</p>
1010
1011<ul>
1012<li>Typemaps that match the stripped <tt>TYPE</tt> and <tt>NAME</tt>.
1013<Li>Typemaps that match the stripped <tt>TYPE</tt> only.
1014</ul>
1015
1016<p>
1017If <tt>TYPE</tt> is an array. The following transformation is made:
1018</p>
1019
1020<ul>
1021<li>Replace all dimensions to <tt>[ANY]</tt> and look for a generic array typemap.
1022</ul>
1023
1024<p>
1025To illustrate, suppose that you had a function like this:
1026</p>
1027
1028<div class="code">
1029<pre>
1030int foo(const char *s);
1031</pre>
1032</div>
1033
1034<p>
1035To find a typemap for the argument <tt>const char *s</tt>, SWIG will search for the following typemaps:
1036</p>
1037
1038<div class="diagram">
1039<pre>
1040const char *s Exact type and name match
1041const char * Exact type match
1042char *s Type and name match (stripped qualifiers)
1043char * Type match (stripped qualifiers)
1044</pre>
1045</div>
1046
1047<p>
1048When more than one typemap rule might be defined, only the first match
1049found is actually used. Here is an example that
1050shows how some of the basic rules are applied:
1051</p>
1052
1053<div class="code"><pre>
1054%typemap(in) int *x {
1055 ... typemap 1
1056}
1057
1058%typemap(in) int * {
1059 ... typemap 2
1060}
1061
1062%typemap(in) const int *z {
1063 ... typemap 3
1064}
1065
1066%typemap(in) int [4] {
1067 ... typemap 4
1068}
1069
1070%typemap(in) int [ANY] {
1071 ... typemap 5
1072}
1073
1074void A(int *x); // int *x rule (typemap 1)
1075void B(int *y); // int * rule (typemap 2)
1076void C(const int *x); // int *x rule (typemap 1)
1077void D(const int *z); // int * rule (typemap 3)
1078void E(int x[4]); // int [4] rule (typemap 4)
1079void F(int x[1000]); // int [ANY] rule (typemap 5)
1080</pre>
1081</div>
1082
1083<H3><a name="Typemaps_nn18"></a>10.3.2 Typedef reductions</H3>
1084
1085
1086<p>
1087If no match is found using the rules in the previous section, SWIG
1088applies a typedef reduction to the type and repeats the typemap search
1089for the reduced type. To illustrate, suppose you had code like this:
1090</p>
1091
1092<div class="code">
1093<pre>
1094%typemap(in) int {
1095 ... typemap 1
1096}
1097
1098typedef int Integer;
1099void blah(Integer x);
1100</pre>
1101</div>
1102
1103<p>
1104To find the typemap for <tt>Integer x</tt>, SWIG will first search for the following
1105typemaps:
1106</p>
1107
1108<div class="diagram">
1109<pre>
1110Integer x
1111Integer
1112</pre>
1113</div>
1114
1115<p>
1116Finding no match, it then applies a reduction <tt>Integer -&gt; int</tt> to the type and
1117repeats the search.
1118</p>
1119
1120<div class="diagram">
1121<pre>
1122int x
1123int --&gt; match: typemap 1
1124</pre>
1125</div>
1126
1127<p>
1128Even though two types might be the same via typedef, SWIG allows typemaps to be defined
1129for each typename independently. This allows for interesting customization possibilities based
1130solely on the typename itself. For example, you could write code like this:
1131</p>
1132
1133<div class="code">
1134<pre>
1135typedef double pdouble; // Positive double
1136
1137// typemap 1
1138%typemap(in) double {
1139 ... get a double ...
1140}
1141// typemap 2
1142%typemap(in) pdouble {
1143 ... get a positive double ...
1144}
1145double sin(double x); // typemap 1
1146pdouble sqrt(pdouble x); // typemap 2
1147</pre>
1148</div>
1149
1150<p>
1151When reducing the type, only one typedef reduction is applied at a
1152time. The search process continues to apply reductions until a
1153match is found or until no more reductions can be made.
1154</p>
1155
1156<p>
1157For complicated types, the reduction process can generate a long list of patterns. Consider the following:
1158</p>
1159
1160<div class="code">
1161<pre>
1162typedef int Integer;
1163typedef Integer Row4[4];
1164void foo(Row4 rows[10]);
1165</pre>
1166</div>
1167
1168<p>
1169To find a match for the <tt>Row4 rows[10]</tt> argument, SWIG would
1170check the following patterns, stopping only when it found a match:
1171</p>
1172
1173<div class="code">
1174<pre>
1175Row4 rows[10]
1176Row4 [10]
1177Row4 rows[ANY]
1178Row4 [ANY]
1179
1180# Reduce Row4 --&gt; Integer[4]
1181Integer rows[10][4]
1182Integer [10][4]
1183Integer rows[ANY][ANY]
1184Integer [ANY][ANY]
1185
1186# Reduce Integer --&gt; int
1187int rows[10][4]
1188int [10][4]
1189int rows[ANY][ANY]
1190int [ANY][ANY]
1191</pre>
1192</div>
1193
1194<p>
1195For parametized types like templates, the situation is even more complicated. Suppose you had some declarations
1196like this:
1197</p>
1198
1199<div class="code">
1200<pre>
1201typedef int Integer;
1202typedef foo&lt;Integer,Integer&gt; fooii;
1203void blah(fooii *x);
1204</pre>
1205</div>
1206
1207<p>
1208In this case, the following typemap patterns are searched for the argument <tt>fooii *x</tt>:
1209</p>
1210
1211<div class="code">
1212<pre>
1213fooii *x
1214fooii *
1215
1216# Reduce fooii --&gt; foo&lt;Integer,Integer&gt;
1217foo&lt;Integer,Integer&gt; *x
1218foo&lt;Integer,Integer&gt; *
1219
1220# Reduce Integer -&gt; int
1221foo&lt;int, Integer&gt; *x
1222foo&lt;int, Integer&gt; *
1223
1224# Reduce Integer -&gt; int
1225foo&lt;int, int&gt; *x
1226foo&lt;int, int&gt; *
1227</pre>
1228</div>
1229
1230<p>
1231Typemap reductions are always applied to the left-most type that appears. Only when no reductions can be made to the left-most
1232type are reductions made to other parts of the type. This behavior means that you could define a typemap for
1233<tt>foo&lt;int,Integer&gt;</tt>, but a typemap for <tt>foo&lt;Integer,int&gt;</tt> would never be matched. Admittedly, this
1234is rather esoteric--there's little practical reason to write a typemap quite like that. Of course, you could rely on this
1235to confuse your coworkers even more.
1236</p>
1237
1238<H3><a name="Typemaps_nn19"></a>10.3.3 Default typemaps</H3>
1239
1240
1241<p>
1242Most SWIG language modules use typemaps to define the default behavior of the C primitive types. This
1243is entirely straightforward. For example, a set of typemaps are written like this:
1244</p>
1245
1246<div class="code">
1247<pre>
1248%typemap(in) int "convert an int";
1249%typemap(in) short "convert a short";
1250%typemap(in) float "convert a float";
1251...
1252</pre>
1253</div>
1254
1255<p>
1256Since typemap matching follows all <tt>typedef</tt> declarations, any sort of type that is
1257mapped to a primitive type through <tt>typedef</tt> will be picked up by one of these primitive typemaps.
1258</p>
1259
1260<p>
1261The default behavior for pointers, arrays, references, and other kinds of types are handled by
1262specifying rules for variations of the reserved <tt>SWIGTYPE</tt> type. For example:
1263</p>
1264
1265<div class="code">
1266<pre>
1267%typemap(in) SWIGTYPE * { ... default pointer handling ... }
1268%typemap(in) SWIGTYPE &amp; { ... default reference handling ... }
1269%typemap(in) SWIGTYPE [] { ... default array handling ... }
1270%typemap(in) enum SWIGTYPE { ... default handling for enum values ... }
1271%typemap(in) SWIGTYPE (CLASS::*) { ... default pointer member handling ... }
1272</pre>
1273</div>
1274
1275<p>
1276These rules match any kind of pointer, reference, or array--even when
1277multiple levels of indirection or multiple array dimensions are used.
1278Therefore, if you wanted to change SWIG's default handling for all
1279types of pointers, you would simply redefine the rule for <tt>SWIGTYPE
1280*</tt>.
1281</p>
1282
1283<p>
1284Finally, the following typemap rule is used to match against simple types that don't match any other rules:
1285</p>
1286
1287<div class="code">
1288<pre>
1289%typemap(in) SWIGTYPE { ... handle an unknown type ... }
1290</pre>
1291</div>
1292
1293<p>
1294This typemap is important because it is the rule that gets triggered
1295when call or return by value is used. For instance, if you have a
1296declaration like this:
1297</p>
1298
1299<div class="code">
1300<pre>
1301double dot_product(Vector a, Vector b);
1302</pre>
1303</div>
1304
1305<p>
1306The <tt>Vector</tt> type will usually just get matched against
1307<tt>SWIGTYPE</tt>. The default implementation of <tt>SWIGTYPE</tt> is
1308to convert the value into pointers (as described in chapter 3).
1309</p>
1310
1311<p>
1312By redefining <tt>SWIGTYPE</tt> it may be possible to implement other
1313behavior. For example, if you cleared all typemaps for
1314<tt>SWIGTYPE</tt>, SWIG simply won't wrap any unknown datatype (which might
1315be useful for debugging). Alternatively, you might modify SWIGTYPE to marshal
1316objects into strings instead of converting them to pointers.
1317</p>
1318
1319<p>
1320The best way to explore the default typemaps is to look at the ones
1321already defined for a particular language module. Typemaps
1322definitions are usually found in the SWIG library in a file such as
1323<tt>python.swg</tt>, <tt>tcl8.swg</tt>, etc.
1324</p>
1325
1326<H3><a name="Typemaps_mixed_default"></a>10.3.4 Mixed default typemaps</H3>
1327
1328
1329<p>
1330The default typemaps described above can be mixed with <tt>const</tt> and with each other.
1331For example the <tt>SWIGTYPE *</tt> typemap is for default pointer handling, but if a <tt>const SWIGTYPE *</tt> typemap
1332is defined it will be used instead for constant pointers. Some further examples follow:
1333</p>
1334
1335<div class="code">
1336<pre>
1337%typemap(in) enum SWIGTYPE &amp; { ... enum references ... }
1338%typemap(in) const enum SWIGTYPE &amp; { ... const enum references ... }
1339%typemap(in) SWIGTYPE *&amp; { ... pointers passed by reference ... }
1340%typemap(in) SWIGTYPE * const &amp; { ... constant pointers passed by reference ... }
1341%typemap(in) SWIGTYPE[ANY][ANY] { ... 2D arrays ... }
1342</pre>
1343</div>
1344
1345<p>
1346Note that the the typedef reduction described earlier is also used with these mixed default typemaps.
1347For example, say the following typemaps are defined and SWIG is looking for the best match for the enum shown below:
1348</p>
1349
1350<div class="code">
1351<pre>
1352%typemap(in) const Hello &amp; { ... }
1353%typemap(in) const enum SWIGTYPE &amp; { ... }
1354%typemap(in) enum SWIGTYPE &amp; { ... }
1355%typemap(in) SWIGTYPE &amp; { ... }
1356%typemap(in) SWIGTYPE { ... }
1357
1358enum Hello {};
1359const Hello &amp;hi;
1360</pre>
1361</div>
1362
1363<p>
1364The typemap at the top of the list will be chosen, not because it is defined first, but because it is the closest match for the type being wrapped.
1365If any of the typemaps in the above list were not defined, then the next one on the list would have precedence.
1366In other words the typemap chosen is the closest explicit match.
1367</p>
1368
1369<p>
1370<b>Compatibility note: </b> The mixed default typemaps were introduced in SWIG-1.3.23, but were not used much in this version.
1371Expect to see them being used more and more within the various libraries in later versions of SWIG.
1372</p>
1373
1374
1375<H3><a name="Typemaps_nn20"></a>10.3.5 Multi-arguments typemaps</H3>
1376
1377
1378<p>
1379When multi-argument typemaps are specified, they take precedence over
1380any typemaps specified for a single type. For example:
1381</p>
1382
1383<div class="code">
1384<pre>
1385%typemap(in) (char *buffer, int len) {
1386 // typemap 1
1387}
1388
1389%typemap(in) char *buffer {
1390 // typemap 2
1391}
1392
1393void foo(char *buffer, int len, int count); // (char *buffer, int len)
1394void bar(char *buffer, int blah); // char *buffer
1395</pre>
1396</div>
1397
1398<p>
1399Multi-argument typemaps are also more restrictive in the way that they are matched.
1400Currently, the first argument follows the matching rules described in the previous section,
1401but all subsequent arguments must match exactly.
1402</p>
1403
1404
1405<H2><a name="Typemaps_nn21"></a>10.4 Code generation rules</H2>
1406
1407
1408<p>
1409This section describes rules by which typemap code is inserted into
1410the generated wrapper code.
1411</p>
1412
1413<H3><a name="Typemaps_nn22"></a>10.4.1 Scope</H3>
1414
1415
1416<p>
1417When a typemap is defined like this:
1418</p>
1419
1420<div class="code">
1421<pre>
1422%typemap(in) int {
1423 $1 = PyInt_AsLong($input);
1424}
1425</pre>
1426</div>
1427
1428<p>
1429the typemap code is inserted into the wrapper function using a new block scope. In other words, the
1430wrapper code will look like this:
1431</p>
1432
1433<div class="code">
1434<pre>
1435wrap_whatever() {
1436 ...
1437 // Typemap code
1438 {
1439 arg1 = PyInt_AsLong(obj1);
1440 }
1441 ...
1442}
1443</pre>
1444</div>
1445
1446<p>
1447Because the typemap code is enclosed in its own block, it is legal to declare temporary variables
1448for use during typemap execution. For example:
1449</p>
1450
1451<div class="code">
1452<pre>
1453%typemap(in) short {
1454 long temp; /* Temporary value */
1455 if (Tcl_GetLongFromObj(interp, $input, &amp;temp) != TCL_OK) {
1456 return TCL_ERROR;
1457 }
1458 $1 = (short) temp;
1459}
1460</pre>
1461</div>
1462
1463<p>
1464Of course, any variables that you declare inside a typemap are destroyed as soon as the typemap
1465code has executed (they are not visible to other parts of the wrapper function or other typemaps
1466that might use the same variable names).
1467</p>
1468
1469<p>
1470Occasionally, typemap code will be specified using a few alternative forms. For example:
1471</p>
1472
1473<div class="code">
1474<pre>
1475%typemap(in) int "$1 = PyInt_AsLong($input);";
1476%typemap(in) int %{
1477$1 = PyInt_AsLong($input);
1478%}
1479</pre>
1480</div>
1481
1482<p>
1483These two forms are mainly used for cosmetics--the specified code is not enclosed inside
1484a block scope when it is emitted. This sometimes results in a less complicated looking wrapper function.
1485</p>
1486
1487<H3><a name="Typemaps_nn23"></a>10.4.2 Declaring new local variables</H3>
1488
1489
1490<p>
1491Sometimes it is useful to declare a new local variable that exists
1492within the scope of the entire wrapper function. A good example of this
1493might be an application in which you wanted to marshal strings. Suppose
1494you had a C++ function like this
1495</p>
1496
1497<div class="code">
1498<pre>
1499int foo(std::string *s);
1500</pre>
1501</div>
1502
1503<p>
1504and you wanted to pass a native string in the target language as an argument. For instance,
1505in Perl, you wanted the function to work like this:
1506</p>
1507
1508<div class="targetlang">
1509<pre>
1510$x = foo("Hello World");
1511</pre>
1512</div>
1513
1514<p>
1515To do this, you can't just pass a raw Perl string as the <tt>std::string *</tt> argument.
1516Instead, you have to create a temporary <tt>std::string</tt> object, copy the Perl string data into it, and
1517then pass a pointer to the object. To do this, simply specify the typemap with an extra parameter like this:
1518</p>
1519
1520<div class="code">
1521<pre>
1522%typemap(in) std::string * <b>(std::string temp)</b> {
1523 unsigned int len;
1524 char *s;
1525 s = SvPV($input,len); /* Extract string data */
1526 temp.assign(s,len); /* Assign to temp */
1527 $1 = &amp;temp; /* Set argument to point to temp */
1528}
1529</pre>
1530</div>
1531
1532<p>
1533In this case, <tt>temp</tt> becomes a local variable in
1534the scope of the entire wrapper function. For example:
1535</p>
1536
1537<div class="code">
1538<pre>
1539wrap_foo() {
1540 std::string temp; &lt;--- Declaration of temp goes here
1541 ...
1542
1543 /* Typemap code */
1544 {
1545 ...
1546 temp.assign(s,len);
1547 ...
1548 }
1549 ...
1550}
1551</pre>
1552</div>
1553
1554<p>
1555When you set <tt>temp</tt> to a value, it
1556persists for the duration of the wrapper function and gets
1557cleaned up automatically on exit.
1558</p>
1559
1560<p>
1561It is perfectly safe to use more than one typemap involving local
1562variables in the same declaration. For example, you could declare a
1563function as :</p>
1564
1565<div class="code"><pre>
1566void foo(std::string *x, std::string *y, std::string *z);
1567</pre></div>
1568
1569<p>
1570This is safely handled because SWIG actually renames all local
1571variable references by appending an argument number suffix. Therefore, the
1572generated code would actually look like this:
1573</p>
1574
1575<div class="code">
1576<pre>
1577wrap_foo() {
1578 int *arg1; /* Actual arguments */
1579 int *arg2;
1580 int *arg3;
1581 std::string temp1; /* Locals declared in the typemap */
1582 std::string temp2;
1583 std::string temp3;
1584 ...
1585 {
1586 char *s;
1587 unsigned int len;
1588 ...
1589 temp1.assign(s,len);
1590 arg1 = *temp1;
1591 }
1592 {
1593 char *s;
1594 unsigned int len;
1595 ...
1596 temp2.assign(s,len);
1597 arg2 = &amp;temp2;
1598 }
1599 {
1600 char *s;
1601 unsigned int len;
1602 ...
1603 temp3.assign(s,len);
1604 arg3 = &amp;temp3;
1605 }
1606 ...
1607}
1608</pre>
1609</div>
1610
1611<p>
1612Some typemaps do not recognize local variables (or they may simply not
1613apply). At this time, only typemaps that apply to argument conversion support this.
1614</p>
1615
1616
1617<H3><a name="Typemaps_nn24"></a>10.4.3 Special variables</H3>
1618
1619
1620<p>
1621Within all typemaps, the following special variables are expanded.
1622</p>
1623
1624<center>
1625<table border=1 summary="Typemap special variables">
1626<tr><th>Variable</th><th>Meaning</th></tr>
1627
1628<tr>
1629<td>$<em>n</em></td>
1630<td>
1631A C local variable corresponding to type <em>n</em> in the typemap
1632pattern.
1633</td>
1634</tr>
1635
1636<tr>
1637<td>$argnum</td>
1638<td>Argument number. Only available in typemaps related to argument conversion</td>
1639</tr>
1640
1641<tr>
1642<td>$<em>n</em>_name</td>
1643<td>Argument name</td>
1644</tr>
1645
1646<tr>
1647<td>$<em>n</em>_type</td>
1648<td>Real C datatype of type <em>n</em>.</td>
1649</tr>
1650
1651<tr>
1652<td>$<em>n</em>_ltype</td>
1653<td>ltype of type <em>n</em></td>
1654</tr>
1655
1656<tr>
1657<td>$<em>n</em>_mangle</td>
1658<td>Mangled form of type <em>n</em>. For example <tt>_p_Foo</tt></td>
1659</tr>
1660
1661<tr>
1662<td>$<em>n</em>_descriptor</td>
1663<td>Type descriptor structure for type <em>n</em>. For example
1664<tt>SWIGTYPE_p_Foo</tt>. This is primarily used when interacting with the
1665run-time type checker (described later).</td>
1666</tr>
1667
1668
1669<tr>
1670<td>$*<em>n</em>_type</td>
1671<td>Real C datatype of type <em>n</em> with one pointer removed.</td>
1672</tr>
1673
1674<tr>
1675<td>$*<em>n</em>_ltype</td>
1676<td>ltype of type <em>n</em> with one pointer removed.</td>
1677</tr>
1678
1679<tr>
1680<td>$*<em>n</em>_mangle</td>
1681<td>Mangled form of type <em>n</em> with one pointer removed. </td>
1682</tr>
1683
1684<tr>
1685<td>$*<em>n</em>_descriptor</td>
1686<td>Type descriptor structure for type <em>n</em> with one pointer removed.
1687</tr>
1688
1689
1690<tr>
1691<td>$&amp;<em>n</em>_type</td>
1692<td>Real C datatype of type <em>n</em> with one pointer added.</td>
1693</tr>
1694
1695<tr>
1696<td>$&amp;<em>n</em>_ltype</td>
1697<td>ltype of type <em>n</em> with one pointer added.</td>
1698</tr>
1699
1700<tr>
1701<td>$&amp;<em>n</em>_mangle</td>
1702<td>Mangled form of type <em>n</em> with one pointer added.</td>
1703</tr>
1704
1705<tr>
1706<td>$&amp;<em>n</em>_descriptor</td>
1707<td>Type descriptor structure for type <em>n</em> with one pointer added.
1708</tr>
1709
1710<tr>
1711<td>$<em>n</em>_basetype</td>
1712<td>Base typename with all pointers and qualifiers stripped.
1713</td>
1714</tr>
1715
1716</table>
1717</center>
1718
1719<p>
1720Within the table, $<em>n</em> refers to a specific type within the typemap specification. For example,
1721if you write this
1722</p>
1723
1724<div class="code">
1725<pre>
1726%typemap(in) int *INPUT {
1727
1728}
1729</pre>
1730</div>
1731
1732<p>
1733then $1 refers to <tt>int *INPUT</tt>. If you have a typemap like this,
1734</p>
1735
1736<div class="code">
1737<pre>
1738%typemap(in) (int argc, char *argv[]) {
1739 ...
1740}
1741</pre>
1742</div>
1743
1744<p>
1745then $1 refers to <tt>int argc</tt> and $2 refers to <tt>char *argv[]</tt>.
1746</p>
1747
1748<p>
1749Substitutions related to types and names always fill in values from the actual code that was matched.
1750This is useful when a typemap might match multiple C datatype. For example:
1751</p>
1752
1753<div class="code">
1754<pre>
1755%typemap(in) int, short, long {
1756 $1 = ($1_ltype) PyInt_AsLong($input);
1757}
1758</pre>
1759</div>
1760
1761<p>
1762In this case, <tt>$1_ltype</tt> is replaced with the datatype that is actually matched.
1763</p>
1764
1765
1766<p>
1767When typemap code is emitted, the C/C++ datatype of the special variables <tt>$1</tt> and
1768<tt>$2</tt> is always an "ltype." An "ltype" is simply a type that can legally appear
1769on the left-hand side of a C assignment operation. Here are a few examples of types
1770and ltypes:
1771</p>
1772
1773<div class="diagram">
1774<pre>
1775type ltype
1776------ ----------------
1777int int
1778const int int
1779conts int * int *
1780int [4] int *
1781int [4][5] int (*)[5]
1782</pre>
1783</div>
1784
1785<p>
1786In most cases a ltype is simply the C datatype with qualifiers stripped off. In addition,
1787arrays are converted into pointers.
1788</p>
1789
1790<p>
1791Variables such as <tt>$&amp;1_type</tt> and <tt>$*1_type</tt> are used to
1792safely modify the type by removing or adding pointers. Although not
1793needed in most typemaps, these substitutions are sometimes needed to properly
1794work with typemaps that convert values between pointers and values.
1795</p>
1796
1797<p>
1798If necessary, type related substitutions can also be used when declaring locals. For example:
1799</p>
1800
1801<div class="code">
1802<pre>
1803%typemap(in) int * ($*1_type temp) {
1804 temp = PyInt_AsLong($input);
1805 $1 = &amp;temp;
1806}
1807</pre>
1808</div>
1809
1810<p>
1811There is one word of caution about declaring local variables in this manner. If you declare a local variable
1812using a type substitution such as <tt>$1_ltype temp</tt>, it won't work like you expect for arrays and certain
1813kinds of pointers. For example, if you wrote this,
1814</p>
1815
1816<div class="code">
1817<pre>
1818%typemap(in) int [10][20] {
1819 $1_ltype temp;
1820}
1821</pre>
1822</div>
1823
1824<p>
1825then the declaration of <tt>temp</tt> will be expanded as
1826</p>
1827
1828<div class="code">
1829<pre>
1830int (*)[20] temp;
1831</pre>
1832</div>
1833
1834<p>
1835This is illegal C syntax and won't compile. There is currently no
1836straightforward way to work around this problem in SWIG due to the way
1837that typemap code is expanded and processed. However, one possible workaround
1838is to simply pick an alternative type such as <tt>void *</tt> and use
1839casts to get the correct type when needed. For example:
1840</p>
1841
1842<div class="code">
1843<pre>
1844%typemap(in) int [10][20] {
1845 void *temp;
1846 ...
1847 (($1_ltype) temp)[i][j] = x; /* set a value */
1848 ...
1849}
1850</pre>
1851</div>
1852
1853<p>
1854Another approach, which only works for arrays is to use the <tt>$1_basetype</tt> substitution. For example:
1855</p>
1856
1857<div class="code">
1858<pre>
1859%typemap(in) int [10][20] {
1860 $1_basetype temp[10][20];
1861 ...
1862 temp[i][j] = x; /* set a value */
1863 ...
1864}
1865</pre>
1866</div>
1867
1868<H2><a name="Typemaps_nn25"></a>10.5 Common typemap methods</H2>
1869
1870
1871<p>
1872The set of typemaps recognized by a language module may vary. However,
1873the following typemap methods are nearly universal:
1874</p>
1875
1876<H3><a name="Typemaps_nn26"></a>10.5.1 "in" typemap</H3>
1877
1878
1879<p>
1880The "in" typemap is used to convert function arguments from the target language
1881to C. For example:
1882</p>
1883
1884<div class="code">
1885<pre>
1886%typemap(in) int {
1887 $1 = PyInt_AsLong($input);
1888}
1889</pre>
1890</div>
1891
1892<p>
1893The following special variables are available:
1894</p>
1895
1896<div class="code">
1897<pre>
1898$input - Input object holding value to be converted.
1899$symname - Name of function/method being wrapped
1900</pre>
1901</div>
1902
1903<p>
1904This is probably the most commonly redefined typemap because it can be used
1905to implement customized conversions.
1906</p>
1907
1908<p>
1909In addition, the "in" typemap allows the number of converted arguments to be
1910specified. For example:
1911</p>
1912
1913<div class="code">
1914<pre>
1915// Ignored argument.
1916%typemap(in, numinputs=0) int *out (int temp) {
1917 $1 = &amp;temp;
1918}
1919</pre>
1920</div>
1921
1922<p>
1923At this time, only zero or one arguments may be converted.
1924</p>
1925
1926<p>
1927<b>Compatibility note: </b> Specifying <tt>numinputs=0</tt>
1928is the same as the old "ignore" typemap.
1929</p>
1930
1931<H3><a name="Typemaps_nn27"></a>10.5.2 "typecheck" typemap</H3>
1932
1933
1934<p>
1935The "typecheck" typemap is used to support overloaded functions and methods. It merely checks an argument
1936to see whether or not it matches a specific type. For example:
1937</p>
1938
1939<div class="code">
1940<pre>
1941%typemap(typecheck,precedence=SWIG_TYPECHECK_INTEGER) int {
1942 $1 = PyInt_Check($input) ? 1 : 0;
1943}
1944</pre>
1945</div>
1946
1947<p>
1948For typechecking, the $1 variable is always a simple integer that is set to 1 or 0 depending on whether or not
1949the input argument is the correct type.
1950</p>
1951
1952<p>
1953If you define new "in" typemaps <em>and</em> your program uses overloaded methods, you should also define a collection of
1954"typecheck" typemaps. More details about this follow in a later section on "Typemaps and Overloading."
1955</p>
1956
1957<H3><a name="Typemaps_nn28"></a>10.5.3 "out" typemap</H3>
1958
1959
1960<p>
1961The "out" typemap is used to convert function/method return values from C
1962into the target language. For example:
1963</p>
1964
1965<div class="code">
1966<pre>
1967%typemap(out) int {
1968 $result = PyInt_FromLong($1);
1969}
1970</pre>
1971</div>
1972
1973<p>
1974The following special variables are available.
1975</p>
1976
1977<div class="code">
1978<pre>
1979$result - Result object returned to target language.
1980$symname - Name of function/method being wrapped
1981</pre>
1982</div>
1983
1984<H3><a name="Typemaps_nn29"></a>10.5.4 "arginit" typemap</H3>
1985
1986
1987<p>
1988The "arginit" typemap is used to set the initial value of a function
1989argument--before any conversion has occurred. This is not normally
1990necessary, but might be useful in highly specialized applications.
1991For example:
1992</p>
1993
1994<div class="code">
1995<pre>
1996// Set argument to NULL before any conversion occurs
1997%typemap(arginit) int *data {
1998 $1 = NULL;
1999}
2000</pre>
2001</div>
2002
2003<H3><a name="Typemaps_nn30"></a>10.5.5 "default" typemap</H3>
2004
2005
2006<p>
2007The "default" typemap is used to turn an argument into a default
2008argument. For example:
2009</p>
2010
2011<div class="code">
2012<pre>
2013%typemap(default) int flags {
2014 $1 = DEFAULT_FLAGS;
2015}
2016...
2017int foo(int x, int y, int flags);
2018</pre>
2019</div>
2020
2021<p>
2022The primary use of this typemap is to either change the wrapping of
2023default arguments or specify a default argument in a language where
2024they aren't supported (like C). Target languages that do not support
2025optional arguments, such as Java and C#, effecively ignore the value specified
2026by this typemap as all arguments must be given.
2027</p>
2028
2029<p>
2030Once a default typemap has been applied to an argument, all arguments
2031that follow must have default values.
2032See the <a href="SWIG.html#SWIG_default_args">Default/optional arguments</a> section
2033for further information on default argument wrapping.
2034</p>
2035
2036<H3><a name="Typemaps_nn31"></a>10.5.6 "check" typemap</H3>
2037
2038
2039<p>
2040The "check" typemap is used to supply value checking code during argument
2041conversion. The typemap is applied <em>after</em> arguments have been
2042converted. For example:
2043</p>
2044
2045<div class="code">
2046<pre>
2047%typemap(check) int positive {
2048 if ($1 &lt;= 0) {
2049 SWIG_exception(SWIG_ValueError,"Expected positive value.");
2050 }
2051}
2052</pre>
2053</div>
2054
2055<H3><a name="Typemaps_nn32"></a>10.5.7 "argout" typemap</H3>
2056
2057
2058<p>
2059The "argout" typemap is used to return values from arguments. This
2060is most commonly used to write wrappers for C/C++ functions that need
2061to return multiple values. The "argout" typemap is almost always combined
2062with an "in" typemap---possibly to ignore the input value. For example:
2063</p>
2064
2065<div class="code">
2066<pre>
2067/* Set the input argument to point to a temporary variable */
2068%typemap(in, numinputs=0) int *out (int temp) {
2069 $1 = &amp;temp;
2070}
2071
2072%typemap(argout) int *out {
2073 // Append output value $1 to $result
2074 ...
2075}
2076</pre>
2077</div>
2078
2079<p>
2080The following special variables are available.
2081</p>
2082
2083<div class="diagram">
2084<pre>
2085$result - Result object returned to target language.
2086$input - The original input object passed.
2087$symname - Name of function/method being wrapped
2088</pre>
2089</div>
2090
2091<p>
2092The code supplied to the "argout" typemap is always placed after
2093the "out" typemap. If multiple return values are used, the extra
2094return values are often appended to return value of the function.
2095</p>
2096
2097<p>
2098See the <tt>typemaps.i</tt> library for examples.
2099</p>
2100
2101<H3><a name="Typemaps_nn33"></a>10.5.8 "freearg" typemap</H3>
2102
2103
2104<p>
2105The "freearg" typemap is used to cleanup argument data. It is only
2106used when an argument might have allocated resources that need to be
2107cleaned up when the wrapper function exits. The "freearg" typemap
2108usually cleans up argument resources allocated by the "in" typemap.
2109For example:
2110</p>
2111
2112<div class="code">
2113<pre>
2114// Get a list of integers
2115%typemap(in) int *items {
2116 int nitems = Length($input);
2117 $1 = (int *) malloc(sizeof(int)*nitems);
2118}
2119// Free the list
2120%typemap(freearg) int *items {
2121 free($1);
2122}
2123</pre>
2124</div>
2125
2126<p>
2127The "freearg" typemap inserted at the end of the wrapper function,
2128just before control is returned back to the target language. This
2129code is also placed into a special variable <tt>$cleanup</tt> that may
2130be used in other typemaps whenever a wrapper function needs to abort
2131prematurely.
2132</p>
2133
2134<H3><a name="Typemaps_nn34"></a>10.5.9 "newfree" typemap</H3>
2135
2136
2137<p>
2138The "newfree" typemap is used in conjunction with the <tt>%newobject</tt>
2139directive and is used to deallocate memory used by the return result
2140of a function. For example:
2141</p>
2142
2143<div class="code">
2144<pre>
2145%typemap(newfree) string * {
2146 delete $1;
2147}
2148%typemap(out) string * {
2149 $result = PyString_FromString($1-&gt;c_str());
2150}
2151...
2152
2153%newobject foo;
2154...
2155string *foo();
2156</pre>
2157</div>
2158
2159<H3><a name="Typemaps_nn35"></a>10.5.10 "memberin" typemap</H3>
2160
2161
2162<p>
2163The "memberin" typemap is used to copy data from <em>an already converted input value</em>
2164into a structure member. It is typically used to handle array members and other special
2165cases. For example:
2166</p>
2167
2168<div class="code">
2169<pre>
2170%typemap(memberin) int [4] {
2171 memmove($1, $input, 4*sizeof(int));
2172}
2173</pre>
2174</div>
2175
2176<p>
2177It is rarely necessary to write "memberin" typemaps---SWIG already provides
2178a default implementation for arrays, strings, and other objects.
2179</p>
2180
2181<H3><a name="Typemaps_nn36"></a>10.5.11 "varin" typemap</H3>
2182
2183
2184<p>
2185The "varin" typemap is used to convert objects in the target language to C for the
2186purposes of assigning to a C/C++ global variable. This is implementation specific.
2187</p>
2188
2189<H3><a name="Typemaps_nn37"></a>10.5.12 "varout" typemap</H3>
2190
2191
2192<p>
2193The "varout" typemap is used to convert a C/C++ object to an object in the target
2194language when reading a C/C++ global variable. This is implementation specific.
2195</p>
2196
2197<H3><a name="throws_typemap"></a>10.5.13 "throws" typemap</H3>
2198
2199
2200<p>
2201The "throws" typemap is only used when SWIG parses a C++ method with an exception specification.
2202It provides a default mechanism for handling C++ methods that have declared the exceptions it will throw.
2203The purpose of this typemap is to convert a C++ exception into an error or exception in the target language.
2204It is slightly different to the other typemaps as it is based around the exception type rather than the type of a parameter or variable.
2205For example:
2206</p>
2207
2208<div class="code">
2209<pre>
2210%typemap(throws) const char * %{
2211 PyErr_SetString(PyExc_RuntimeError, $1);
2212 SWIG_fail;
2213%}
2214void bar() throw (const char *);
2215</pre>
2216</div>
2217
2218<p>
2219As can be seen from the generated code below, SWIG generates an exception handler
2220with the catch block comprising the "throws" typemap content.
2221</p>
2222
2223<div class="code">
2224<pre>
2225...
2226try {
2227 bar();
2228}
2229catch(char const *_e) {
2230 PyErr_SetString(PyExc_RuntimeError, _e);
2231 SWIG_fail;
2232
2233}
2234...
2235</pre>
2236</div>
2237
2238<p>
2239Note that if your methods do not have an exception specification yet they do throw exceptions, SWIG cannot know how to deal with them.
2240For a neat way to handle these, see the <a href="Customization.html#exception">Exception handling with %exception</a> section.
2241</p>
2242
2243<H2><a name="Typemaps_nn39"></a>10.6 Some typemap examples</H2>
2244
2245
2246<p>
2247This section contains a few examples. Consult language module documentation
2248for more examples.
2249</p>
2250
2251<H3><a name="Typemaps_nn40"></a>10.6.1 Typemaps for arrays</H3>
2252
2253
2254<p>
2255A common use of typemaps is to provide support for C arrays appearing both as
2256arguments to functions and as structure members.
2257</p>
2258
2259<p>
2260For example, suppose you had a function like this:
2261</p>
2262
2263<div class="code">
2264<pre>
2265void set_vector(int type, float value[4]);
2266</pre>
2267</div>
2268
2269<p>
2270If you wanted to handle <tt>float value[4]</tt> as a list of floats, you might write a typemap
2271similar to this:
2272</p>
2273
2274<div class="code">
2275<pre>
2276
2277%typemap(in) float value[4] (float temp[4]) {
2278 int i;
2279 if (!PySequence_Check($input)) {
2280 PyErr_SetString(PyExc_ValueError,"Expected a sequence");
2281 return NULL;
2282 }
2283 if (PySequence_Length($input) != 4) {
2284 PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected 4 elements");
2285 return NULL;
2286 }
2287 for (i = 0; i &lt; 4; i++) {
2288 PyObject *o = PySequence_GetItem($input,i);
2289 if (PyNumber_Check(o)) {
2290 temp[i] = (float) PyFloat_AsDouble(o);
2291 } else {
2292 PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");
2293 return NULL;
2294 }
2295 }
2296 $1 = temp;
2297}
2298</pre>
2299</div>
2300
2301<p>
2302In this example, the variable <tt>temp</tt> allocates a small array on the
2303C stack. The typemap then populates this array and passes it to the underlying C function.
2304</p>
2305
2306<p>
2307When used from Python, the typemap allows the following type of function call:
2308</p>
2309
2310<div class="targetlang">
2311<pre>
2312&gt;&gt;&gt; set_vector(type, [ 1, 2.5, 5, 20 ])
2313</pre>
2314</div>
2315
2316<p>
2317If you wanted to generalize the typemap to apply to arrays of all dimensions you might write this:
2318</p>
2319
2320<div class="code">
2321<pre>
2322%typemap(in) float value[ANY] (float temp[$1_dim0]) {
2323 int i;
2324 if (!PySequence_Check($input)) {
2325 PyErr_SetString(PyExc_ValueError,"Expected a sequence");
2326 return NULL;
2327 }
2328 if (PySequence_Length($input) != $1_dim0) {
2329 PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements");
2330 return NULL;
2331 }
2332 for (i = 0; i &lt; $1_dim0; i++) {
2333 PyObject *o = PySequence_GetItem($input,i);
2334 if (PyNumber_Check(o)) {
2335 temp[i] = (float) PyFloat_AsDouble(o);
2336 } else {
2337 PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");
2338 return NULL;
2339 }
2340 }
2341 $1 = temp;
2342}
2343</pre>
2344</div>
2345
2346<p>
2347In this example, the special variable <tt>$1_dim0</tt> is expanded with the actual
2348array dimensions. Multidimensional arrays can be matched in a similar manner. For example:
2349</p>
2350
2351<div class="code">
2352<pre>
2353%typemap(python,in) float matrix[ANY][ANY] (float temp[$1_dim0][$1_dim1]) {
2354 ... convert a 2d array ...
2355}
2356</pre>
2357</div>
2358
2359<p>
2360For large arrays, it may be impractical to allocate storage on the stack using a temporary variable
2361as shown. To work with heap allocated data, the following technique can be used.
2362</p>
2363
2364<div class="code">
2365<pre>
2366%typemap(in) float value[ANY] {
2367 int i;
2368 if (!PySequence_Check($input)) {
2369 PyErr_SetString(PyExc_ValueError,"Expected a sequence");
2370 return NULL;
2371 }
2372 if (PySequence_Length($input) != $1_dim0) {
2373 PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements");
2374 return NULL;
2375 }
2376 $1 = (float *) malloc($1_dim0*sizeof(float));
2377 for (i = 0; i &lt; $1_dim0; i++) {
2378 PyObject *o = PySequence_GetItem($input,i);
2379 if (PyNumber_Check(o)) {
2380 $1[i] = (float) PyFloat_AsDouble(o);
2381 } else {
2382 PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");
2383 free($1);
2384 return NULL;
2385 }
2386 }
2387}
2388%typemap(freearg) float value[ANY] {
2389 if ($1) free($1);
2390}
2391</pre>
2392</div>
2393
2394<p>
2395In this case, an array is allocated using <tt>malloc</tt>. The <tt>freearg</tt> typemap is then used
2396to release the argument after the function has been called.
2397</p>
2398
2399<p>
2400Another common use of array typemaps is to provide support for array structure members.
2401Due to subtle differences between pointers and arrays in C, you can't just "assign" to
2402a array structure member. Instead, you have to explicitly copy elements into the array.
2403For example, suppose you had a structure like this:
2404</p>
2405
2406<div class="code"><pre>
2407struct SomeObject {
2408 float value[4];
2409 ...
2410};
2411</pre></div>
2412
2413<p>
2414When SWIG runs, it won't produce any code to set the <tt>vec</tt> member.
2415You may even get a warning message like this:
2416</p>
2417
2418<div class="shell"><pre>
2419swig -python example.i
2420Generating wrappers for Python
2421example.i:10. Warning. Array member value will be read-only.
2422</pre></div>
2423
2424<p>
2425These warning messages indicate that SWIG does not know how you want
2426to set the <tt>vec</tt> field.
2427</p>
2428
2429<p>
2430To fix this, you can supply a special "memberin" typemap like this:
2431</p>
2432
2433<div class="code"><pre>
2434%typemap(memberin) float [ANY] {
2435 int i;
2436 for (i = 0; i &lt; $1_dim0; i++) {
2437 $1[i] = $input[i];
2438 }
2439}
2440</pre></div>
2441
2442<p>
2443The memberin typemap is used to set a structure member from data that has already been converted
2444from the target language to C. In this case, <tt>$input</tt> is the local variable in which
2445converted input data is stored. This typemap then copies this data into the structure.
2446</p>
2447
2448<p>
2449When combined with the earlier typemaps for arrays, the combination of the "in" and "memberin" typemap allows
2450the following usage:
2451</p>
2452
2453<div class="targetlang">
2454<pre>
2455&gt;&gt;&gt; s = SomeObject()
2456&gt;&gt;&gt; s.x = [1, 2.5, 5, 10]
2457</pre>
2458</div>
2459
2460<p>
2461Related to structure member input, it may be desirable to return structure members as a new kind of
2462object. For example, in this example, you will get very odd program behavior where the structure member
2463can be set nicely, but reading the member simply returns a pointer:
2464</p>
2465
2466<div class="targetlang">
2467<pre>
2468&gt;&gt;&gt; s = SomeObject()
2469&gt;&gt;&gt; s.x = [1, 2.5, 5, 10]
2470&gt;&gt;&gt; print s.x
2471_1008fea8_p_float
2472&gt;&gt;&gt;
2473</pre>
2474</div>
2475
2476<p>
2477To fix this, you can write an "out" typemap. For example:
2478</p>
2479
2480<div class="code">
2481<pre>
2482%typemap(out) float [ANY] {
2483 int i;
2484 $result = PyList_New($1_dim0);
2485 for (i = 0; i &lt; $1_dim0; i++) {
2486 PyObject *o = PyFloat_FromDouble((double) $1[i]);
2487 PyList_SetItem($result,i,o);
2488 }
2489}
2490</pre>
2491</div>
2492
2493<p>
2494Now, you will find that member access is quite nice:
2495</p>
2496
2497<div class="targetlang">
2498<pre>
2499&gt;&gt;&gt; s = SomeObject()
2500&gt;&gt;&gt; s.x = [1, 2.5, 5, 10]
2501&gt;&gt;&gt; print s.x
2502[ 1, 2.5, 5, 10]
2503</pre>
2504</div>
2505
2506<p>
2507<b>Compatibility Note:</b> SWIG1.1 used to provide a special "memberout" typemap. However, it was mostly
2508useless and has since been eliminated. To return structure members, simply use the "out" typemap.
2509</p>
2510
2511<H3><a name="Typemaps_nn41"></a>10.6.2 Implementing constraints with typemaps</H3>
2512
2513
2514<p>
2515One particularly interesting application of typemaps is the
2516implementation of argument constraints. This can be done with the
2517"check" typemap. When used, this allows you to provide code for
2518checking the values of function arguments. For example :</p>
2519
2520<div class="code"><pre>
2521%module math
2522
2523%typemap(check) double posdouble {
2524 if ($1 &lt; 0) {
2525 croak("Expecting a positive number");
2526 }
2527}
2528
2529...
2530double sqrt(double posdouble);
2531
2532</pre></div>
2533
2534<p>
2535This provides a sanity check to your wrapper function. If a negative
2536number is passed to this function, a Perl exception will be raised and
2537your program terminated with an error message.</p>
2538
2539<p>
2540This kind of checking can be particularly useful when working with
2541pointers. For example :</p>
2542
2543<div class="code"><pre>
2544%typemap(check) Vector * {
2545 if ($1 == 0) {
2546 PyErr_SetString(PyExc_TypeError,"NULL Pointer not allowed");
2547 return NULL;
2548 }
2549}
2550
2551</pre></div>
2552
2553<p>
2554will prevent any function involving a <tt>Vector *</tt> from accepting
2555a NULL pointer. As a result, SWIG can often prevent a potential
2556segmentation faults or other run-time problems by raising an exception
2557rather than blindly passing values to the underlying C/C++ program.</p>
2558
2559<p>
2560Note: A more advanced constraint checking system is in development. Stay tuned.
2561</p>
2562
2563<H2><a name="Typemaps_nn42"></a>10.7 Multi-argument typemaps</H2>
2564
2565
2566<p>
2567So far, the typemaps presented have focused on the problem of dealing with
2568single values. For example, converting a single input object to a single argument
2569in a function call. However, certain conversion problems are difficult to handle
2570in this manner. As an example, consider the example at the very beginning of this
2571chapter:
2572</p>
2573
2574<div class="code">
2575<pre>
2576int foo(int argc, char *argv[]);
2577</pre>
2578</div>
2579
2580<p>
2581Suppose that you wanted to wrap this function so that it accepted a single
2582list of strings like this:
2583</p>
2584
2585<div class="targetlang">
2586<pre>
2587&gt;&gt;&gt; foo(["ale","lager","stout"])
2588</pre>
2589</div>
2590
2591<p>
2592To do this, you not only need to map a list of strings to <tt> char *argv[]</tt>, but the
2593value of <tt>int argc</tt> is implicitly determined by the length of the list. Using only simple
2594typemaps, this type of conversion is possible, but extremely painful. Therefore, SWIG1.3
2595introduces the notion of multi-argument typemaps.
2596</p>
2597
2598<p>
2599A multi-argument typemap is a conversion rule that specifies how to
2600convert a <em>single</em> object in the target language to set of
2601consecutive function arguments in C/C++. For example, the following multi-argument
2602maps perform the conversion described for the above example:
2603</p>
2604
2605<div class="code">
2606<pre>
2607%typemap(in) (int argc, char *argv[]) {
2608 int i;
2609 if (!PyList_Check($input)) {
2610 PyErr_SetString(PyExc_ValueError, "Expecting a list");
2611 return NULL;
2612 }
2613 $1 = PyList_Size($input);
2614 $2 = (char **) malloc(($1+1)*sizeof(char *));
2615 for (i = 0; i &lt; $1; i++) {
2616 PyObject *s = PyList_GetItem($input,i);
2617 if (!PyString_Check(s)) {
2618 free($2);
2619 PyErr_SetString(PyExc_ValueError, "List items must be strings");
2620 return NULL;
2621 }
2622 $2[i] = PyString_AsString(s);
2623 }
2624 $2[i] = 0;
2625}
2626
2627%typemap(freearg) (int argc, char *argv[]) {
2628 if ($2) free($2);
2629}
2630</pre>
2631</div>
2632
2633<p>
2634A multi-argument map is always specified by surrounding the arguments with parentheses as shown.
2635For example:
2636</p>
2637
2638<div class="code">
2639<pre>
2640%typemap(in) (int argc, char *argv[]) { ... }
2641</pre>
2642</div>
2643
2644<p>
2645Within the typemap code, the variables <tt>$1</tt>, <tt>$2</tt>, and so forth refer to each type
2646in the map. All of the usual substitutions apply--just use the appropriate <tt>$1</tt> or <tt>$2</tt>
2647prefix on the variable name (e.g., <tt>$2_type</tt>, <tt>$1_ltype</tt>, etc.)
2648</p>
2649
2650<p>
2651Multi-argument typemaps always have precedence over simple typemaps and SWIG always performs longest-match searching.
2652Therefore, you will get the following behavior:
2653</p>
2654
2655<div class="code">
2656<pre>
2657%typemap(in) int argc { ... typemap 1 ... }
2658%typemap(in) (int argc, char *argv[]) { ... typemap 2 ... }
2659%typemap(in) (int argc, char *argv[], char *env[]) { ... typemap 3 ... }
2660
2661int foo(int argc, char *argv[]); // Uses typemap 2
2662int bar(int argc, int x); // Uses typemap 1
2663int spam(int argc, char *argv[], char *env[]); // Uses typemap 3
2664</pre>
2665</div>
2666
2667<p>
2668It should be stressed that multi-argument typemaps can appear anywhere in a function declaration and can
2669appear more than once. For example, you could write this:
2670</p>
2671
2672<div class="code">
2673<pre>
2674%typemap(in) (int scount, char *swords[]) { ... }
2675%typemap(in) (int wcount, char *words[]) { ... }
2676
2677void search_words(int scount, char *swords[], int wcount, char *words[], int maxcount);
2678</pre>
2679</div>
2680
2681<p>
2682Other directives such as <tt>%apply</tt> and <tt>%clear</tt> also work with multi-argument maps. For example:
2683</p>
2684
2685<div class="code">
2686<pre>
2687%apply (int argc, char *argv[]) {
2688 (int scount, char *swords[]),
2689 (int wcount, char *words[])
2690};
2691...
2692%clear (int scount, char *swords[]), (int wcount, char *words[]);
2693...
2694</pre>
2695</div>
2696
2697<p>
2698Although multi-argument typemaps may seem like an exotic, little used feature, there
2699are several situations where they make sense. First, suppose you wanted to wrap
2700functions similar to the low-level <tt>read()</tt> and <tt>write()</tt> system calls.
2701For example:
2702</p>
2703
2704<div class="code">
2705<pre>
2706typedef unsigned int size_t;
2707
2708int read(int fd, void *rbuffer, size_t len);
2709int write(int fd, void *wbuffer, size_t len);
2710</pre>
2711</div>
2712
2713<p>
2714As is, the only way to use the functions would be to allocate memory and pass some kind of pointer
2715as the second argument---a process that might require the use of a helper function. However, using
2716multi-argument maps, the functions can be transformed into something more natural. For example, you
2717might write typemaps like this:
2718</p>
2719
2720<div class="code">
2721<pre>
2722// typemap for an outgoing buffer
2723%typemap(in) (void *wbuffer, size_t len) {
2724 if (!PyString_Check($input)) {
2725 PyErr_SetString(PyExc_ValueError, "Expecting a string");
2726 return NULL;
2727 }
2728 $1 = (void *) PyString_AsString($input);
2729 $2 = PyString_Size($input);
2730}
2731
2732// typemap for an incoming buffer
2733%typemap(in) (void *rbuffer, size_t len) {
2734 if (!PyInt_Check($input)) {
2735 PyErr_SetString(PyExc_ValueError, "Expecting an integer");
2736 return NULL;
2737 }
2738 $2 = PyInt_AsLong($input);
2739 if ($2 &lt; 0) {
2740 PyErr_SetString(PyExc_ValueError, "Positive integer expected");
2741 return NULL;
2742 }
2743 $1 = (void *) malloc($2);
2744}
2745
2746// Return the buffer. Discarding any previous return result
2747%typemap(argout) (void *rbuffer, size_t len) {
2748 Py_XDECREF($result); /* Blow away any previous result */
2749 if (result &lt; 0) { /* Check for I/O error */
2750 free($1);
2751 PyErr_SetFromErrno(PyExc_IOError);
2752 return NULL;
2753 }
2754 $result = PyString_FromStringAndSize($1,result);
2755 free($1);
2756}
2757</pre>
2758</div>
2759
2760<p>
2761(note: In the above example, <tt>$result</tt> and <tt>result</tt> are two different variables.
2762<tt>result</tt> is the real C datatype that was returned by the function. <tt>$result</tt> is the
2763scripting language object being returned to the interpreter.).
2764</p>
2765
2766<p>
2767Now, in a script, you can write code that simply passes buffers as strings like this:
2768</p>
2769
2770<div class="targetlang">
2771<pre>
2772&gt;&gt;&gt; f = example.open("Makefile")
2773&gt;&gt;&gt; example.read(f,40)
2774'TOP = ../..\nSWIG = $(TOP)/.'
2775&gt;&gt;&gt; example.read(f,40)
2776'./swig\nSRCS = example.c\nTARGET '
2777&gt;&gt;&gt; example.close(f)
27780
2779&gt;&gt;&gt; g = example.open("foo", example.O_WRONLY | example.O_CREAT, 0644)
2780&gt;&gt;&gt; example.write(g,"Hello world\n")
278112
2782&gt;&gt;&gt; example.write(g,"This is a test\n")
278315
2784&gt;&gt;&gt; example.close(g)
27850
2786&gt;&gt;&gt;
2787</pre>
2788</div>
2789
2790<p>
2791A number of multi-argument typemap problems also arise in libraries that
2792perform matrix-calculations--especially if they are mapped onto low-level Fortran
2793or C code. For example, you might have a function like this:
2794</p>
2795
2796<div class="code">
2797<pre>
2798int is_symmetric(double *mat, int rows, int columns);
2799</pre>
2800</div>
2801
2802<p>
2803In this case, you might want to pass some kind of higher-level object as an matrix. To do
2804this, you could write a multi-argument typemap like this:
2805</p>
2806
2807<div class="code">
2808<pre>
2809%typemap(in) (double *mat, int rows, int columns) {
2810 MatrixObject *a;
2811 a = GetMatrixFromObject($input); /* Get matrix somehow */
2812
2813 /* Get matrix properties */
2814 $1 = GetPointer(a);
2815 $2 = GetRows(a);
2816 $3 = GetColumns(a);
2817}
2818</pre>
2819</div>
2820
2821<p>
2822This kind of technique can be used to hook into scripting-language matrix packages such as
2823Numeric Python. However, it should also be stressed that some care is in order. For example,
2824when crossing languages you may need to worry about issues such as row-major vs. column-major
2825ordering (and perform conversions if needed).
2826</p>
2827
2828<H2><a name="runtime_type_checker"></a>10.8 The run-time type checker</H2>
2829
2830
2831<p>
2832Most scripting languages need type information at run-time. This type information
2833can include how to construct types, how to garbage collect types, and the inheritance
2834relationships between types. If the language interface does not provide its own type
2835information storage, the generated SWIG code needs to provide it.
2836</p>
2837
2838<p>
2839Requirements for the type system:
2840</p>
2841<ul>
2842<li>Store inheritance and type equivalence information and be able to correctly
2843re-create the type pointer.</li>
2844<li>Share type information between modules.</li>
2845<li>Modules can be loaded in any order, irregardless of actual type
2846dependency.</li>
2847<li>Avoid the use of dynamically allocated memory, and library/system calls in general.</li>
2848<li>Provide a reasonably fast implementation, minimizing the lookup time for all
2849language modules.</li>
2850<li>Custom, language specific information can be attached to types.</li>
2851<li>Modules can be unloaded from the type system.</li>
2852</ul>
2853
2854<H3><a name="Typemaps_nn45"></a>10.8.1 Implementation</H3>
2855
2856
2857<p>
2858The run-time type checker is used by many, but not all, of SWIG's supported target languages.
2859The run-time type checker features
2860are not required and are thus not used for strongly typed languages such as Java and C#.
2861The scripting and scheme based languages rely on it and it forms
2862a critical part of SWIG's operation for these languages.
2863</p>
2864
2865<p>
2866When pointers, arrays, and objects are wrapped by SWIG, they are normally converted
2867into typed pointer objects. For example, an instance of <tt>Foo *</tt> might be
2868a string encoded like this:
2869</p>
2870
2871<div class="diagram">
2872<pre>
2873_108e688_p_Foo
2874</pre>
2875</div>
2876
2877<p>
2878At a basic level, the type checker simply restores some type-safety to
2879extension modules. However, the type checker is also responsible for
2880making sure that wrapped C++ classes are handled
2881correctly---especially when inheritance is used. This is especially
2882important when an extension module makes use of multiple inheritance.
2883For example:
2884</p>
2885
2886<div class="code">
2887<pre>
2888class Foo {
2889 int x;
2890};
2891
2892class Bar {
2893 int y;
2894};
2895
2896class FooBar : public Foo, public Bar {
2897 int z;
2898};
2899</pre>
2900</div>
2901
2902<p>
2903When the class <tt>FooBar</tt> is organized in memory, it contains the contents
2904of the classes <tt>Foo</tt> and <tt>Bar</tt> as well as its own data members. For example:
2905</p>
2906
2907<div class="diagram">
2908<pre>
2909FooBar --&gt; | -----------| &lt;-- Foo
2910 | int x |
2911 |------------| &lt;-- Bar
2912 | int y |
2913 |------------|
2914 | int z |
2915 |------------|
2916</pre>
2917</div>
2918
2919<p>
2920Because of the way that base class data is stacked together, the
2921casting of a <tt>Foobar *</tt> to either of the base classes may
2922change the actual value of the pointer. This means that it is
2923generally not safe to represent pointers using a simple integer or a
2924bare <tt>void *</tt>---type tags are needed to implement correct
2925handling of pointer values (and to make adjustments when needed).
2926</p>
2927
2928<p>
2929In the wrapper code generated for each language, pointers are handled through
2930the use of special type descriptors and conversion functions. For example,
2931if you look at the wrapper code for Python, you will see code like this:
2932</p>
2933
2934<div class="code">
2935<pre>
2936if ((SWIG_ConvertPtr(obj0,(void **) &amp;arg1, SWIGTYPE_p_Foo,1)) == -1) return NULL;
2937</pre>
2938</div>
2939
2940<p>
2941In this code, <tt>SWIGTYPE_p_Foo</tt> is the type descriptor that
2942describes <tt>Foo *</tt>. The type descriptor is actually a pointer to a
2943structure that contains information about the type name to use in the
2944target language, a list of equivalent typenames (via typedef or
2945inheritance), and pointer value handling information (if applicable).
2946The <tt>SWIG_ConvertPtr()</tt> function is simply a utility function
2947that takes a pointer object in the target language and a
2948type-descriptor objects and uses this information to generate a C++
2949pointer. However, the exact name and calling conventions of the conversion
2950function depends on the target language (see language specific chapters for details).
2951</p>
2952
2953<p>
2954The actual type code is in swigrun.swg, and gets inserted near the top of the generated
2955swig wrapper file. The phrase "a type X that can cast into a type Y" means
2956that given a type X, it can be converted into a type Y. In other words, X is a derived
2957class of Y or X is a typedef of Y. The structure to store type information looks like this:
2958</p>
2959
2960<div class="code">
2961<pre>
2962/* Structure to store information on one type */
2963typedef struct swig_type_info {
2964 const char *name; /* mangled name of this type */
2965 const char *str; /* human readable name for this type */
2966 swig_dycast_func dcast; /* dynamic cast function down a hierarchy */
2967 struct swig_cast_info *cast; /* Linked list of types that can cast into this type */
2968 void *clientdata; /* Language specific type data */
2969} swig_type_info;
2970
2971/* Structure to store a type and conversion function used for casting */
2972typedef struct swig_cast_info {
2973 swig_type_info *type; /* pointer to type that is equivalent to this type */
2974 swig_converter_func converter; /* function to cast the void pointers */
2975 struct swig_cast_info *next; /* pointer to next cast in linked list */
2976 struct swig_cast_info *prev; /* pointer to the previous cast */
2977} swig_cast_info;
2978</pre>
2979</div>
2980
2981<p>
2982Each <tt>swig_type_info</tt> stores a linked list of types that it is equivalent to. Each entry in this
2983doubly linked list stores a pointer back to another swig_type_info structure,
2984along with a pointer to a conversion function. This conversion function is used
2985to solve the above problem of the FooBar class, correctly returning a pointer to
2986the type we want.
2987</p>
2988
2989<p>
2990The basic problem we need to solve is verifying and building arguments passed to functions.
2991So going back to the <tt>SWIG_ConvertPtr()</tt> function example from above, we are
2992expecting a <tt>Foo *</tt> and need to
2993check if <tt>obj0</tt> is in fact a <tt>Foo *</tt>. From before, <tt>SWIGTYPE_p_Foo</tt> is just
2994a pointer to the <tt>swig_type_info</tt> structure describing <tt>Foo *</tt>. So we loop though the
2995linked list of <tt>swig_cast_info</tt> structures attached to <tt>SWIGTYPE_p_Foo</tt>. If we see that the type of <tt>obj0</tt> is in the
2996linked list, we pass the object through the associated conversion function and
2997then return a positive. If we reach the end of the linked list without a match,
2998then <tt>obj0</tt> can not be converted to a <tt>Foo *</tt> and an error is generated.
2999</p>
3000
3001<p>
3002Another issue needing to be addressed is sharing type information between multiple modules.
3003More explicitly, we need
3004to have ONE <tt>swig_type_info</tt> for each type. If two modules both use the type, the
3005second module loaded must lookup and use the swig_type_info structure from the module already loaded.
3006Because no dynamic memory is used and the circular dependencies of the
3007casting information, loading the type information is somewhat tricky, and not explained here.
3008A complete description is in the <tt>common.swg</tt> file (and near the top of any generated file).
3009</p>
3010
3011<p>
3012Each module has one swig_module_info structure which looks like this:
3013</p>
3014
3015<div class="code">
3016<pre>
3017/* Structure used to store module information
3018 * Each module generates one structure like this, and the runtime collects
3019 * all of these structures and stores them in a circularly linked list.*/
3020typedef struct swig_module_info {
3021 swig_type_info **types; /* Array of pointers to swig_type_info structs in this module */
3022 int size; /* Number of types in this module */
3023 struct swig_module_info *next; /* Pointer to next element in circularly linked list */
3024 swig_type_info **type_initial; /* Array of initially generated type structures */
3025 swig_cast_info **cast_initial; /* Array of initially generated casting structures */
3026 void *clientdata; /* Language specific module data */
3027} swig_module_info;
3028</pre>
3029</div>
3030
3031<p>
3032Each module stores an array of pointers to <tt>swig_type_info</tt> structures and the number of
3033types in this module. So when a second module is loaded, it finds the <tt>swig_module_info</tt>
3034structure for the first module and searches the array of types. If any of its own
3035types are in the first module and have already been loaded, it uses those <tt>swig_type_info</tt>
3036structures rather than creating new ones. These <tt>swig_module_info</tt>
3037structures are chained together in a circularly linked list.
3038</p>
3039
3040<H3><a name="Typemaps_nn46"></a>10.8.2 Usage</H3>
3041
3042
3043<p>This section covers how to use these functions from typemaps. To learn how to
3044call these functions from external files (not the generated _wrap.c file), see
3045the <a href="Modules.html#external_run_time">External access to the run-time system</a>
3046section.</p>
3047
3048<p>When pointers are converted in a typemap, the typemap code often looks
3049similar to this:
3050</p>
3051
3052<div class="code">
3053<pre>
3054%typemap(in) Foo * {
3055 if ((SWIG_ConvertPtr($input, (void **) &amp;$1, $1_descriptor)) == -1) return NULL;
3056}
3057</pre>
3058</div>
3059
3060<p>
3061The most critical part is the typemap is the use of the <tt>$1_descriptor</tt>
3062special variable. When placed in a typemap, this is expanded into the
3063<tt>SWIGTYPE_*</tt> type descriptor object above. As a general rule,
3064you should always use <tt>$1_descriptor</tt> instead of trying to
3065hard-code the type descriptor name directly.
3066</p>
3067
3068<p>
3069There is another reason why you should always use the
3070<tt>$1_descriptor</tt> variable. When this special variable is
3071expanded, SWIG marks the corresponding type as "in use." When
3072type-tables and type information is emitted in the wrapper file,
3073descriptor information is only generated for those datatypes that were
3074actually used in the interface. This greatly reduces the size of the
3075type tables and improves efficiency.
3076</p>
3077
3078<p>
3079Occassionally, you might need to write a typemap that needs to convert
3080pointers of other types. To handle this, a special macro substition
3081<tt>$descriptor(type)</tt> can be used to generate the SWIG type
3082descriptor name for any C datatype. For example:
3083</p>
3084
3085<div class="code">
3086<pre>
3087%typemap(in) Foo * {
3088 if ((SWIG_ConvertPtr($input, (void **) &amp;$1, $1_descriptor)) == -1) {
3089 Bar *temp;
3090 if ((SWIG_ConvertPtr($input, (void **) &amp;temp, <b>$descriptor(Bar *)</b>) == -1) {
3091 return NULL;
3092 }
3093 $1 = (Foo *) temp;
3094 }
3095}
3096</pre>
3097</div>
3098
3099<p>
3100The primary use of <tt>$descriptor(type)</tt> is when writing typemaps for container
3101objects and other complex data structures. There are some restrictions on the argument---namely it must
3102be a fully defined C datatype. It can not be any of the special typemap variables.
3103</p>
3104
3105<p>
3106In certain cases, SWIG may not generate type-descriptors like you expect. For example,
3107if you are converting pointers in some non-standard way or working with an unusual
3108combination of interface files and modules, you may find that SWIG omits information
3109for a specific type descriptor. To fix this, you may need to use the <tt>%types</tt> directive.
3110For example:
3111</p>
3112
3113<div class="code">
3114<pre>
3115%types(int *, short *, long *, float *, double *);
3116</pre>
3117</div>
3118
3119<p>
3120When <tt>%types</tt> is used, SWIG generates type-descriptor
3121information even if those datatypes never appear elsewhere in the
3122interface file.
3123</p>
3124
3125<p>
3126A final problem related to the type-checker is the conversion of types
3127in code that is external to the SWIG wrapper file. This situation is
3128somewhat rare in practice, but occasionally a programmer may want to
3129convert a typed pointer object into a C++ pointer somewhere else in
3130their program. The only problem is that the SWIG type descriptor
3131objects are only defined in the wrapper code and not normally
3132accessible.
3133</p>
3134
3135<p>
3136To correctly deal with this situation, the following technique can be used:
3137</p>
3138
3139<div class="code">
3140<pre>
3141
3142/* Some non-SWIG file */
3143
3144/* External declarations */
3145extern void *SWIG_TypeQuery(const char *);
3146extern int SWIG_ConvertPtr(PyObject *, void **ptr, void *descr);
3147
3148void foo(PyObject *o) {
3149 Foo *f;
3150 static void *descr = 0;
3151 if (!descr) {
3152 descr = SWIG_TypeQuery("Foo *"); /* Get the type descriptor structure for Foo */
3153 assert(descr);
3154 }
3155 if ((SWIG_ConvertPtr(o,(void **) &amp;f, descr) == -1)) {
3156 abort();
3157 }
3158 ...
3159}
3160</pre>
3161</div>
3162
3163<p>
3164Further details about the run-time type checking can be found in the documentation for
3165individual language modules. Reading the source code may also help. The file
3166<tt>swigrun.swg</tt> in the SWIG library contains all of the source code for
3167type-checking. This code is also included in every generated wrapped file so you
3168probably just look at the output of SWIG to get a better sense for how types are
3169managed.
3170</p>
3171
3172<H2><a name="Typemaps_overloading"></a>10.9 Typemaps and overloading</H2>
3173
3174
3175<p>
3176In many target languages, SWIG fully supports C++ overloaded methods and functions. For example,
3177if you have a collection of functions like this:
3178</p>
3179
3180<div class="code">
3181<pre>
3182int foo(int x);
3183int foo(double x);
3184int foo(char *s, int y);
3185</pre>
3186</div>
3187
3188<p>
3189You can access the functions in a normal way from the scripting interpreter:
3190</p>
3191
3192<div class="targetlang">
3193<pre>
3194# Python
3195foo(3) # foo(int)
3196foo(3.5) # foo(double)
3197foo("hello",5) # foo(char *, int)
3198
3199# Tcl
3200foo 3 # foo(int)
3201foo 3.5 # foo(double)
3202foo hello 5 # foo(char *, int)
3203</pre>
3204</div>
3205
3206<p>
3207To implement overloading, SWIG generates a separate wrapper function for each overloaded method.
3208For example, the above functions would produce something roughly like this:
3209</p>
3210
3211<div class="code">
3212<pre>
3213// wrapper pseudocode
3214_wrap_foo_0(argc, args[]) { // foo(int)
3215 int arg1;
3216 int result;
3217 ...
3218 arg1 = FromInteger(args[0]);
3219 result = foo(arg1);
3220 return ToInteger(result);
3221}
3222
3223_wrap_foo_1(argc, args[]) { // foo(double)
3224 double arg1;
3225 int result;
3226 ...
3227 arg1 = FromDouble(args[0]);
3228 result = foo(arg1);
3229 return ToInteger(result);
3230}
3231
3232_wrap_foo_2(argc, args[]) { // foo(char *, int)
3233 char *arg1;
3234 int arg2;
3235 int result;
3236 ...
3237 arg1 = FromString(args[0]);
3238 arg2 = FromInteger(args[1]);
3239 result = foo(arg1,arg2);
3240 return ToInteger(result);
3241}
3242
3243</pre>
3244</div>
3245
3246<p>
3247Next, a dynamic dispatch function is generated:
3248</p>
3249
3250<div class="code">
3251<pre>
3252_wrap_foo(argc, args[]) {
3253 if (argc == 1) {
3254 if (IsInteger(args[0])) {
3255 return _wrap_foo_0(argc,args);
3256 }
3257 if (IsDouble(args[0])) {
3258 return _wrap_foo_1(argc,args);
3259 }
3260 }
3261 if (argc == 2) {
3262 if (IsString(args[0]) &amp;&amp; IsInteger(args[1])) {
3263 return _wrap_foo_2(argc,args);
3264 }
3265 }
3266 error("No matching function!\n");
3267}
3268</pre>
3269</div>
3270
3271<p>
3272The purpose of the dynamic dispatch function is to select the appropriate C++ function based on
3273argument types---a task that must be performed at runtime in most of SWIG's target languages.
3274</p>
3275
3276<p>
3277The generation of the dynamic dispatch function is a relatively tricky affair. Not only must input typemaps
3278be taken into account (these typemaps can radically change the types of arguments accepted), but overloaded
3279methods must also be sorted and checked in a very specific order to resolve potential ambiguity. A high-level
3280overview of this ranking process is found in the "<a href="SWIGPlus.html#SWIGPlus">SWIG and C++</a>" chapter. What isn't mentioned in that chapter
3281is the mechanism by which it is implemented---as a collection of typemaps.
3282</p>
3283
3284<p>
3285To support dynamic dispatch, SWIG first defines a general purpose type hierarchy as follows:
3286</p>
3287
3288<div class="diagram">
3289<pre>
3290Symbolic Name Precedence Value
3291------------------------------ ------------------
3292SWIG_TYPECHECK_POINTER 0
3293SWIG_TYPECHECK_VOIDPTR 10
3294SWIG_TYPECHECK_BOOL 15
3295SWIG_TYPECHECK_UINT8 20
3296SWIG_TYPECHECK_INT8 25
3297SWIG_TYPECHECK_UINT16 30
3298SWIG_TYPECHECK_INT16 35
3299SWIG_TYPECHECK_UINT32 40
3300SWIG_TYPECHECK_INT32 45
3301SWIG_TYPECHECK_UINT64 50
3302SWIG_TYPECHECK_INT64 55
3303SWIG_TYPECHECK_UINT128 60
3304SWIG_TYPECHECK_INT128 65
3305SWIG_TYPECHECK_INTEGER 70
3306SWIG_TYPECHECK_FLOAT 80
3307SWIG_TYPECHECK_DOUBLE 90
3308SWIG_TYPECHECK_COMPLEX 100
3309SWIG_TYPECHECK_UNICHAR 110
3310SWIG_TYPECHECK_UNISTRING 120
3311SWIG_TYPECHECK_CHAR 130
3312SWIG_TYPECHECK_STRING 140
3313SWIG_TYPECHECK_BOOL_ARRAY 1015
3314SWIG_TYPECHECK_INT8_ARRAY 1025
3315SWIG_TYPECHECK_INT16_ARRAY 1035
3316SWIG_TYPECHECK_INT32_ARRAY 1045
3317SWIG_TYPECHECK_INT64_ARRAY 1055
3318SWIG_TYPECHECK_INT128_ARRAY 1065
3319SWIG_TYPECHECK_FLOAT_ARRAY 1080
3320SWIG_TYPECHECK_DOUBLE_ARRAY 1090
3321SWIG_TYPECHECK_CHAR_ARRAY 1130
3322SWIG_TYPECHECK_STRING_ARRAY 1140
3323</pre>
3324</div>
3325
3326<p>
3327(These precedence levels are defined in <tt>swig.swg</tt>, a library file that's included by all target language modules.)
3328</p>
3329
3330<p>
3331In this table, the precedence-level determines the order in which types are going to be checked. Low values
3332are always checked before higher values. For example, integers are checked before floats, single values are checked
3333before arrays, and so forth.
3334</p>
3335
3336<p>
3337Using the above table as a guide, each target language defines a collection of "typecheck" typemaps.
3338The follow excerpt from the Python module illustrates this:
3339</p>
3340
3341<div class="code">
3342<pre>
3343/* Python type checking rules */
3344/* Note: %typecheck(X) is a macro for %typemap(typecheck,precedence=X) */
3345
3346%typecheck(SWIG_TYPECHECK_INTEGER)
3347 int, short, long,
3348 unsigned int, unsigned short, unsigned long,
3349 signed char, unsigned char,
3350 long long, unsigned long long,
3351 const int &amp;, const short &amp;, const long &amp;,
3352 const unsigned int &amp;, const unsigned short &amp;, const unsigned long &amp;,
3353 const long long &amp;, const unsigned long long &amp;,
3354 enum SWIGTYPE,
3355 bool, const bool &amp;
3356{
3357 $1 = (PyInt_Check($input) || PyLong_Check($input)) ? 1 : 0;
3358}
3359
3360%typecheck(SWIG_TYPECHECK_DOUBLE)
3361 float, double,
3362 const float &amp;, const double &amp;
3363{
3364 $1 = (PyFloat_Check($input) || PyInt_Check($input) || PyLong_Check($input)) ? 1 : 0;
3365}
3366
3367%typecheck(SWIG_TYPECHECK_CHAR) char {
3368 $1 = (PyString_Check($input) &amp;&amp; (PyString_Size($input) == 1)) ? 1 : 0;
3369}
3370
3371%typecheck(SWIG_TYPECHECK_STRING) char * {
3372 $1 = PyString_Check($input) ? 1 : 0;
3373}
3374
3375%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &amp;, SWIGTYPE [] {
3376 void *ptr;
3377 if (SWIG_ConvertPtr($input, (void **) &amp;ptr, $1_descriptor, 0) == -1) {
3378 $1 = 0;
3379 PyErr_Clear();
3380 } else {
3381 $1 = 1;
3382 }
3383}
3384
3385%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE {
3386 void *ptr;
3387 if (SWIG_ConvertPtr($input, (void **) &amp;ptr, $&amp;1_descriptor, 0) == -1) {
3388 $1 = 0;
3389 PyErr_Clear();
3390 } else {
3391 $1 = 1;
3392 }
3393}
3394
3395%typecheck(SWIG_TYPECHECK_VOIDPTR) void * {
3396 void *ptr;
3397 if (SWIG_ConvertPtr($input, (void **) &amp;ptr, 0, 0) == -1) {
3398 $1 = 0;
3399 PyErr_Clear();
3400 } else {
3401 $1 = 1;
3402 }
3403}
3404
3405%typecheck(SWIG_TYPECHECK_POINTER) PyObject *
3406{
3407 $1 = ($input != 0);
3408}
3409</pre>
3410</div>
3411
3412<p>
3413It might take a bit of contemplation, but this code has merely organized all of the basic C++ types, provided some simple type-checking
3414code, and assigned each type a precedence value.
3415</p>
3416
3417<p>
3418Finally, to generate the dynamic dispatch function, SWIG uses the following algorithm:
3419</p>
3420
3421<ul>
3422<li>Overloaded methods are first sorted by the number of required arguments.</li>
3423<li>Methods with the same number of arguments are then sorted by precedence values of argument types.</li>
3424<li>Typecheck typemaps are then emitted to produce a dispatch function that checks arguments in the correct order.</li>
3425</ul>
3426
3427<p>
3428If you haven't written any typemaps of your own, it is unnecessary to worry about the typechecking rules.
3429However, if you have written new input typemaps, you might have to supply a typechecking rule as well.
3430An easy way to do this is to simply copy one of the existing typechecking rules.
3431Here is an example,
3432</p>
3433
3434<div class="code">
3435<pre>
3436// Typemap for a C++ string
3437%typemap(in) std::string {
3438 if (PyString_Check($input)) {
3439 $1 = std::string(PyString_AsString($input));
3440 } else {
3441 SWIG_exception(SWIG_TypeError, "string expected");
3442 }
3443}
3444// Copy the typecheck code for "char *".
3445%typemap(typecheck) std::string = char *;
3446</pre>
3447</div>
3448
3449<p>
3450The bottom line: If you are writing new typemaps and you are using overloaded methods, you will probably
3451have to write typecheck code or copy existing code. Since this is a relatively new SWIG feature, there are
3452few examples to work with. However, you might look at some of the existing library files likes 'typemaps.i' for
3453a guide.
3454</p>
3455
3456<p>
3457<b>Notes:</b>
3458</p>
3459
3460<ul>
3461<li>Typecheck typemaps are not used for non-overloaded methods. Because of this, it is
3462still always necessary to check types in any "in" typemaps.
3463</li>
3464
3465<li>The dynamic dispatch process is only meant to be a heuristic. There are many corner
3466cases where SWIG simply can't disambiguate types to the same degree as C++. The only way to
3467resolve this ambiguity is to use the %rename directive to rename one of the overloaded methods (effectively
3468eliminating overloading).
3469</li>
3470
3471<li>
3472Typechecking may be partial. For example, if working with arrays, the typecheck code might
3473simply check the type of the first array element and use that to dispatch to the correct function.
3474Subsequent "in" typemaps would then perform more extensive type-checking.
3475</li>
3476
3477<li>Make sure you read the section on overloading in the "<a href="SWIGPlus.html#SWIGPlus">SWIG and C++</a>" chapter.
3478</li>
3479</ul>
3480
3481<H2><a name="Typemaps_nn48"></a>10.10 More about <tt>%apply</tt> and <tt>%clear</tt></H2>
3482
3483
3484<p>
3485In order to implement certain kinds of program behavior, it is sometimes necessary to
3486write sets of typemaps. For example, to support output arguments, one often writes
3487a set of typemaps like this:
3488</p>
3489
3490<div class="code">
3491<pre>
3492%typemap(in,numinputs=0) int *OUTPUT (int temp) {
3493 $1 = &amp;temp;
3494}
3495%typemap(argout) int *OUTPUT {
3496 // return value somehow
3497}
3498</pre>
3499</div>
3500
3501<p>
3502To make it easier to apply the typemap to different argument types and names, the <tt>%apply</tt> directive
3503performs a copy of all typemaps from one type to another. For example, if you specify this,
3504</p>
3505
3506<div class="code">
3507<pre>
3508%apply int *OUTPUT { int *retvalue, int32 *output };
3509</pre>
3510</div>
3511
3512<p>
3513then all of the <tt>int *OUTPUT</tt> typemaps are copied to <tt>int *retvalue</tt> and <tt>int32 *output</tt>.
3514</p>
3515
3516<p>
3517However, there is a subtle aspect of <tt>%apply</tt> that needs more description. Namely, <tt>%apply</tt> does not
3518overwrite a typemap rule if it is already defined for the target datatype. This behavior allows you to do two things:
3519</p>
3520
3521<ul>
3522<li>You can specialize parts of a complex typemap rule by first defining a few typemaps and then using
3523<tt>%apply</tt> to incorporate the remaining pieces.
3524</li>
3525
3526<li>Sets of different typemaps can be applied to the same datatype using repeated <tt>%apply</tt> directives.
3527</li>
3528</ul>
3529
3530<p>
3531For example:
3532</p>
3533
3534<div class="code">
3535<pre>
3536%typemap(in) int *INPUT (int temp) {
3537 temp = ... get value from $input ...;
3538 $1 = &amp;temp;
3539}
3540
3541%typemap(check) int *POSITIVE {
3542 if (*$1 &lt;= 0) {
3543 SWIG_exception(SWIG_ValueError,"Expected a positive number!\n");
3544 return NULL;
3545 }
3546}
3547
3548...
3549%apply int *INPUT { int *invalue };
3550%apply int *POSITIVE { int *invalue };
3551</pre>
3552</div>
3553
3554<p>
3555Since <tt>%apply</tt> does not overwrite or replace any existing rules, the only way to reset behavior is to
3556use the <tt>%clear</tt> directive. <tt>%clear</tt> removes all typemap rules defined for a specific datatype. For
3557example:
3558</p>
3559
3560<div class="code">
3561<pre>
3562%clear int *invalue;
3563</pre>
3564</div>
3565
3566<H2><a name="Typemaps_nn49"></a>10.11 Reducing wrapper code size</H2>
3567
3568
3569<p>
3570Since the code supplied to a typemap is inlined directly into wrapper functions, typemaps can result
3571in a tremendous amount of code bloat. For example, consider this typemap for an array:
3572</p>
3573
3574<div class="code">
3575<pre>
3576%typemap(in) float [ANY] {
3577 int i;
3578 if (!PySequence_Check($input)) {
3579 PyErr_SetString(PyExc_ValueError,"Expected a sequence");
3580 return NULL;
3581 }
3582 if (PySequence_Length($input) != $1_dim0) {
3583 PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements");
3584 return NULL;
3585 }
3586 $1 = (float) malloc($1_dim0*sizeof(float));
3587 for (i = 0; i &lt; $1_dim0; i++) {
3588 PyObject *o = PySequence_GetItem($input,i);
3589 if (PyNumber_Check(o)) {
3590 $1[i] = (float) PyFloat_AsDouble(o);
3591 } else {
3592 PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");
3593 free(result);
3594 return NULL;
3595 }
3596 }
3597}
3598</pre>
3599</div>
3600
3601<p>
3602If you had a large interface with hundreds of functions all accepting
3603array parameters, this typemap would be replicated
3604repeatedly--generating a huge amount of code. A better approach might
3605be to consolidate some of the typemap into a function. For example:
3606</p>
3607
3608<div class="code">
3609<pre>
3610%{
3611/* Define a helper function */
3612static float *
3613convert_float_array(PyObject *input, int size) {
3614 int i;
3615 float *result;
3616 if (!PySequence_Check(input)) {
3617 PyErr_SetString(PyExc_ValueError,"Expected a sequence");
3618 return NULL;
3619 }
3620 if (PySequence_Length(input) != size) {
3621 PyErr_SetString(PyExc_ValueError,"Size mismatch. ");
3622 return NULL;
3623 }
3624 result = (float) malloc(size*sizeof(float));
3625 for (i = 0; i &lt; size; i++) {
3626 PyObject *o = PySequence_GetItem(input,i);
3627 if (PyNumber_Check(o)) {
3628 result[i] = (float) PyFloat_AsDouble(o);
3629 } else {
3630 PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");
3631 free(result);
3632 return NULL;
3633 }
3634 }
3635 return result;
3636}
3637%}
3638
3639%typemap(in) float [ANY] {
3640 $1 = convert_float_array($input, $1_dim0);
3641 if (!$1) return NULL;
3642}
3643%}
3644</pre>
3645</div>
3646
3647<H2><a name="Typemaps_nn47"></a>10.12 Passing data between typemaps</H2>
3648
3649
3650<p>
3651It is also important to note that the primary use of local variables
3652is to create stack-allocated objects for temporary use inside a
3653wrapper function (this is faster and less-prone to error than
3654allocating data on the heap). In general, the variables are not intended
3655to pass information between different types of typemaps. However, this
3656can be done if you realize that local names have the argument number appended
3657to them. For example, you could do this:
3658</p>
3659
3660<div class="code">
3661<pre>
3662%typemap(in) int *(int temp) {
3663 temp = (int) PyInt_AsLong($input);
3664 $1 = &amp;temp;
3665}
3666
3667%typemap(argout) int * {
3668 PyObject *o = PyInt_FromLong(temp$argnum);
3669 ...
3670}
3671</pre>
3672</div>
3673
3674<p>
3675In this case, the <tt>$argnum</tt> variable is expanded into the argument
3676number. Therefore, the code will reference the appropriate local
3677such as <tt>temp1</tt> and <tt>temp2</tt>. It should be noted that there are
3678plenty of opportunities to break the universe here and that accessing locals
3679in this manner should probably be avoided. At the very least, you should make
3680sure that the typemaps sharing information have exactly the same types and names.
3681</p>
3682
3683
3684<H2><a name="Typemaps_nn51"></a>10.13 Where to go for more information?</H2>
3685
3686
3687<p>
3688The
3689best place to find out more information about writing typemaps is to
3690look in the SWIG library. Most language modules define all of their
3691default behavior using typemaps. These are found in files such as
3692<tt>python.swg</tt>, <tt>perl5.swg</tt>, <tt>tcl8.swg</tt> and so
3693forth. The <tt>typemaps.i</tt> file in the library also contains
3694numerous examples. You should look at these files to get a feel
3695for how to define typemaps of your own.
3696Some of the language modules support additional typemaps and further
3697information is available in the individual chapters for each target language.
3698</p>
3699
3700</body>
3701</html>