1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
|
<html>
<head>
<title>SWIG Internals</title>
</head>
<body>
<center>
<h1>SWIG Internals Manual</h1>
</b>
</center>
<p>
<p>
(Note : This is a work in progress.)
<h2>Table of Contents</h2>
<ul>
<li><a name="i1" href="#1">1. Introduction</a>
<ul>
<li><a name="i1.1" href="#1.1">1.1 Directory Guide</a>
<li><a name="i1.2" href="#1.2">1.2 Overall Program Flow</a>
</ul>
<li><a name="i2" href="#2">2. DOH</a>
<ul>
<li><a name="i2.1" href="#2.1">2.1 Motivation and Background</a>
<li><a name="i2.2" href="#2.2">2.2 Basic Types</a>
<li><a name="i2.3" href="#2.3">2.3 Creating, Copying and Destroying Objects</a>
<li><a name="i2.4" href="#2.4">2.4 A Word About Mutability and Copying</a>
<li><a name="i2.5" href="#2.5">2.5 Strings</a>
<li><a name="i2.6" href="#2.6">2.6 Lists</a>
<li><a name="i2.7" href="#2.7">2.7 Hash Tables</a>
<li><a name="i2.8" href="#2.8">2.8 Files</a>
<li><a name="i2.9" href="#2.9">2.9 Void Objects</a>
<li><a name="i2.10" href="#2.10">2.10 Utility Functions</a>
</ul>
<li><a name="i3" href="#3">3. Types and Typemaps</a>
<li><a name="i4" href="#4">4. Parsing</a>
<li><a name="i5" href="#5">5. C/C++ Wrapper Support Functions</a>
<li><a name="i6" href="#6">6. Symbol Naming Guidelines for Generated C/C++ Code</a>
<li><a name="i7" href="#7">7. Debugging SWIG</a>
<ul>
<li><a name="i7.1" href="#7.1">7.1 Debugging DOH Types The Hard Way</a>
<li><a name="i7.2" href="#7.2">7.2 Debugging DOH memory allocation problems</a>
</ul>
</ul>
<a name="1" href="#i1">
<h2>1. Introduction</h2>
</a>
This document details SWIG internals: architecture and sometimes
implementation. The first few sections concentrate on data structures,
interfaces, conventions and code shared by all language targets.
Subsequent sections focus on a particular language.
<p>
The audience is assumed to be SWIG developers (who should also read the
<a href="engineering.html">SWIG Engineering Manual</a> before starting
to code).
<a name="1.1" href="#i1.1">
<h3>1.1 Directory Guide</h3>
</a>
<table border=1>
<tr><td><a href="index.html">Doc</a></td>
<td>HTML documentation. If you find a documentation bug, please
<a href="mailto:bug-swig-doc@glug.org">let us know</a>.</td>
</tr>
<tr><td>Examples</td>
<td>This subdir tree contains examples of using SWIG w/ different
scripting languages, including makefiles. Typically, there are the
"simple" and "class" examples, w/ some languages offering additional
examples. See the README more index.html file in each directory
for more info. [FIXME: Ref SWIG user manual.]</td>
</tr>
<tr><td>Lib</td>
<td>These are the <tt>.i</tt> (interface) files that form the SWIG
installed library. Language-specific files are in subdirectories (for
example, guile/typemaps.i). Each language also has a <tt>.swg</tt> file
implementing runtime type support for that language. The SWIG library
is not versioned.</td>
</tr>
<tr><td>Misc</td>
<td>Currently this subdir only contains file <tt>fileheader</tt>. See
the <a href="engineering.html">Engineering Manual</a> for more
info.</td>
</tr>
<tr><td>Source</td>
<td>The C and C++ source code for the <tt>swig</tt> executable is in this
subdir tree.</td>
<table border=1>
<tr><td>DOH</td>
<td>C library providing memory allocation, file access and generic
containers.</td>
</tr>
<tr><td>Include</td>
<td>Configuration .h files</td>
</tr>
<tr><td>CParse</td>
<td>Parser (lex / yacc) files and support</td>
</tr>
<tr><td>Modules</td>
<td>Language-specific callbacks that does actual code generation (each
language has a .cxx and a .h file).</td>
</tr>
<tr><td>Preprocessor</td>
<td>SWIG-specialized C/C++ preprocessor.</td>
</tr>
<tr><td>Swig</td>
<td>This directory contains the ANSI C core of the system
and contains generic functions related to types, file handling,
scanning, and so forth.</td>
</tr>
</table></td>
</tr>
<tr><td>Tools</td>
<td>The mkdist.py script and other tools.</td>
</tr>
<tr><td>Win</td>
<td>This improperly-named (spit spit) subdir only has README.txt.</td>
</tr>
</table>
<a name="1.2" href="#1.2">
<h3>1.2 Overall Program Flow</h3>
</a>
Here is the general control flow and where under subdir <tt>Source</tt>
to look for code:
<ul>
<li> <tt>Modules/swigmain.cxx:main()</tt> is the program entry
point. It parses the language-specifying command-line option (for
example, <tt>-java</tt>), creating a new language-specific wrapping
object (each language is a C++ class derived from base class
<tt>Language</tt>). This object and the command-line is passed to
<tt>SWIG_main()</tt>, whose return value is the program exit value.
<li> <tt>Modules/main.cxx:SWIG_main()</tt> is the "real" main. It
initializes the preprocessor and typemap machinery, defines some
preprocessor symbols, locates the SWIG library, processes common
command-line options, and then calls the language-specific command-line
parser. From here there are three paths: "help", "checkout" and
everything else.
<ul>
<li> In "help" mode, clean up open files and exit.
<li> In "checkout" mode, copy specified files from the SWIG library
to the current directory. Errors cause error messages but no
non-local exits.
<li> Otherwise, do wrapping: determine output file name(s), define
some preprocessor symbols and run the preprocessor, initialize
the interface-definition parser, set up the typemap for handling
new return strings, and finally do the language-specific parse
(by calling the language object's <tt>parse()</tt> method), which
creates output files by side-effect.
</ul>
Afterwards, remove temporary files, and clean up. If the command-line
included <tt>-freeze</tt>, go into an infinite loop; otherwise return the
error count.
<li> The language-specific <tt>parse()</tt> (and all other
language-specific code) lives in <tt>Modules/foo.{h,cxx}</tt> for
language Foo. Typically, <tt>FOO::parse()</tt> calls
<tt>FOO::headers()</tt> and then the global function <tt>yyparse()</tt>,
which uses the callbacks registered by <tt>SWIG_main()</tt> above.
</ul>
<a name="2" href="#i2">
<h2>2. DOH</h2>
</a>
DOH is a collection of low-level objects such as strings, lists, and
hash tables upon which the rest of SWIG is built. The name 'DOH'
unofficially stands for "Dave's Object Hack", but it's also a good
expletive to use when things don't work (as in "SWIG core
dumped---DOH!").
<a name="2.1" href="#2.1">
<h3>2.1 Motivation and Background</h3>
</a>
The development of DOH is influenced heavily by the problems
encountered during earlier attempts to create a C++ based version of
SWIG2.0. In each of these attempts (over a 3 year period), the
resulting system always ended up growing into a colossal nightmare of
large inheritance hierarchies and dozens of specialized classes for
different types of objects (functions, variables, constants, etc.).
The end result was that the system was tremendously complicated,
difficult to understand, difficult to maintain, and fairly inflexible
in the grand scheme of things.
<p>
DOH takes a different approach to tackling the complexity problem.
First, rather than going overboard with dozens of types and class
definitions, DOH only defines a handful of simple yet very useful
objects that are easy to remember. Second, DOH uses dynamic
typing---one of the features that make scripting languages so useful
and which make it possible to accomplish things with much less code.
Finally, DOH utilizes a few coding tricks that allow it to perform
a limited form of function overloading for certain C datatypes (more
on that a little later).
<p>
The key point to using DOH is that instead of thinking about code in
terms of highly specialized C data structures, just about everything
ends up being represented in terms of a just a few datatypes. For
example, structures are replaced by DOH hash tables whereas arrays are
replaced by DOH lists. At first, this is probably a little strange to
most C/C++ programmers, but in the long run in makes the system
extremely flexible and highly extensible. Also, in terms of coding,
many of the newly DOH-based subsystems are less than half the size (in
lines of code) of the earlier C++ implementation.
<a name="2.2" href="#i2.2">
<h3>2.2 Basic Types</h3>
</a>
The following built-in types are currently provided by DOH:
<ul>
<li><b>String</b>. A string of characters with automatic memory
management and high-level operations such as string replacement. In addition,
strings support file I/O operations that make it possible to use them just
about anyplace a file can be used.
<p>
<li><b>List</b>. A list of arbitrary DOH objects (of possibly mixed types).
<p>
<li><b>Hash</b>. A hash table that maps a set of string keys to a set of arbitrary
DOH objects. The DOH version of an associative array for all of you Perl fans.
<p>
<li><b>File</b>. A DOH wrapper around the C FILE * structure. This is provided
since other objects sometimes want to behave like files (strings for instance).
<p>
<li><b>Void</b>. A DOH wrapper around an arbitrary C pointer. This can be used
if you want to place arbitrary C data structures in DOH lists and hash tables.
</ul>
Due to dynamic typing, all of the objects in DOH are represented by pointers
of type <tt>DOH *</tt>. Furthermore, all objects are completely
opaque--that means that the only way to access the internals of an
object is through a well-defined public API. For convenience, the following
symbolic names are sometimes used to improve readability:
<ul>
<Li><tt>DOHString *</tt>. A String object.
<li><tt>DOHList *</tt>. A list object.
<li><tt>DOHHash *</tt>. A hash object.
<li><tt>DOHFile *</tt>. A file object.
<li><tt>DOHVoid *</tt>. A void object.
<li><tt>DOHString_or_char *</tt>. A DOH String object or a raw C "char *".
</ul>
It should be stressed that all of these names are merely symbolic aliases to the
type <tt>DOH *</tt> and that no compile-time type checking is performed (of course,
a runtime error may occur if you screw up).
<a name="2.3" href="#i2.3">
<h3>2.3 Creating, Copying, and Destroying Objects </h3>
</a>
The following functions can be used to create new DOH objects
<ul>
<Li><tt>NewString(DOHString_or_char *value)</tt><br>
Create a new string object with contents initially
set to value. value can be either a C string or a DOH string object.
<p>
<li><tt>NewStringf(char *fmt, ...)</tt><br>
Create a new string object with contents initially set to
a formatted string. Think of this as being sprintf() combined with an object constructor.
<p>
<li><tt>NewList()</tt><br>
Create a new list object that is initially empty.
<p>
<Li><tt>NewHash()</tt><br>
Create a new hash object that is initially empty.
<p>
<li><tt>NewFile(DOHString_or_char *filename, char *mode)</tt><br>
Open a file and return a file object. This is a
wrapper around the C <tt>fopen()</tt> library call.
<p>
<li><tt>NewFileFromFile(FILE *f)</tt><br>
Create a new file object given an already opened <tt>FILE *</tt> object.
<p>
<li><tt>NewVoid(void *obj, void (*del)(void *))</tt><br>
Create a new DOH object that is a wrapper around an
arbitrary C pointer. <tt>del</tt> is an optional destructor function that will be called when the object
is destroyed.
</ul>
Any object can be copied using the <tt>Copy()</tt> function. For example:
<blockquote>
<pre>
DOH *a, *b, *c, *d;
a = NewString("Hello World");
b = NewList();
c = Copy(a); /* Copy the string a */
d = Copy(b); /* Copy the list b */
</pre>
</blockquote>
Copies of lists and hash tables are shallow. That is, their contents are only copied by reference.
<p>
Objects can be deleted using the <tt>Delete()</tt> function. For example:
<blockquote>
<pre>
DOH *a = NewString("Hello World");
...
Delete(a); /* Destroy a */
</pre>
</blockquote>
All objects are referenced counted and given a reference count of 1 when initially created. The
<tt>Delete()</tt> function only destroys an object when the reference count reaches zero. When
an object is placed in a list or hash table, it's reference count is automatically increased. For example:
<blockquote>
<pre>
DOH *a, *b;
a = NewString("Hello World");
b = NewList();
Append(b,a); /* Increases refcnt of a to 2 */
Delete(a); /* Decreases refcnt of a to 1 */
Delete(b); /* Destroys b, and destroys a */
</pre>
</blockquote>
Should it ever be necessary to manually increase the reference count of an object, the DohIncref() function
can be used:
<blockquote>
<pre>
DOH *a = NewString("Hello");
DohIncref(a);
</pre>
</blockquote>
<a name="2.4" href="#i2.4">
<h3>2.4 A Word About Mutability and Copying</h3>
</a>
All DOH objects are mutable regardless of their current reference
count. For example, if you create a string and then create a 1000
references to it (in lists and hash tables), changes to the string
will be reflected in all of the references. Therefore, if you need to
make any kind of local change, you should first make a copy using the
Copy() function. Caveat: when copying lists and hash tables, elements
are copied by reference.
<a name="2.5" href="#i2.5">
<h3>2.5 Strings</h3>
</a>
The DOH String type is perhaps the most flexible object. First, it supports a variety of string-oriented
operations. Second, it supports many of the same operations as lists. Finally, strings provide file I/O
operations that allow them to be used interchangeably with DOH file objects.
[ TODO ]
<a name="2.6" href="#i2.6">
<h3>2.6 Lists</h3>
</a>
<p>
Example usage of lists:
</p>
<blockquote>
<pre>
/* Create and populate */
List *list = NewList();
Append(list, NewString("listval1"));
Append(list, NewString("listval2"));
Append(list, NewString("listval3"));
Append(list, NewString("listval4"));
Append(list, NewString("listval5"));
/* Size */
Printf(stdout, "list len: %d\n", Len(list));
/* Delete */
Delitem(list, 3);
/* Replace */
Setitem(list, 0, NewString("newlistval1"));
/* Get */
String *item = Getitem(list,1);
if (item)
Printf(stdout, "get: %s\n", item);
else
Printf(stdout, "get: [non-existent]\n");
/* Iterate through the container */
int len = Len(list);
for (int i=0; i<len; i++) {
String *item = Getitem(list,i);
Printf(stdout, "list item: %s\n", item);
}
</blockquote>
</pre>
<p>
Resulting output:
</p>
<blockquote>
<pre>
hash len: 5
get: hashval2
hash item: hashval5 [h5]
hash item: hashval1 [h1]
hash item: hashval2 [h2]
hash item: hashval3 [h3]
</pre>
</blockquote>
<a name="2.7" href="#i2.7">
<h3>2.7 Hash tables </h3>
</a>
<p>
Example usage of hash tables:
</p>
<blockquote>
<pre>
/* Create and populate */
Hash *hash = NewHash();
Setattr(hash, "h1", NewString("hashval1"));
Setattr(hash, "h2", NewString("hashval2"));
Setattr(hash, "h3", NewString("hashval3"));
Setattr(hash, "h4", NewString("hashval4"));
Setattr(hash, "h5", NewString("hashval5"));
/* Size */
Printf(stdout, "hash len: %d\n", Len(hash));
/* Delete */
Delattr(hash, "h4");
/* Get */
String *item = Getattr(hash, "h2");
if (item)
Printf(stdout, "get: %s\n", item);
else
Printf(stdout, "get: [non-existent]\n");
/* Iterate through the container */
Iterator it;
for (it = First(hash); it.key; it= Next(it))
Printf(stdout, "hash item: %s [%s]\n", (it.item), (it.key));
</pre>
</blockquote>
<p>
Resulting output:
</p>
<blockquote>
<pre>
list len: 5
get: listval2
list item: newlistval1
list item: listval2
list item: listval3
list item: listval5
</pre>
</blockquote>
<a name="2.8" href="#i2.8">
<h3>2.8 Files </h3>
</a>
[ TODO ]
<a name="2.9" href="#i2.9">
<h3>2.9 Void objects </h3>
</a>
[ TODO ]
<a name="2.10" href="#i2.10">
<h3>2.10 Utility functions </h3>
</a>
[ TODO ]
<a name="3" href="#i3">
<h2>3. Types and Typemaps</h2>
</a>
<p>
The representation and manipulation of types is currently in the
process of being reorganized and (hopefully) simplified. The
following list describes the current set of functions that are used to
manipulate datatypes.
<ul>
<li><tt>SwigType_str(SwigType *t, char *name)</tt>.<br>
This function produces the exact string
representation of the datatype <tt>t</tt>. <tt>name</tt> is an optional parameter that
specifies a declaration name. This is used when dealing with more complicated datatypes
such as arrays and pointers to functions where the output might look something like
"<tt>int (*name)(int, double)</tt>".
<p>
<li><tt>SwigType_lstr(SwigType *t, char *name)</tt>.<br>
This function produces a string
representation of a datatype that can be safely be assigned a value (i.e., can be used as the
"lvalue" of an expression). To do this, qualifiers such as "const", arrays, and references
are stripped away or converted into pointers. For example:
<blockquote>
<pre>
Original Datatype lstr()
------------------ --------
const char *a char *a
double a[20] double *a
double a[20][30] double *a
double &a double *a
</pre>
</blockquote>
The intent of the lstr() function is to produce local variables inside wrapper functions--all
of which must be reassignable types since they are the targets of conversions from a scripting
representation.
<p>
<li><tt>SwigType_rcaststr(SwigType *t, char *name)</tt>.
<br> This function produces a string
that casts a type produced by the <tt>lstr()</tt> function to the type produced by the
<tt>str()</tt> function. You might view it as the inverse of lstr(). This function only produces
output when it needs to (when str() and lstr() produce different results). Furthermore, an optional
name can be supplied when the cast is to be applied to a specific name. Examples:
<blockquote>
<pre>
Original Datatype rcaststr()
------------------ ---------
char *a
const char *a (const char *) name
double a[20] (double *) name
double a[20][30] (double (*)[30]) name
double &a (double &) *name
</pre>
</blockquote>
<p>
<li><tt>SwigType_lcaststr(SwigType *t, char *name)</tt>.
<br> This function produces a string
that casts a type produced by the <tt>str()</tt> function to the type produced by the
<tt>lstr()</tt> function. This function only produces
output when it needs to (when str() and lstr() produce different results). Furthermore, an optional
name can be supplied when the cast is to be applied to a specific name.
<blockquote>
<pre>
Original Datatype lcaststr()
------------------ ---------
char *a
const char *a (char *) name
double a[20] (double *) name
double a[20][30] (double *) name
double &a (double *) &name
</pre>
</blockquote>
<p>
<li><tt>SwigType_manglestr(SwigType *t)</tt>. <br>
Produces a type-string that is used to identify this datatype in the target scripting language.
Usually this string looks something like "<tt>_p_p_double</tt>" although the target language
may redefine the output for its own purposes. Normally this function strips all qualifiers,
references, and arrays---producing a mangled version of the type produced by the <tt>lstr()</tt> function.
</ul>
The following example illustrates the intended use of the above functions when creating wrapper
functions using shorthand pseudocode. Suppose you had a function like this:
<blockquote>
<pre>
int foo(int a, double b[20][30], const char *c, double &d);
</pre>
</blockquote>
Here's how a wrapper function would be generated using the type generation functions above:
<blockquote>
<pre>
wrapper_foo() {
lstr("int","result")
lstr("int","arg0")
lstr("double [20][30]", "arg1")
lstr("const char *", "arg2")
lstr("double &", "arg3")
...
get arguments
...
result = (lcaststr("int")) foo(rcaststr("int","arg0"),
rcaststr("double [20][30]","arg1"),
rcaststr("const char *", "arg2"),
rcaststr("double &", "arg3"))
...
}
</pre>
</blockquote>
Here's how it would look with the corresponding output filled in:
<blockquote>
<pre>
wrapper_foo() {
int result;
int arg0;
double *arg1;
char *arg2;
double *arg3;
...
get arguments
...
result = (int) foo(arg0,
(double (*)[30]) arg1,
(const char *) arg2,
(double &) *arg3);
...
}
</pre>
</blockquote>
<b>Notes:</b>
<ul>
<li>For convenience, the string generation functions return a
"<tt>char *</tt>" that points to statically allocated memory living
inside the type library. Therefore, it is never necessary (and it's
an error) to free the pointer returned by the functions. Also, if you
need to save the result, you should make a copy of it. However, with
that said, it is probably worth nothing that these functions do cache
the last 8 results. Therefore, it's fairly safe to make a handful of
repeated calls without making any copies.
</ul>
[TODO]
<a name="4" href="#i4">
<h2>4. Parsing</h2>
</a>
[TODO]
<a name="5" href="#i5">
<h2>5. The C/C++ Wrapping Layer</h2>
</a>
Added: Dave Beazley (July 22, 2000)
<p>
When SWIG generates wrappers, it tries to provide a mostly seamless integration
with the original code. However, there are a number of problematic features
of C/C++ programs that complicate this interface.
<ul>
<li><b>Passing and returning structures by value.</b> When used, SWIG converts
all pass-by-value functions into wrappers that pass by reference. For example:
<blockquote>
<pre>
double dot_product(Vector a, Vector b);
</pre>
</blockquote>
gets turned into a wrapper like this:
<blockquote>
<pre>
double wrap_dot_product(Vector *a, Vector *b) {
return dot_product(*a,*b);
}
</pre>
</blockquote>
Functions that return by value require a memory allocation to store the result. For example:
<blockquote>
<pre>
Vector cross_product(Vector *a, Vector *b);
</pre>
</blockquote>
become
<blockquote>
<pre>
Vector *wrap_cross_product(Vector *a, Vector *b) {
Vector *result = (Vector *) malloc(sizeof(Vector));
*result = cross_product(a,b);
return result;
}
</pre>
</blockquote>
Note: If C++ is being wrapped, the default copy constructor is used
instead of malloc() to create a copy of the return result.
<p>
<li><b>C++ references</b>. C++ references are handled exactly the same as
pass/return by value except that a memory allocation is not made for functions
that return a reference.
<p>
<li><b>Qualifiers such as "const" and "volatile".</b> SWIG strips all
qualifiers from the interface presented to the target language.
Besides, what in the heck is "const" in Perl anyways?
<p>
<li><b>Instance Methods</b>. Method invocations are handled as a function call in which
a pointer to the object (the "this" pointer) appears as the first argument. For example, in
the following class:
<blockquote>
<pre>
class Foo {
public:
double bar(double);
};
</pre>
</blockquote>
The "bar" method is wrapped by a function like this:
<blockquote>
<pre>
double Foo_bar(Foo *self, double arg0) {
return self->bar(arg0);
}
</pre>
</blockquote>
<p>
<li><b>Structure/class data members</b>. Data members are handled by creating a pair
of wrapper functions that set and get the value respectively. For example:
<blockquote>
<pre>
struct Foo {
int x;
};
</pre>
</blockquote>
gets wrapped as follows:
<blockquote>
<pre>
int Foo_x_get(Foo *self) {
return self->x;
}
int Foo_x_set(Foo *self, int value) {
return (self->x = value);
}
</pre>
</blockquote>
<p>
<li><b>Constructors</b>. Constructors for C/C++ data structures are wrapped by
a function like this:
<blockquote>
<pre>
Foo *new_Foo() {
return new Foo;
}
</pre>
</blockquote>
Note: For C, new objects are created using the calloc() function.
<p>
<li><b>Destructors</b>. Destructors for C/C++ data structures are wrapper like this:
<blockquote>
<pre>
void delete_Foo(Foo *self) {
delete self;
}
</pre>
</blockquote>
Note: For C, objects are destroyed using free().
</ul>
The creation of wrappers and various type transformations are handled by a collection of functions
found in the file <tt>Source/Swig/cwrap.c</tt>.
<ul>
<li>
<tt>char *Swig_clocal(DataType *t, char *name, char *value)</tt><br>
This function creates a string containing the declaration of a local variable with
type <tt>t</tt>, name <tt>name</tt>, and default value <tt>value</tt>. This local
variable is stripped of all qualifiers and will be a pointer if the type is a reference
or user defined type.
<p>
<li>
<tt>DataType *Swig_clocal_type(DataType *t)</tt><br>
Returns a type object corresponding to the type string produced by the Swig_clocal() function.
<p>
<li><tt>char *Swig_clocal_deref(DataType *t, char *name)</tt><br>
This function is the inverse of the <tt>clocal()</tt> function. Given a type and a name,
it produces a string containing the code needed to cast/convert the type produced by
<tt>Swig_clocal()</tt> back into it's original type.
<p>
<li><tt>char *Swig_clocal_assign(DataType *t, char *name)</tt><br>
Given a type and name, this produces a string containing the code (and an optional cast)
needed to make an assignment from the real datatype to the local datatype produced
by <tt>Swig_clocal()</tt>. Kind of the opposite of deref().
<p>
<li><tt>int Swig_cargs(Wrapper *w, ParmList *l)</tt><br>
Given a wrapper function object and a list of parameters, this function declares a set
of local variables for holding all of the parameter values (using Swig_clocal()). Returns
the number of parameters. In addition, this function sets the local name of each parameter
which can be retrieved using the <tt>Parm_Getlname()</tt> function.
<p>
<li><tt>void Swig_cresult(Wrapper *w, DataType *t, char *resultname, char *decl)</tt><br>
Generates the code needed to set the result of a wrapper function and performs all of
the needed memory allocations for ANSI C (if necessary). <tt>t</tt> is the type of the
result, <tt>resultname</tt> is the name of the result variable, and <tt>decl</tt> is
a string that contains the C code which produces the result.
<p>
<li><tt>void Swig_cppresult(Wrapper *w, DataType *t, char *resultname, char *decl)</tt><br>
Generates the code needed to set the result of a wrapper function and performs all of
the needed memory allocations for C++ (if necessary). <tt>t</tt> is the type of the
result, <tt>resultname</tt> is the name of the result variable, and <tt>decl</tt> is
a string that contains the C code which produces the result.
<p>
<li><tt>Wrapper *Swig_cfunction_wrapper(char *fname, DataType *rtype, ParmList *parms, char *code)</tt><br>
Create a wrapper around a normal function declaration. <tt>fname</tt> is the name of the wrapper,
<tt>rtype</tt> is the return type, <tt>parms</tt> are the function parameters, and <tt>code</tt> is a
string containing the code in the function body.
<p>
<li><tt>Wrapper *Swig_cmethod_wrapper(char *classname, char *methodname, DataType *rtype, DataType *parms, char *code)</tt><br>
<p>
<li><tt>char *Swig_cfunction_call(char *name, ParmList *parms)</tt>
This function produces a string containing the code needed to call a C function.
The string that is produced contains all of the transformations needed to convert
pass-by-value into pass-by-reference as well as handle C++ references. Produces
a string like "name(arg0, arg1, ..., argn)".
</ul>
Here is a short example showing how these functions could be used. Suppose you had a
C function like this:
<blockquote>
<pre>
double dot_product(Vector a, Vector b);
</pre>
</blockquote>
Here's how you might write a really simple wrapper function
<blockquote>
<pre>
ParmList *l = ... parameter list of the function ...
DataType *t = ... return type of the function ...
char *name = ... name of the function ...
Wrapper *w = NewWrapper();
Printf(w->def,"void wrap_%s() {\n", name);
/* Declare all of the local variables */
Swig_cargs(w, l);
/* Convert all of the arguments */
...
/* Make the function call and declare the result variable */
Swig_cresult(w,t,"result",Swig_cfunction(name,l));
/* Convert the result into whatever */
...
Printf(w->code,"}\n");
Wrapper_print(w,out);
</pre>
</blockquote>
The output of this would appear as follows:
<blockquote>
<pre>
void wrap_dot_product() {
Vector *arg0;
Vector *arg1;
double result;
...
result = dot_product(*arg0, *arg1);
...
}
</pre>
</blockquote>
Notice that the <tt>Swig_cargs()</tt>, <tt>Swig_cresult()</tt>, and <tt>Swig_cfunction()</tt> functions
have taken care of the type conversions for the <tt>Vector</tt> type automatically.
<p>
<b>Notes:</b>
<ul>
<Li>The intent of these functions is to provide <em>consistent</em> handling of function parameters
and return values so that language module writers don't have to worry about it too much.
<p>
<li>These functions may be superseded by features in the new typemap system which provide hooks
for specifying local variable declarations and argument conversions.
</ul>
<a name="6" href="#i6">
<h2>6. Symbol Naming Guidelines for Generated C/C++ Code</h2>
</a>
The C++ standard (ISO/IEC 14882:1998(E)) states:
<blockquote>
<pre>
<i>
17.4.3.1.2 Global names [lib.global.names]
1 Certain sets of names and function signatures are always reserved to the implementation:
* Each name that contains a double underscore (__) or begins with an underscore followed
by an upper case letter (2.11) is reserved to the implementation for any use.
* Each name that begins with an underscore is reserved to the implementation for use as
a name in the global namespace.165)
165) Such names are also reserved in namespace ::std (17.4.3.1). [back to text]
</i>
</pre>
</blockquote>
When generating code it is important not to generate symbols that might clash with the code being wrapped. It is tempting to flout the standard or just use a symbol which starts with a single underscore followed by a lowercase letter in order to avoid name clashes. However even these legal symbols can also clash with symbols being wrapped. The following guidelines should be used when generating code in order to meet the standard and make it highly unlikely that symbol clashes will occur:
<p>
For C++ code that doesn't attempt to mangle a symbol being wrapped (for example SWIG convenience functions):
<ul>
<li> Put symbols in the <tt>Swig</tt> namespace, for example class <tt>Swig::Director</tt>. Qualify using the <tt>Swig</tt> namespace whenever the symbol is referenced, even within the <tt>Swig</tt> namespace, for example <tt>new Swig::Director()</tt> not <tt>new Director()</tt>.</li>
<li> Use <tt>swig_</tt> as a prefix for all member variables and member functions that are involved in an inheritance chain with wrapped classes, for example <tt>Swig::Director::swig_get_up()</tt> and <tt>bool Swig::Director::swig_up</tt>.</li>
<li> Alternatively class names can be prefixed with <tt>Swig</tt> in the global namespace for example <tt>template<class T> class SwigValueWrapper</tt>.</li>
</ul>
<p>
For code compiled as C or C++ that doesn't attempt to mangle a symbol being wrapped (for example SWIG convenience functions):
<ul>
<li> Use <tt>SWIG_</tt> as a prefix for structures for example <tt>SWIG_JavaExceptions_t</tt>.</li>
<li> Use <tt>SWIG_</tt> as a prefix for global functions for example <tt>SWIG_TypeRegister</tt>. </li>
<li> Use <tt>SWIG_</tt> as a prefix for macros for example <tt>#define SWIG_PY_INT 1</tt></li>
</ul>
For code compiled as C or C++ that attempts to mangle a wrapped symbol:
<ul>
<li> Use <tt>SWIGxxx</tt> or <tt>Swigxxx</tt> as a prefix where xxx is chosen which would make <tt>SWIGxxx</tt>/<tt>Swigxxx</tt> a unique symbol in the global namespace, for example <tt>class SwigDirectorFoo</tt> when wrapping <tt>class Foo</tt>. Don't use a trailing underscore for the prefix as this may generate a double underscore when wrapping a symbol which starts with a single underscore.</li>
</ul>
In the past SWIG has generated many symbols which flout the standard especially double underscores. In fact they may not all be rooted out yet, so please fix them when you see them.
<a name="7" href="#i7">
<h2>7. Debugging SWIG</h2>
</a>
<p>
The DOH types used in the SWIG source code are all typedefined to void.
Consequently, it is impossible for debuggers to automatically extract any information about DOH objects.
The easiest approach to debugging and viewing the contents of DOH objects is to make a call into one of the family of SWIG print functions from the debugger.
The "Debugging Functions" section in <a href="tree.html">SWIG Parse Tree Handling</a> lists them.
It is sometimes easier to debug by placing a few calls to these functions in code of interest and recompile, especially if your debugger cannot easily make calls into functions within a debugged binary.
</p>
<p>
The SWIG distribution comes with some additional support for the gdb debugger in the <tt>Tools/swig.gdb</tt> file.
Follow the instructions in this file for 'installing'.
This support file provides an easy way to call into some of the family of SWIG print functions via additional user-defined gdb commands.
Some usage of the <tt>swigprint</tt> and <tt>locswigprint</tt> user-defined commands are demonstrated below.
</p>
<p>
More often than not, a parse tree node needs to be examined.
The session below displays the node <tt>n</tt> in one of the Java language module wrapper functions.
The <tt>swigprint</tt> method is used to show the symbol name (<tt>symname</tt> - a DOH String type) and the node (<tt>n</tt> - a DOH Hash type).
</p>
<blockquote>
<pre>
Breakpoint 1, JAVA::functionWrapper (this=0x97ea5f0, n=0xb7d2afc8) at Modules/java.cxx:799
799 String *symname = Getattr(n, "sym:name");
(gdb) next
800 SwigType *t = Getattr(n, "type");
(gdb) swigprint symname
Shape_x_set
(gdb) swigprint n
Hash(0xb7d2afc8) {
'membervariableHandler:view' : variableHandler,
'feature:except' : 0,
'name' : x,
'ismember' : 1,
'sym:symtab' : Hash(0xb7d2aca8) {......},
'nodeType' : cdecl,
'nextSibling' : Hash(0xb7d2af98) {.............},
'kind' : variable,
'variableHandler:feature:immutable' : <Object 'VoidObj' at 0xb7cfa008>,
'sym:name' : Shape_x_set,
'view' : membervariableHandler,
'membervariableHandler:sym:name' : x,
'membervariableHandler:type' : double,
'membervariableHandler:parms' : <Object 'VoidObj' at 0xb7cfa008>,
'parentNode' : Hash(0xb7d2abc8) {..............................},
'feature:java:enum' : typesafe,
'access' : public,
'parms' : Hash(0xb7cb9408) {......},
'wrap:action' : if (arg1) (arg1)->x = arg2;,
'type' : void,
'memberset' : 1,
'sym:overname' : __SWIG_0,
'membervariableHandler:name' : x,
}
</pre>
</blockquote>
<p>
Note that all the attributes in the Hash are shown, including the 'sym:name' attribute which was assigned to the <tt>symname</tt> variable.
</p>
<p>
Hash types can be shown either expanded or collapsed.
When a Hash is shown expanded, all the attributes are displayed along with their values, otherwise a '.' replaces each attribute when collapsed.
Therefore a count of the dots provides the number of attributes within an unexpanded Hash.
Below shows the 'parms' Hash being displayed with the default Hash expansion of 1, then with 2 provided as the second argument to <tt>swigprint</tt> to expand to two Hash levels in order to view the contents of the collapsed 'nextSibling' Hash.
</p>
<blockquote>
<pre>
(gdb) swigprint 0xb7cb9408
Hash(0xb7cb9408) {
'name' : self,
'type' : p.Shape,
'self' : 1,
'nextSibling' : Hash(0xb7cb9498) {...},
'hidden' : 1,
'nodeType' : parm,
}
(gdb) swigprint 0xb7cb9408 2
Hash(0xb7cb9408) {
'name' : self,
'type' : p.Shape,
'self' : 1,
'nextSibling' : Hash(0xb7cb9498) {
'name' : x,
'type' : double,
'nodeType' : parm,
},
'hidden' : 1,
'nodeType' : parm,
}
</pre>
</blockquote>
<p>
The same Hash can also be displayed with file and line location information via the <tt>locswigprint</tt> command.
</p>
<blockquote>
<pre>
(gdb) locswigprint 0xb7cb9408
example.h:11: [Hash(0xb7cb9408) {
Hash(0xb7cb9408) {
'name' : self,
'type' : p.Shape,
'self' : 1,
'nextSibling' : Hash(0xb7cb9498) {...},
'hidden' : 1,
'nodeType' : parm,
}]
</pre>
</blockquote>
<p>
<b>Tip</b>: Commands in gdb can be shortened with whatever makes them unique and can be command completed with the tab key.
Thus <tt>swigprint</tt> can usually be shortened to <tt>sw</tt> and <tt>locswigprint</tt> to <tt>loc</tt>.
The help for each command can also be obtained within the debugging session, for example, 'help swigprint'.
</p>
<p>
The sub-section below gives pointers for debugging DOH objects using casts and provides an insight into why it can be hard to debug SWIG without the family of print functions.
<p>
<a name="7.1" href="#i7.1">
<h3>7.1 Debugging DOH Types The Hard Way</h3>
</a>
The DOH types used in SWIG are all typedefined to void and hence the lack of type information for inspecting types within a debugger.
Most debuggers will however be able to display useful variable information when an object is cast to the appropriate type.
Getting at the underlying C string within DOH types is cumbersome, but possible with appropriate casts.
The casts below can be used in a debugger windows, but be sure to compile with compiler optimisations turned off before attempting the casts else they are unlikely to work.
Even displaying the underlying string in a String * doesn't work straight off in all debuggers due to the multiple definitions of String as a struct and a void.
<p>
Below are a list of common SWIG types.
With each is the cast that can be used in the debugger to extract the underlying type information and the underlying char * string.
<ul>
<p>
<li>String *s;</li>
<tt>(struct String *)((DohBase *)s)->data</tt>
<br>
The underlying char * string can be displayed with
<br>
<tt>(*(struct String *)(((DohBase *)s)->data)).str</tt>
<p>
<li>SwigType *t;</li>
<tt>(struct String *)((DohBase *)t)->data</tt>
<br>
The underlying char * string can be displayed with
<br>
<tt>(*(struct String *)(((DohBase *)t)->data)).str</tt>
<p>
<li>const_String_or_char_ptr sc;</li>
Either <br>
<tt>(*(struct String *)(((DohBase *)sc)->data)).str</tt>
<br> or <br>
<tt>(char *)sc</tt>
<br> will work depending on whether the underlying type is really a String * or char *.
</ul>
<a name="7.2" href="#i7.2">
<h3>7.2 Debugging DOH memory allocation problems</h3>
</a>
<p>
The DOH objects are reference counted and use pools for memory allocation.
The implementation is in <tt>memory.c</tt>. When there are memory corruption problems,
various memory allocator tools are normally used to diagnose problems. These can be used
on SWIG and can be very useful. However, they won't necessarily find use of stale DOH objects,
that is, DOH objects
that are used after they have been deleted. This is because the DOH memory allocator
grabs a chunk of memory from the C memory allocator and manages the usage internally.
Stale DOH object usage can be checked for by defining <tt>DOH_DEBUG_MEMORY_POOLS</tt> in
<tt>memory.c</tt>. If an attempt to use an object is made after the reference count is
zero, an assertion is triggered instead of quietly re-using the stale object...
</p>
<blockquote>
<pre>
swig: DOH/memory.c:91: DohCheck: Assertion `!DOH_object_already_deleted' failed.
</pre>
</blockquote>
<p>
This can be memory intensive as previously used memory in the pool is not re-used so is
only recommended for diagnosing memory corruption problems.
</p>
<hr>
Copyright (C) 1999-2010 SWIG Development Team.
</body>
</html>
|