summaryrefslogtreecommitdiffstats
path: root/python/sip/doc/sipref.txt
blob: 4e14f79ee239987d23c69f7c1d608744f50b38b2 (plain)
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
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
=====================================================================
 SIP - A Tool for Generating Python Bindings for C and C++ Libraries
=====================================================================

-----------------
 Reference Guide
-----------------

:Contact:   info@riverbankcomputing.co.uk
:Version:   4.6
:Copyright: Copyright (c) 2007 Riverbank Computing Limited

.. contents::
.. section-numbering::


Introduction
============

This is the reference guide for SIP 4.6.  SIP is a tool for
automatically generating `Python <http://www.python.org>`__ bindings for C and
C++ libraries.  SIP was originally developed in 1998 for
`PyQt <http://www.riverbankcomputing.co.uk/pyqt/>`__ - the Python bindings for
the Qt GUI toolkit - but is suitable for generating bindings for any C or C++
library.

This version of SIP generates bindings for Python v2.3 or later.

There are many other similar tools available.  One of the original such tools
is `SWIG <http://www.swig.org>`__ and, in fact, SIP is so called because it
started out as a small SWIG.  Unlike SWIG, SIP is specifically designed for
bringing together Python and C/C++ and goes to great lengths to make the
integration as tight as possible.

The homepage for SIP is http://www.riverbankcomputing.co.uk/sip/.  Here you
will always find the latest stable version, current development snapshots, and
the latest version of this documentation.


License
-------

SIP is licensed under the same terms as Python itself.  SIP places no
restrictions on the license you may apply to the bindings you create.


Features
--------

SIP, and the bindings it produces, have the following features.

    - bindings are fast to load and minimise memory consumption especially when
      only a small sub-set of a large library is being used

    - automatic conversion between standard Python and C/C++ data types

    - overloading of functions and methods with different argument signatures

    - access to a C++ class's protected methods

    - the ability to define a Python class that is a sub-class of a C++ class,
      including abstract C++ classes

    - Python sub-classes can implement the ``__dtor__(self)`` method which
      will be called from the C++ class's virtual destructor

    - support for ordinary C++ functions, class methods, static class methods,
      virtual class methods and abstract class methods

    - the ability to re-implement C++ virtual and abstract methods in Python

    - support for global and class variables

    - support for global and class operators

    - support for C++ namespaces

    - support for C++ templates

    - support for C++ exceptions and wrapping them as Python exceptions

    - the ability to define mappings between C++ classes and similar Python
      data types that are automatically invoked

    - the ability to automatically exploit any available run time type
      information to ensure that the class of a Python instance object matches
      the class of the corresponding C++ instance

    - full support of the Python global interpreter lock, including the ability
      to specify that a C++ function of method may block, therefore allowing
      the lock to be released and other Python threads to run

    - support for the concept of ownership of a C++ instance (i.e. what part of
      the code is responsible for calling the instance's destructor) and how
      the ownership may change during the execution of an application

    - the ability to generate bindings for a C++ class library that itself is
      built on another C++ class library which also has had bindings generated
      so that the different bindings integrate and share code properly

    - a sophisticated versioning system that allows the full lifetime of a C++
      class library, including any platform specific or optional features, to
      be described in a single set of specification files 

    - the ability to include documentation in the specification files which can
      be extracted and subsequently processed by external tools

    - the ability to include copyright notices and licensing information in the
      specification files that is automatically included in all generated
      source code

    - a build system, written in Python, that you can extend to configure,
      compile and install your own bindings without worrying about platform
      specific issues

    - support for building your extensions using distutils

    - SIP, and the bindings it produces, runs under UNIX, Linux, Windows and
      MacOS/X


SIP Components
--------------

SIP comprises a number of different components.

    - The SIP code generator (``sip`` or ``sip.exe``).  This processes ``.sip``
      specification files and generates C or C++ bindings.  It is covered in
      detail in `Using SIP`_.

    - The SIP header file (``sip.h``).  This contains definitions and data
      structures needed by the generated C and C++ code.

    - The SIP module (``sip.so`` or ``sip.pyd``).  This is a Python extension
      module that is imported automatically by SIP generated bindings and
      provides them with some common utility functions.  See also `Using the
      SIP Module in Applications`_.

    - The SIP build system (``sipconfig.py``).  This is a pure Python module
      that is created when SIP is configured and encapsulates all the necessary
      information about your system including relevant directory names,
      compiler and linker flags, and version numbers.  It also includes several
      Python classes and functions which help you write configuration scripts
      for your own bindings.  It is covered in detail in `The SIP Build
      System`_.

    - The SIP distutils extension (``sipdistutils.py``).  This is a distutils
      extension that can be used to build your extension modules using
      distutils and is an alternative to writing configuration scripts with the
      SIP build system.  This can be as simple as adding your .sip files to the
      list of files needed to build the extension module.  It is covered in
      detail in `Building Your Extension with distutils`_.


Qt Support
----------

SIP has specific support for the creation of bindings based on Trolltech's Qt
toolkit.

The SIP code generator understands the signal/slot type safe callback mechanism
that Qt uses to connect objects together.  This allows applications to define
new Python signals, and allows any Python callable object to be used as a slot.

SIP itself does not require Qt to be installed.


Potential Incompatibilities with Earlier Versions
=================================================

SIP v4.4
--------

    - The ``SIP_BUILD`` C preprocessor symbol has been removed.

    - `sipConvertToCpp()`_, `sipIsSubClassInstance()`_ and the old `Generated
      Type Convertors`_ have been deprecated.  The functions
      `sipCanConvertToInstance()`_, `sipConvertToInstance()`_,
      `sipForceConvertToInstance()`_, `sipConvertFromInstance()`_,
      `sipConvertFromNewInstance()`_, `sipCanConvertToMappedType()`_,
      `sipConvertToMappedType()`_, `sipForceConvertToMappedType()`_ and
      `sipConvertFromMappedType()`_ should be used instead.  Handwritten
      `%ConvertFromTypeCode`_ and `%ConvertToTypeCode`_ now has the
      responsibility for using these to implement the ``Transfer`` and
      ``TransferBack`` annotations.


Installing SIP
==============

Downloading SIP
---------------

You can get the latest release of the SIP source code from
http://www.riverbankcomputing.co.uk/sip/download.php.

SIP is also included with all of the major Linux distributions.  However, it
may be a version or two out of date.

You may also find more up to date pre-compiled binaries on
`SourceForge <http://sourceforge.net/project/showfiles.php?group_id=61057>`_.


Configuring SIP
---------------

After unpacking the source package (either a ``.tar.gz`` or a ``.zip`` file
depending on your platform) you should then check for any ``README`` files
that relate to your platform.

Next you need to configure SIP by executing the ``configure.py`` script.  For
example::

    python configure.py

This assumes that the Python interpreter is on your path.  Something like the
following may be appropriate on Windows::

    c:\python25\python configure.py

If you have multiple versions of Python installed then make sure you use the
interpreter for which you wish SIP to generate bindings for.

The full set of command line options is:

-h       Display a help message.
-a       Export all symbols in any SIP generated module and the SIP module
         itself.  This was the default behaviour of SIP prior to v4.2.
         Normally only a module's inititialisation function is exported.  This
         option is deprecated as the ``ModuleMakefile`` class of `The SIP Build
         System`_ allows this to be specified on a per module basis.
-b dir   The SIP code generator will be installed in the directory ``dir``.
-d dir   The SIP module will be installed in the directory ``dir``.
-e dir   The SIP header file will be installed in the directory ``dir``.
-k       The SIP module will be built as a static library.  This is useful when
         building the SIP module as a Python builtin (see
         `Builtin Modules and Custom Interpreters`_).
-n       The SIP code generator and module will be built as universal binaries
         under MacOS/X.
-p plat  Explicitly specify the platform/compiler to be used by the build
         system, otherwise a platform specific default will be used.  The
         ``-h`` option will display all the supported platform/compilers and
         the default.
-u       The SIP module will be built with debugging symbols.
-v dir   By default ``.sip`` files will be installed in the directory ``dir``.

The configure.py script takes many other options that allows the build system
to be finely tuned.  These are of the form ``name=value`` or ``name+=value``.
The ``-h`` option will display each supported ``name``, although not all are
applicable to all platforms.

The ``name=value`` form means that ``value`` will replace the existing value of
``name``.

The ``name+=value`` form means that ``value`` will be appended to the existing
value of ``name``.

For example, the following will disable support for C++ exceptions (and so
reduce the size of module binaries) when used with GCC::

    python configure.py CXXFLAGS+=-fno-exceptions

A pure Python module called ``sipconfig.py`` is generated by ``configure.py``.
This defines each ``name`` and its corresponding ``value``.  Looking at it will
give you a good idea of how the build system uses the different options.  It is
covered in detail in `The SIP Build System`_.


Configuring SIP Using MinGW
***************************

SIP, and the modules it generates, can be built with MinGW, the Windows port of
GCC.  You must use the ``-p`` command line option to specify the correct
platform.  For example::

    c:\python25\python configure.py -p win32-g++


Configuring SIP Using the Borland C++ Compiler
**********************************************

SIP, and the modules it generates, can be built with the free Borland C++
compiler.  You must use the ``-p`` command line option to specify the correct
platform.  For example::

    c:\python25\python configure.py -p win32-borland

You must also make sure you have a Borland-compatible version of the Python
library.  If you are using the standard Python distribution (built using the
Microsoft compiler) then you must convert the format of the Python library.
For example::

    coff2omf python25.lib python25_bcpp.lib


Building SIP
------------

The next step is to build SIP by running your platform's ``make`` command.  For
example::

    make

The final step is to install SIP by running the following command::

    make install

(Depending on your system you may require root or administrator privileges.)

This will install the various SIP components.


Using SIP
=========

Bindings are generated by the SIP code generator from a number of specification
files, typically with a ``.sip`` extension.  Specification files look very
similar to C and C++ header files, but often with additional information (in
the form of a *directive* or an *annotation*) and code so that the bindings
generated can be finely tuned.


A Simple C++ Example
--------------------

We start with a simple example.  Let's say you have a (fictional) C++ library
that implements a single class called ``Word``.  The class has one constructor
that takes a ``\0`` terminated character string as its single argument.  The
class has one method called ``reverse()`` which takes no arguments and returns
a ``\0`` terminated character string.  The interface to the class is defined in
a header file called ``word.h`` which might look something like this::

    // Define the interface to the word library.

    class Word {
        const char *the_word;

    public:
        Word(const char *w);

        char *reverse() const;
    };

The corresponding SIP specification file would then look something like this::

    // Define the SIP wrapper to the word library.

    %Module word 0

    class Word {

    %TypeHeaderCode
    #include <word.h>
    %End

    public:
        Word(const char *w);

        char *reverse() const;
    };

Obviously a SIP specification file looks very much like a C++ (or C) header
file, but SIP does not include a full C++ parser.  Let's look at the
differences between the two files.

    - The `%Module`_ directive has been added [#]_.  This is used to name the
      Python module that is being created and to give it a *generation* number.
      In this example these are ``word`` and ``0`` respectively.  The
      generation number is effectively the version number of the module.

    - The `%TypeHeaderCode`_ directive has been added.  The text between this
      and the following `%End`_ directive is included literally in the code
      that SIP generates.  Normally it is used, as in this case, to
      ``#include`` the corresponding C++ (or C) header file [#]_.

    - The declaration of the private variable ``this_word`` has been removed.
      SIP does not support access to either private or protected instance
      variables.

If we want to we can now generate the C++ code in the current directory by
running the following command::

    sip -c . word.sip

However, that still leaves us with the task of compiling the generated code and
linking it against all the necessary libraries.  It's much easier to use the
SIP build system to do the whole thing.

Using the SIP build system is simply a matter of writing a small Python script.
In this simple example we will assume that the ``word`` library we are wrapping
and it's header file are installed in standard system locations and will be
found by the compiler and linker without having to specify any additional
flags.  In a more realistic example your Python script may take command line
options, or search a set of directories to deal with different configurations
and installations.

This is the simplest script (conventionally called ``configure.py``)::

    import os
    import sipconfig

    # The name of the SIP build file generated by SIP and used by the build
    # system.
    build_file = "word.sbf"

    # Get the SIP configuration information.
    config = sipconfig.Configuration()

    # Run SIP to generate the code.
    os.system(" ".join([config.sip_bin, "-c", ".", "-b", build_file, "word.sip"]))
    
    # Create the Makefile.
    makefile = sipconfig.SIPModuleMakefile(config, build_file)

    # Add the library we are wrapping.  The name doesn't include any platform
    # specific prefixes or extensions (e.g. the "lib" prefix on UNIX, or the
    # ".dll" extension on Windows).
    makefile.extra_libs = ["word"]

    # Generate the Makefile itself.
    makefile.generate()

Hopefully this script is self-documenting.  The key parts are the
``Configuration`` and ``SIPModuleMakefile`` classes.  The build system contains
other Makefile classes, for example to build programs or to call other
Makefiles in sub-directories.

After running the script (using the Python interpreter the extension module is
being created for) the generated C++ code and ``Makefile`` will be in the
current directory.

To compile and install the extension module, just run the following
commands [#]_::

    make
    make install

That's all there is to it.

See `Building Your Extension with distutils`_ for an example of how to build
this example using distutils.

.. [#] All SIP directives start with a ``%`` as the first non-whitespace
       character of a line.
.. [#] SIP includes many code directives like this.  They differ in where the
       supplied code is placed by SIP in the generated code.
.. [#] On Windows you might run ``nmake`` or ``mingw32-make`` instead.


A Simple C Example
------------------

Let's now look at a very similar example of wrapping a fictional C library::

    /* Define the interface to the word library. */

    struct Word {
        const char *the_word;
    };

    struct Word *create_word(const char *w);
    char *reverse(struct Word *word);

The corresponding SIP specification file would then look something like this::

    /* Define the SIP wrapper to the word library. */

    %CModule word 0

    struct Word {

    %TypeHeaderCode
    #include <word.h>
    %End

        const char *the_word;
    };

    struct Word *create_word(const char *w) /Factory/;
    char *reverse(struct Word *word);

Again, let's look at the differences between the two files.

    - The `%CModule`_ directive has been added.  This has the same syntax as
      the `%Module`_ directive used in the previous example but tells SIP that
      the library being wrapped is implemented in C rather than C++.

    - The `%TypeHeaderCode`_ directive has been added.

    - The Factory_ annotation has been added to the ``create_word()`` function.
      This tells SIP that a newly created structure is being returned and it is
      owned by Python.

The ``configure.py`` build system script described in the previous example can
be used for this example without change.


A More Complex C++ Example
--------------------------

In this last example we will wrap a fictional C++ library that contains a class
that is derived from a Qt class.  This will demonstrate how SIP allows a class
hierarchy to be split across multiple Python extension modules, and will
introduce SIP's versioning system.

The library contains a single C++ class called ``Hello`` which is derived from
Qt's ``QLabel`` class.  It behaves just like ``QLabel`` except that the text
in the label is hard coded to be ``Hello World``.  To make the example more
interesting we'll also say that the library only supports Qt v3.0 and later,
and also includes a function called ``setDefault()`` that is not implemented
in the Windows version of the library.

The ``hello.h`` header file looks something like this::

    // Define the interface to the hello library.

    #include <qlabel.h>
    #include <qwidget.h>
    #include <qstring.h>

    class Hello : public QLabel {
        // This is needed by the Qt Meta-Object Compiler.
        Q_OBJECT

    public:
        Hello(QWidget *parent, const char *name = 0, WFlags f = 0);

    private:
        // Prevent instances from being copied.
        Hello(const Hello &);
        Hello &operator=(const Hello &);
    };

    #if !defined(Q_OS_WIN)
    void setDefault(const QString &def);
    #endif

The corresponding SIP specification file would then look something like this::

    // Define the SIP wrapper to the hello library.

    %Module hello 0

    %Import qt/qtmod.sip

    %If (Qt_3_0_0 -)

    class Hello : QLabel {

    %TypeHeaderCode
    #include <hello.h>
    %End

    public:
        Hello(QWidget *parent /TransferThis/, const char *name = 0, WFlags f = 0);

    private:
        Hello(const Hello &);
    };

    %If (!WS_WIN)
    void setDefault(const QString &def);
    %End

    %End

Again we look at the differences, but we'll skip those that we've looked at in
previous examples.

    - The `%Import`_ directive has been added to specify that we are extending
      the class hierarchy defined in the file ``qt/qtmod.sip``.  This file is
      part of PyQt.  The build system will take care of finding the file's
      exact location.

    - The `%If`_ directive has been added to specify that
      everything [#]_ up to the matching `%End`_ directive only applies to Qt
      v3.0 and later.  ``Qt_3_0_0`` is a *tag* defined in ``qtmod.sip`` [#]_
      using the `%Timeline`_ directive.  `%Timeline`_ is used to define a tag
      for each version of a library's API you are wrapping allowing you to
      maintain all the different versions in a single SIP specification.  The
      build system provides support to ``configure.py`` scripts for working out
      the correct tags to use according to which version of the library is
      actually installed.

    - The ``public`` keyword used in defining the super-classes has been
      removed.  This is not supported by SIP.

    - The TransferThis_ annotation has been added to the first argument
      of the constructor.  It specifies that if the argument is not 0 (i.e. the
      ``Hello`` instance being constructed has a parent) then ownership of the
      instance is transferred from Python to C++.  It is needed because Qt
      maintains objects (i.e. instances derived from the ``QObject`` class) in
      a hierachy.  When an object is destroyed all of its children are also
      automatically destroyed.  It is important, therefore, that the Python
      garbage collector doesn't also try and destroy them.  This is covered in
      more detail in `Ownership of Objects`_.  SIP provides many other
      annotations that can be applied to arguments, functions and classes.
      Multiple annotations are separated by commas.  Annotations may have
      values.

    - The ``=`` operator has been removed.  This operator is not supported by
      SIP.

    - The `%If`_ directive has been added to specify that everything up to the
      matching `%End`_ directive does not apply to Windows.  ``WS_WIN`` is
      another tag defined by PyQt, this time using the `%Platforms`_ directive.
      Tags defined by the `%Platforms`_ directive are mutually exclusive, i.e.
      only one may be valid at a time [#]_.

One question you might have at this point is why bother to define the private
copy constructor when it can never be called from Python?  The answer is to
prevent the automatic generation of a public copy constructor.

We now look at the ``configure.py`` script.  This is a little different to the
script in the previous examples for two related reasons.

Firstly, PyQt includes a pure Python module called ``pyqtconfig`` that extends
the SIP build system for modules, like our example, that build on top of PyQt.
It deals with the details of which version of Qt is being used (i.e. it
determines what the correct tags are) and where it is installed.  This is
called a module's configuration module.

Secondly, we generate a configuration module (called ``helloconfig``) for our
own ``hello`` module.  There is no need to do this, but if there is a chance
that somebody else might want to extend your C++ library then it would make
life easier for them.

Now we have two scripts.  First the ``configure.py`` script::

    import os
    import sipconfig
    import pyqtconfig

    # The name of the SIP build file generated by SIP and used by the build
    # system.
    build_file = "hello.sbf"

    # Get the PyQt configuration information.
    config = pyqtconfig.Configuration()

    # Get the extra SIP flags needed by the imported qt module.  Note that
    # this normally only includes those flags (-x and -t) that relate to SIP's
    # versioning system.
    qt_sip_flags = config.pyqt_qt_sip_flags

    # Run SIP to generate the code.  Note that we tell SIP where to find the qt
    # module's specification files using the -I flag.
    os.system(" ".join([config.sip_bin, "-c", ".", "-b", build_file, "-I", config.pyqt_sip_dir, qt_sip_flags, "hello.sip"]))

    # We are going to install the SIP specification file for this module and
    # its configuration module.
    installs = []

    installs.append(["hello.sip", os.path.join(config.default_sip_dir, "hello")])

    installs.append(["helloconfig.py", config.default_mod_dir])

    # Create the Makefile.  The QtModuleMakefile class provided by the
    # pyqtconfig module takes care of all the extra preprocessor, compiler and
    # linker flags needed by the Qt library.
    makefile = pyqtconfig.QtModuleMakefile(
        configuration=config,
        build_file=build_file,
        installs=installs
    )

    # Add the library we are wrapping.  The name doesn't include any platform
    # specific prefixes or extensions (e.g. the "lib" prefix on UNIX, or the
    # ".dll" extension on Windows).
    makefile.extra_libs = ["hello"]

    # Generate the Makefile itself.
    makefile.generate()

    # Now we create the configuration module.  This is done by merging a Python
    # dictionary (whose values are normally determined dynamically) with a
    # (static) template.
    content = {
        # Publish where the SIP specifications for this module will be
        # installed.
        "hello_sip_dir":    config.default_sip_dir,

        # Publish the set of SIP flags needed by this module.  As these are the
        # same flags needed by the qt module we could leave it out, but this
        # allows us to change the flags at a later date without breaking
        # scripts that import the configuration module.
        "hello_sip_flags":  qt_sip_flags
    }

    # This creates the helloconfig.py module from the helloconfig.py.in
    # template and the dictionary.
    sipconfig.create_config_module("helloconfig.py", "helloconfig.py.in", content)

Next we have the ``helloconfig.py.in`` template script::

    import pyqtconfig

    # These are installation specific values created when Hello was configured.
    # The following line will be replaced when this template is used to create
    # the final configuration module.
    # @SIP_CONFIGURATION@

    class Configuration(pyqtconfig.Configuration):
        """The class that represents Hello configuration values.
        """
        def __init__(self, sub_cfg=None):
            """Initialise an instance of the class.

            sub_cfg is the list of sub-class configurations.  It should be None
            when called normally.
            """
            # This is all standard code to be copied verbatim except for the
            # name of the module containing the super-class.
            if sub_cfg:
                cfg = sub_cfg
            else:
                cfg = []

            cfg.append(_pkg_config)

            pyqtconfig.Configuration.__init__(self, cfg)

    class HelloModuleMakefile(pyqtconfig.QtModuleMakefile):
        """The Makefile class for modules that %Import hello.
        """
        def finalise(self):
            """Finalise the macros.
            """
            # Make sure our C++ library is linked.
            self.extra_libs.append("hello")

            # Let the super-class do what it needs to.
            pyqtconfig.QtModuleMakefile.finalise(self)

Again, we hope that the scripts are self documenting.

.. [#] Some parts of a SIP specification aren't subject to version control.
.. [#] Actually in ``versions.sip``.  PyQt uses the `%Include`_ directive to
       split the SIP specification for Qt across a large number of separate
       ``.sip`` files.
.. [#] Tags can also be defined by the `%Feature`_ directive.  These tags are
       not mutually exclusive, i.e. any number may be valid at a time.


Ownership of Objects
--------------------

When a C++ instance is wrapped a corresponding Python object is created.  The
Python object behaves as you would expect in regard to garbage collection - it
is garbage collected when its reference count reaches zero.  What then happens
to the corresponding C++ instance?  The obvious answer might be that the
instance's destructor is called.  However the library API may say that when the
instance is passed to a particular function, the library takes ownership of the
instance, i.e. responsibility for calling the instance's destructor is
transferred from the SIP generated module to the library.

Ownership of an instance may also be associated with another instance.  The
implication being that the owned instance will automatically be destroyed if
the owning instance is destroyed.  SIP keeps track of these relationships to
ensure that Python's cyclic garbage collector can detect and break any
reference cycles between the owning and owned instances.  The association is
implemented as the owning instance taking a reference to the owned instance.

The TransferThis_, Transfer_ and TransferBack annotations are used to specify
where, and it what direction, transfers of ownership happen.  It is very
important that these are specified correctly to avoid crashes (where both
Python and C++ call the destructor) and memory leaks (where neither Python and
C++ call the destructor).

This applies equally to C structures where the structure is returned to the
heap using the ``free()`` function.

See also `sipTransferTo()`_ and `sipTransferBack()`_.


Support for Wide Characters
---------------------------

SIP v4.6 introduced support for wide characters (i.e. the ``wchar_t`` type).
Python's C API includes support for converting between unicode objects and wide
character strings and arrays.  When converting from a unicode object to wide
characters SIP creates the string or array on the heap (using memory allocated
using `sipMalloc()`_).  This then raises the problem of how this memory is
subsequently freed.

The following describes how SIP handles this memory in the different situations
where this is an issue.

    - When a wide string or array is passed to a function or method then the
      memory is freed (using `sipFree()`_) after than function or method
      returns.

    - When a wide string or array is returned from a virtual method then SIP
      does not free the memory until the next time the method is called.

    - When an assignment is made to a wide string or array instance variable
      then SIP does not first free the instance's current string or array.


The Python Global Interpreter Lock
----------------------------------

Python's Global Interpretor Lock (GIL) must be acquired before calls can be
made to the Python API.  It should also be released when a potentially
blocking call to C/C++ library is made in order to allow other Python threads
to be executed.  In addition, some C/C++ libraries may implement their own
locking strategies that conflict with the GIL causing application deadlocks.
SIP provides ways of specifying when the GIL is released and acquired to
ensure that locking problems can be avoided.

SIP always ensures that the GIL is acquired before making calls to the Python
API.  By default SIP does not release the GIL when making calls to the C/C++
library being wrapped.  The ReleaseGIL_ annotation can be used to override
this behaviour when required.

If SIP is given the ``-g`` command line option then the default behaviour is
changed and SIP releases the GIL every time is makes calls to the C/C++
library being wrapped.  The HoldGIL_ annotation can be used to override this
behaviour when required.


The SIP Command Line
====================

The syntax of the SIP command line is::

    sip [options] [specification]

``specification`` is the name of the specification file for the module.  If it
is omitted then ``stdin`` is used.

The full set of command line options is:

-h      Display a help message.
-V      Display the SIP version number.
-a file
        The name of the QScintilla API file to generate.  This file contains a
        description of the module API in a form that the QScintilla editor
        component can use for auto-completion and call tips.  (The file may
        also be used by the SciTE editor but must be sorted first.)  By default
        the file is not generated.
-b file
        The name of the build file to generate.  This file contains the
        information about the module needed by the SIP build system to generate
        a platform and compiler specific Makefile for the module.  By default
        the file is not generated.
-c dir  The name of the directory (which must exist) into which all of the
        generated C or C++ code is placed.  By default no code is generated.
-d file
        The name of the documentation file to generate.  Documentation is
        included in specification files using the `%Doc`_ and `%ExportedDoc`_
        directives.  By default the file is not generated.
-e      Support for C++ exceptions is enabled.  This causes all calls to C++
        code to be enclosed in ``try``/``catch`` blocks and C++ exceptions to
        be converted to Python exceptions.  By default exception support is
        disabled.
-g      The Python GIL is released before making any calls to the C/C++ library
        being wrapped and reacquired afterwards.  See `The Python Global
        Interpreter Lock`_ and the ReleaseGIL_ and HoldGIL_ annotations.
-I dir  The directory is added to the list of directories searched when looking
        for a specification file given in an `%Include`_ or `%Import`_
        directive.  This option may be given any number of times.
-j number
        The generated code is split into the given number of files.  This make
        it easier to use the parallel build facility of most modern
        implementations of ``make``.  By default 1 file is generated for each C
        structure or C++ class.
-r      Debugging statements that trace the execution of the bindings are
        automatically generated.  By default the statements are not generated.
-s suffix
        The suffix to use for generated C or C++ source files.  By default
        ``.c`` is used for C and ``.cpp`` for C++.
-t tag  The SIP version tag (declared using a `%Timeline`_ directive) or the
        SIP platform tag (declared using the `%Platforms`_ directive) to
        generate code for.  This option may be given any number of times so
        long as the tags do not conflict.
-w      The display of warning messages is enabled.  By default warning
        messages are disabled.
-x feature
        The feature (declared using the `%Feature`_ directive) is disabled.
-z file
        The name of a file containing more command line options.


SIP Specification Files
=======================

A SIP specification consists of some C/C++ type and function declarations and
some directives.  The declarations may contain annotations which provide SIP
with additional information that cannot be expressed in C/C++.  SIP does not
include a full C/C++ parser.

It is important to understand that a SIP specification describes the Python
API, i.e. the API available to the Python programmer when they ``import`` the
generated module.  It does not have to accurately represent the underlying
C/C++ library.  There is nothing wrong with omitting functions that make
little sense in a Python context, or adding functions implemented with
handwritten code that have no C/C++ equivalent.  It is even possible (and
sometimes necessary) to specify a different super-class hierarchy for a C++
class.  All that matters is that the generated code compiles properly.

In most cases the Python API matches the C/C++ API.  In some cases handwritten
code (see `%MethodCode`_) is used to map from one to the other without SIP
having to know the details itself.  However, there are a few cases where SIP
generates a thin wrapper around a C++ method or constructor (see `Generated
Derived Classes`_) and needs to know the exact C++ signature.  To deal with
these cases SIP allows two signatures to be specified.  For example::

    class Klass
    {
    public:
        // The Python signature is a tuple, but the underlying C++ signature
        // is a 2 element array.
        Klass(SIP_PYTUPLE) [(int *)];
    %MethodCode
            int iarr[2];

            if (PyArg_ParseTuple(a0, "ii", &iarr[0], &iarr[1]))
            {
                // Note that we use the SIP generated derived class
                // constructor.
                Py_BEGIN_ALLOW_THREADS
                sipCpp = new sipKlass(iarr);
                Py_END_ALLOW_THREADS
            }
    %End
    };


Syntax Definition
-----------------

The following is a semi-formal description of the syntax of a specification
file.

.. parsed-literal::

    *specification* ::= {*module-statement*}

    *module-statement* ::= [*module-directive* | *statement*]

    *module-directive* ::= [`%CModule`_ | `%Copying`_ | `%Doc`_ |
            `%ExportedDoc`_ | `%ExportedHeaderCode`_ | `%Feature`_ |
            `%Import`_ | `%Include`_ | `%License`_ | `%MappedType`_ |
            *mapped-type-template* | `%Module`_ | `%ModuleCode`_ |
            `%ModuleHeaderCode`_ | `%OptionalInclude`_ | `%Platforms`_ |
            `%PreInitialisationCode`_ | `%PostInitialisationCode`_ |
            *sip-option-list* | `%Timeline`_ | `%UnitCode`_]

    *sip-option-list* :: `%SIPOptions`_ ``(`` *option-list* ``)``

    *option-list* ::= *option* [``,`` *option-list*]

    *statement* :: [*class-statement* | *function* | *variable*]

    *class-statement* :: [`%If`_ | *class* | *class-template* | *enum* |
            *namespace* | *opaque-class* | *operator* | *struct* | *typedef* |
            *exception*]

    *class* ::= ``class`` *name* [``:`` *super-classes*] [*class-annotations*]
            ``{`` {*class-line*} ``};``

    *super-classes* ::= *name* [``,`` *super-classes*]

    *class-line* ::= [*class-statement* | `%BIGetReadBufferCode`_ |
            `%BIGetWriteBufferCode`_ | `%BIGetSegCountCode`_ |
            `%BIGetCharBufferCode`_ | `%ConvertToSubClassCode`_ |
            `%ConvertToTypeCode`_ | `%GCClearCode`_ | `%GCTraverseCode`_ |
            `%TypeCode`_ | `%TypeHeaderCode`_ | *constructor* | *destructor* |
            *method* | *static-method* | *virtual-method* | *special-method* |
            *operator* | *virtual-operator* | *class-variable* | ``public:`` |
            ``public slots:`` | ``protected:`` | ``protected slots:`` |
            ``private:`` | ``private slots:`` | ``signals:``]

    *constructor* ::= [``explicit``] *name* ``(`` [*argument-list*] ``)``
            [*exceptions*] [*function-annotations*]
            [*c++-constructor-signature*] ``;`` [`%MethodCode`_]

    *c++-constructor-signature* ::= ``[(`` [*argument-list*] ``)]``

    *destructor* ::= [``virtual``] ``~`` *name* ``()`` [*exceptions*] [``= 0``]
            [*function-annotations*] ``;`` [`%MethodCode`_]
            [`%VirtualCatcherCode`_]

    *method* ::= *type* *name* ``(`` [*argument-list*] ``)`` [``const``]
            [*exceptions*] [``= 0``] [*function-annotations*] [*c++-signature*]
            ``;`` [`%MethodCode`_]

    *c++-signature* ::= ``[`` *type* ``(`` [*argument-list*] ``)]``

    *static-method* ::= ``static`` *function*

    *virtual-method* ::= ``virtual`` *type* *name* ``(`` [*argument-list*] ``)``
            [``const``] [*exceptions*] [``= 0``] [*function-annotations*]
            [*c++-signature*] ``;`` [`%MethodCode`_] [`%VirtualCatcherCode`_]

    *special-method* ::= *type* *special-method-name*
            ``(`` [*argument-list*] ``)`` [*function-annotations*] ``;``
            [`%MethodCode`_]

    *special-method-name* ::= [ ``__abs__`` | ``__add__`` | ``__and__`` |
            ``__call__`` | ``__cmp__`` | ``__contains__`` | ``__delitem__`` |
            ``__div__`` | ``__eq__`` | ``__float__`` | ``__ge__`` |
            ``__getitem__`` | ``__gt__`` | ``__hash__`` | ``__iadd__`` |
            ``__iand__`` | ``__idiv__`` | ``__ilshift__`` | ``__imod__`` |
            ``__imul__`` | ``__int__`` | ``__invert__`` | ``__ior__`` |
            ``__irshift__`` | ``__isub__`` | ``__ixor__`` | ``__le__`` |
            ``__len__`` | ``__long__`` | ``__lshift__`` | ``__lt__`` |
            ``__mod__`` | ``__mul__`` | ``__ne__`` | ``__neg__`` |
            ``__nonzero__`` | ``__or__`` | ``__pos__`` | ``__repr__`` |
            ``__rshift__`` | ``__setitem__`` | ``__str__`` | ``__sub__`` |
            ``__xor__``]

    *operator* ::= *operator-type*
            ``(`` [*argument-list*] ``)`` [``const``] [*exceptions*]
            [*function-annotations*] ``;`` [`%MethodCode`_]

    *virtual-operator* ::= ``virtual`` *operator-type*
            ``(`` [*argument-list*] ``)`` [``const``] [*exceptions*] [``= 0``]
            [*function-annotations*] ``;`` [`%MethodCode`_]
            [`%VirtualCatcherCode`_]

    *operatator-type* ::= [ *operator-function* | *operator-cast* ]

    *operator-function* ::= *type* ``operator`` *operator-name*

    *operator-cast* ::= ``operator`` *type*

    *operator-name* ::= [``+`` | ``-`` | ``*`` | ``/`` | ``%`` | ``&`` |
            ``|`` | ``^`` | ``<<`` | ``>>`` | ``+=`` | ``-=`` | ``*=`` |
            ``/=`` | ``%=`` | ``&=`` | ``|=`` | ``^=`` | ``<<=`` | ``>>=`` |
            ``~`` | ``()`` | ``[]`` | ``<`` | ``<=`` | ``==`` | ``!=`` |
            ``>`` | ``>>=``]

    *class-variable* ::= [``static``] *variable*

    *class-template* :: = ``template`` ``<`` *type-list* ``>`` *class*

    *mapped-type-template* :: = ``template`` ``<`` *type-list* ``>``
            `%MappedType`_

    *enum* ::= ``enum`` [*name*] [*enum-annotations*] ``{`` {*enum-line*} ``};``

    *enum-line* ::= [`%If`_ | *name* [*enum-annotations*] ``,``

    *function* ::= *type* *name* ``(`` [*argument-list*] ``)`` [*exceptions*]
            [*function-annotations*] ``;`` [`%MethodCode`_]

    *namespace* ::= ``namespace`` *name* ``{`` {*namespace-line*} ``};``

    *namespace-line* ::= [`%TypeHeaderCode`_ | *statement*]

    *opaque-class* ::= ``class`` *scoped-name* ``;``

    *struct* ::= ``struct`` *name* ``{`` {*class-line*} ``};``

    *typedef* ::= ``typedef`` [*typed-name* | *function-pointer*] ``;``

    *variable*::= *typed-name* [*variable-annotations*] ``;`` [`%AccessCode`_]
            [`%GetCode`_] [`%SetCode`_]

    *exception* ::= `%Exception`_ *exception-name* [*exception-base*] ``{``
            [`%TypeHeaderCode`_] `%RaiseCode`_ `};``

    *exception-name* ::= *scoped-name*

    *exception-base* ::= ``(`` [*exception-name* | *python-exception*] ``)``

    *python-exception* ::= [``SIP_Exception`` | ``SIP_StopIteration`` |
            ``SIP_StandardError`` | ``SIP_ArithmeticError`` |
            ``SIP_LookupError`` | ``SIP_AssertionError`` |
            ``SIP_AttributeError`` | ``SIP_EOFError`` |
            ``SIP_FloatingPointError`` | ``SIP_EnvironmentError`` |
            ``SIP_IOError`` | ``SIP_OSError`` | ``SIP_ImportError`` |
            ``SIP_IndexError`` | ``SIP_KeyError`` | ``SIP_KeyboardInterrupt`` |
            ``SIP_MemoryError`` | ``SIP_NameError`` | ``SIP_OverflowError`` |
            ``SIP_RuntimeError`` | ``SIP_NotImplementedError`` |
            ``SIP_SyntaxError`` | ``SIP_IndentationError`` | ``SIP_TabError`` |
            ``SIP_ReferenceError`` | ``SIP_SystemError`` | ``SIP_SystemExit`` |
            ``SIP_TypeError`` | ``SIP_UnboundLocalError`` |
            ``SIP_UnicodeError`` | ``SIP_UnicodeEncodeError`` |
            ``SIP_UnicodeDecodeError`` | ``SIP_UnicodeTranslateError`` |
            ``SIP_ValueError`` | ``SIP_ZeroDivisionError`` |
            ``SIP_WindowsError`` | ``SIP_VMSError``]

    *exceptions* ::= ``throw (`` [*exception-list*] ``)``

    *exception-list* ::= *scoped-name* [``,`` *exception-list*]

    *argument-list* ::= *argument* [``,`` *argument-list*] [``,`` ``...``]

    *argument* ::= [*type* [*name*] [*argument-annotations*]
            [*default-value*] | SIP_ANYSLOT_ [*default-value*] | SIP_QOBJECT_ |
            SIP_RXOBJ_CON_ | SIP_RXOBJ_DIS_ | SIP_SIGNAL_ [*default-value*] |
            SIP_SLOT_ [*default-value*] | SIP_SLOT_CON_ | SIP_SLOT_DIS_]

    *default-value* ::= ``=`` *expression*

    *expression* ::= [*value* | *value* *binary-operator* *expression*]

    *value* ::= [*unary-operator*] *simple-value*

    *simple-value* ::= [*scoped-name* | *function-call* | *real-value* |
            *integer-value* | *boolean-value* | *string-value* |
            *character-value*]

    *typed-name*::= *type* *name*

    *function-pointer*::= *type* ``(*`` *name* ``)(`` [*type-list*] ``)``

    *type-list* ::= *type* [``,`` *type-list*]

    *function-call* ::= *scoped-name* ``(`` [*value-list*] ``)``

    *value-list* ::= *value* [``,`` *value-list*]

    *real-value* ::= a floating point number

    *integer-value* ::= a number

    *boolean-value* ::= [``true`` | ``false``]

    *string-value* ::= ``"`` {*character*} ``"``

    *character-value* ::= ````` *character* `````

    *unary-operator* ::= [``!`` | ``~`` | ``-`` | ``+``]

    *binary-operator* ::= [``-`` | ``+`` | ``*`` | ``/`` | ``&`` | ``|``]

    *argument-annotations* ::= see `Argument Annotations`_

    *class-annotations* ::= see `Class Annotations`_

    *enum-annotations* ::= see `Enum Annotations`_

    *function-annotations* ::= see `Function Annotations`_

    *variable-annotations* ::= see `Variable Annotations`_

    *type* ::= [``const``] *base-type* {``*``} [``&``]

    *type-list* ::= *type* [``,`` *type-list*]

    *base-type* ::= [*scoped-name* | *template* | ``struct`` *scoped-name* |
            ``short`` | ``unsigned short`` | ``int`` | ``unsigned`` |
            ``unsigned int`` | ``long`` | ``unsigned long`` | ``float`` |
            ``double`` | ``bool`` | ``char`` | ``signed char`` |
            ``unsigned char`` | ``void`` | ``wchar_t`` | SIP_PYCALLABLE_ |
            SIP_PYDICT_ | SIP_PYLIST_ | SIP_PYOBJECT_ | SIP_PYSLICE_ |
            SIP_PYTUPLE_ | SIP_PYTYPE_]

    *scoped-name* ::= *name* [``::`` *scoped-name*]

    *template* ::= *scoped-name* ``<`` *type-list* ``>``

    *name* ::= _A-Za-z {_A-Za-z0-9}

Here is a short list of differences between C++ and the subset supported by
SIP that might trip you up.

    - SIP does not support the use of ``[]`` in types.  Use pointers instead.

    - A global ``operator`` can only be defined if its first argument is a
      class or a named enum that has been wrapped in the same module.

    - Variables declared outside of a class are effectively read-only.

    - A class's list of super-classes doesn't not include any access specifier
      (e.g. ``public``).


Variable Numbers of Arguments
-----------------------------

SIP supports the use of ``...`` as the last part of a function signature.  Any
remaining arguments are collected as a Python tuple.


Additional SIP Types
--------------------

SIP supports a number of additional data types that can be used in Python
signatures.


SIP_ANYSLOT
***********

This is both a ``const char *`` and a ``PyObject *`` that is used as the type
of the member instead of ``const char *`` in functions that implement the
connection or disconnection of an explicitly generated signal to a slot.
Handwritten code must be provided to interpret the conversion correctly.


SIP_PYCALLABLE
**************

This is a ``PyObject *`` that is a Python callable object.


SIP_PYDICT
**********

This is a ``PyObject *`` that is a Python dictionary object.


SIP_PYLIST
**********

This is a ``PyObject *`` that is a Python list object.


SIP_PYOBJECT
************

This is a ``PyObject *`` of any Python type.


SIP_PYSLICE
***********

This is a ``PyObject *`` that is a Python slice object.


SIP_PYTUPLE
***********

This is a ``PyObject *`` that is a Python tuple object.


SIP_PYTYPE
**********

This is a ``PyObject *`` that is a Python type object.


SIP_QOBJECT
***********

This is a ``QObject *`` that is a C++ instance of a class derived from Qt's
``QObject`` class.


SIP_RXOBJ_CON
*************

This is a ``QObject *`` that is a C++ instance of a class derived from Qt's
``QObject`` class.  It is used as the type of the receiver instead of ``const
QObject *`` in functions that implement a connection to a slot.


SIP_RXOBJ_DIS
*************

This is a ``QObject *`` that is a C++ instance of a class derived from Qt's
``QObject`` class.  It is used as the type of the receiver instead of ``const
QObject *`` in functions that implement a disconnection from a slot.


SIP_SIGNAL
**********

This is a ``const char *`` that is used as the type of the signal instead of
``const char *`` in functions that implement the connection or disconnection
of an explicitly generated signal to a slot.


SIP_SLOT
********

This is a ``const char *`` that is used as the type of the member instead of
``const char *`` in functions that implement the connection or disconnection
of an explicitly generated signal to a slot.


SIP_SLOT_CON
************

This is a ``const char *`` that is used as the type of the member instead of
``const char *`` in functions that implement the connection of an internally
generated signal to a slot.  The type includes a comma separated list of types
that is the C++ signature of of the signal.

To take an example, ``QAccel::connectItem()`` connects an internally generated
signal to a slot.  The signal is emitted when the keyboard accelerator is
activated and it has a single integer argument that is the ID of the
accelerator.  The C++ signature is::

    bool connectItem(int id, const QObject *receiver, const char *member);

The corresponding SIP specification is::

    bool connectItem(int, SIP_RXOBJ_CON, SIP_SLOT_CON(int));


SIP_SLOT_DIS
************

This is a ``const char *`` that is used as the type of the member instead of
``const char *`` in functions that implement the disconnection of an
internally generated signal to a slot.  The type includes a comma separated
list of types that is the C++ signature of of the signal.


SIP Directives
==============

In this section we describe each of the directives that can be used in
specification files.  All directives begin with ``%`` as the first
non-whitespace character in a line.

Some directives have arguments or contain blocks of code or documentation.  In
the following descriptions these are shown in *italics*.  Optional arguments
are enclosed in [*brackets*].

Some directives are used to specify handwritten code.  Handwritten code must
not define names that start with the prefix ``sip``.


%AccessCode
-----------

.. parsed-literal::

    %AccessCode
        *code*
    %End

This directive is used immediately after the declaration of an instance of a
wrapped class or structure, or a pointer to such an instance.  You use it to
provide handwritten code that overrides the default behaviour.

For example::

    class Klass;

    Klass *klassInstance;
    %AccessCode
        // In this contrived example the C++ library we are wrapping defines
        // klassInstance as Klass ** (which SIP doesn't support) so we
        // explicitly dereference it.
        if (klassInstance && *klassInstance)
            return *klassInstance;

        // This will get converted to None.
        return 0;
    %End


%BIGetCharBufferCode
--------------------

.. parsed-literal::

    %BIGetCharBufferCode
        *code*
    %End

This directive (along with `%BIGetReadBufferCode`_, `%BIGetSegCountCode`_ and
`%BIGetWriteBufferCode`_) is used to specify code that implements Python's
buffer interface.  See the section `Buffer Object Structures
<http://www.python.org/dev/doc/devel/api/buffer-structs.html>`__ for the
details.

The following variables are made available to the handwritten code:

*type* \*sipCpp
    This is a pointer to the structure or class instance.  Its *type* is a
    pointer to the structure or class.

void \*\*sipPtrPtr
    This is the pointer used to return the address of the character buffer.

SIP_SSIZE_T sipRes
    The handwritten code should set this to the length of the character buffer
    or -1 if there was an error.

SIP_SSIZE_T sipSegment
    This is the number of the segment of the character buffer.

PyObject \*sipSelf
    This is the Python object that wraps the the structure or class instance,
    i.e. ``self``.


%BIGetReadBufferCode
--------------------

.. parsed-literal::

    %BIGetReadBufferCode
        *code*
    %End

This directive (along with `%BIGetCharBufferCode`_, `%BIGetSegCountCode`_ and
`%BIGetWriteBufferCode`_) is used to specify code that implements Python's
buffer interface.

The following variables are made available to the handwritten code:

*type* \*sipCpp
    This is a pointer to the structure or class instance.  Its *type* is a
    pointer to the structure or class.

void \*\*sipPtrPtr
    This is the pointer used to return the address of the read buffer.

SIP_SSIZE_T sipRes
    The handwritten code should set this to the length of the read buffer or
    -1 if there was an error.

SIP_SSIZE_T sipSegment
    This is the number of the segment of the read buffer.

PyObject \*sipSelf
    This is the Python object that wraps the the structure or class instance,
    i.e. ``self``.


%BIGetSegCountCode
------------------

.. parsed-literal::

    %BIGetSegCountCode
        *code*
    %End

This directive (along with `%BIGetCharBufferCode`_, `%BIGetReadBufferCode`_ and
`%BIGetWriteBufferCode`_) is used to specify code that implements Python's
buffer interface.

The following variables are made available to the handwritten code:

*type* \*sipCpp
    This is a pointer to the structure or class instance.  Its *type* is a
    pointer to the structure or class.

SIP_SSIZE_T \*sipLenPtr
    This is the pointer used to return the total length in bytes of all
    segments of the buffer.

SIP_SSIZE_T sipRes
    The handwritten code should set this to the number of segments that make
    up the buffer.

PyObject \*sipSelf
    This is the Python object that wraps the the structure or class instance,
    i.e. ``self``.


%BIGetWriteBufferCode
---------------------

.. parsed-literal::

    %BIGetWriteBufferCode
        *code*
    %End

This directive (along with `%BIGetCharBufferCode`_, `%BIGetReadBufferCode`_
and `%BIGetSegCountCode`_ is used to specify code that implements Python's
buffer interface.

The following variables are made available to the handwritten code:

*type* \*sipCpp
    This is a pointer to the structure or class instance.  Its *type* is a
    pointer to the structure or class.

void \*\*sipPtrPtr
    This is the pointer used to return the address of the write buffer.

SIP_SSIZE_T sipRes
    The handwritten code should set this to the length of the write buffer or
    -1 if there was an error.

SIP_SSIZE_T sipSegment
    This is the number of the segment of the write buffer.

PyObject \*sipSelf
    This is the Python object that wraps the the structure or class instance,
    i.e. ``self``.


%CModule
--------

.. parsed-literal::

    %CModule *name* [*version*]

This directive is used to identify that the library being wrapped is a C
library and to define the name of the module and it's optional version number.

See the `%Module`_ directive for an explanation of the version number.

For example::

    %CModule dbus 1


%ConvertFromTypeCode
--------------------

.. parsed-literal::

    %ConvertFromTypeCode
        *code*
    %End

This directive is used as part of the `%MappedType`_ directive to specify the
handwritten code that converts an instance of a mapped type to a Python
object.

The following variables are made available to the handwritten code:

*type* \*sipCpp
    This is a pointer to the instance of the mapped type to be converted.  It
    will never be zero as the conversion from zero to ``Py_None`` is handled
    before the handwritten code is called.

PyObject \*sipTransferObj
    This specifies any desired ownership changes to the returned object.  If it
    is ``NULL`` then the ownership should be left unchanged.  If it is
    ``Py_None`` then ownership should be transferred to Python.  Otherwise
    ownership should be transferred to C/C++ and the returned object associated
    with *sipTransferObj*.  The code can choose to interpret these changes in
    any way.  For example, if the code is converting a C++ container of wrapped
    classes to a Python list it is likely that the ownership changes should be
    made to each element of the list.

The handwritten code must explicitly return a ``PyObject *``.  If there was an
error then a Python exception must be raised and ``NULL`` returned.

The following example converts a ``QList<QWidget *>`` instance to a Python
list of ``QWidget`` instances::

    %ConvertFromTypeCode
        PyObject *l;

        // Create the Python list of the correct length.
        if ((l = PyList_New(sipCpp -> size())) == NULL)
            return NULL;

        // Go through each element in the C++ instance and convert it to a
        // wrapped QWidget.
        for (int i = 0; i < sipCpp -> size(); ++i)
        {
            QWidget *w = sipCpp -> at(i);
            PyObject *wobj;

            // Get the Python wrapper for the QWidget instance, creating a new
            // one if necessary, and handle any ownership transfer.
            if ((wobj = sipConvertFromInstance(w, sipClass_QWidget, sipTransferObj)) == NULL)
            {
                // There was an error so garbage collect the Python list.
                Py_DECREF(l);
                return NULL;
            }

            // Add the wrapper to the list.
            PyList_SET_ITEM(l, i, wobj);
        }

        // Return the Python list.
        return l;
    %End


%ConvertToSubClassCode
----------------------

.. parsed-literal::

    %ConvertToSubClassCode
        *code*
    %End

When SIP needs to wrap a C++ class instance it first checks to make sure it
hasn't already done so.  If it has then it just returns a new reference to the
corresponding Python object.  Otherwise it creates a new Python object of the
appropriate type.  In C++ a function may be defined to return an instance of a
certain class, but can often return a sub-class instead.

This directive is used to specify handwritten code that exploits any available
real-time type information (RTTI) to see if there is a more specific Python
type that can be used when wrapping the C++ instance.  The RTTI may be
provided by the compiler or by the C++ instance itself.

The directive is included in the specification of one of the classes that the
handwritten code handles the type conversion for.  It doesn't matter which
one, but a sensible choice would be the one at the root of that class
hierarchy in the module.

Note that if a class hierarchy extends over a number of modules then this
directive should be used in each of those modules to handle the part of the
hierarchy defined in that module.  SIP will ensure that the different pieces
of code are called in the right order to determine the most specific Python
type to use.

The following variables are made available to the handwritten code:

*type* \*sipCpp
    This is a pointer to the C++ class instance.

void \*\*sipCppRet
    When the sub-class is derived from more than one super-class then it is
    possible that the C++ address of the instance as the sub-class is
    different to that of the super-class.  If so, then this must be set to the
    C++ address of the instance when cast (usually using ``static_cast``)
    from the super-class to the sub-class.

sipWrapperType \*sipClass
    The handwritten code must set this to the SIP generated Python type object
    that corresponds to the class instance.  (The type object for class
    ``Klass`` is ``sipClass_Klass``.)  If the RTTI of the class instance isn't
    recognised then ``sipClass`` must be set to ``NULL``.  The code doesn't
    have to recognise the exact class, only the most specific sub-class that
    it can.

The handwritten code must not explicitly return.

The following example shows the sub-class conversion code for ``QEvent`` based
class hierarchy in PyQt::

    class QEvent
    {
    %ConvertToSubClassCode
        // QEvent sub-classes provide a unique type ID.
        switch (sipCpp -> type())
        {
        case QEvent::Timer:
            sipClass = sipClass_QTimerEvent;
            break;

        case QEvent::KeyPress:
        case QEvent::KeyRelease:
            sipClass = sipClass_QKeyEvent;
            break;

        // Skip the remaining event types to keep the example short.

        default:
            // We don't recognise the type.
            sipClass = NULL;
        }
    %End

        // The rest of the class specification.

    };

The SIP API includes the `sipMapIntToClass()`_ and `sipMapStringToClass()`_
functions that convert integer and string based RTTI to Python type objects
based on ordered lookup tables.


%ConvertToTypeCode
------------------

.. parsed-literal::

    %ConvertToTypeCode
        *code*
    %End

This directive is used to specify the handwritten code that converts a Python
object to a mapped type instance and to handle any ownership transfers.  It is
used as part of the `%MappedType`_ directive and as part of a class
specification.  The code is also called to determine if the Python object is of
the correct type prior to conversion.

When used as part of a class specification it can automatically convert
additional types of Python object.  For example, PyQt uses it in the
specification of the ``QString`` class to allow Python string objects and
unicode objects to be used wherever ``QString`` instances are expected.

The following variables are made available to the handwritten code:

int \*sipIsErr
    If this is ``NULL`` then the code is being asked to check the type of the
    Python object.  The check must not have any side effects.  Otherwise the
    code is being asked to convert the Python object and a non-zero value
    should be returned through this pointer if an error occurred during the
    conversion.

PyObject \*sipPy
    This is the Python object to be converted.

*type* \*\*sipCppPtr
    This is a pointer through which the address of the mapped type instance (or
    zero if appropriate) is returned.  Its value is undefined if ``sipIsErr``
    is ``NULL``.

PyObject \*sipTransferObj
    This specifies any desired ownership changes to *sipPy*.  If it is ``NULL``
    then the ownership should be left unchanged.  If it is ``Py_None`` then
    ownership should be transferred to Python.  Otherwise ownership should be
    transferred to C/C++ and *sipPy* associated with *sipTransferObj*.  The
    code can choose to interpret these changes in any way.

The handwritten code must explicitly return an ``int`` the meaning of which
depends on the value of ``sipIsErr``.

If ``sipIsErr`` is ``NULL`` then a non-zero value is returned if the Python
object has a type that can be converted to the mapped type.  Otherwise zero is
returned.

If ``sipIsErr`` is not ``NULL`` then a combination of the following flags is
returned.

        - ``SIP_TEMPORARY`` is set to indicate that the returned instance is a
          temporary and should be released to avoid a memory leak.

        - ``SIP_DERIVED_CLASS`` is set to indicate that the type of the
          returned instance is a derived class.  See `Generated Derived
          Classes`_.

The following example converts a Python list of ``QPoint`` instances to a
``QList<QPoint>`` instance::

    %ConvertToTypeCode
        // See if we are just being asked to check the type of the Python
        // object.
        if (!sipIsErr)
        {
            // Checking whether or not None has been passed instead of a list
            // has already been done.
            if (!PyList_Check(sipPy))
                return 0;

            // Check the type of each element.  We specify SIP_NOT_NONE to
            // disallow None because it is a list of QPoint, not of a pointer
            // to a QPoint, so None isn't appropriate.
            for (int i = 0; i < PyList_GET_SIZE(sipPy); ++i)
                if (!sipCanConvertToInstance(PyList_GET_ITEM(sipPy, i),
                                             sipClass_QPoint, SIP_NOT_NONE))
                    return 0;

            // The type is valid.
            return 1;
        }

        // Create the instance on the heap.
        QList<QPoint> *ql = new QList<QPoint>;

        for (int i = 0; i < PyList_GET_SIZE(sipPy); ++i)
        {
            QPoint *qp;
            int state;

            // Get the address of the element's C++ instance.  Note that, in
            // this case, we don't apply any ownership changes to the list
            // elements, only to the list itself.
            qp = reinterpret_cast<QPoint *>(sipConvertToInstance(
                                                    PyList_GET_ITEM(sipPy, i),
                                                    sipClass_QPoint, 0,
                                                    SIP_NOT_NONE,
                                                    &state, sipIsErr));

            // Deal with any errors.
            if (*sipIsErr)
            {
                sipReleaseInstance(qp, sipClass_QPoint, state);

                // Tidy up.
                delete ql;

                // There is no temporary instance.
                return 0;
            }

            ql -> append(*qp);

            // A copy of the QPoint was appended to the list so we no longer
            // need it.  It may be a temporary instance that should be
            // destroyed, or a wrapped instance that should not be destroyed.
            // sipReleaseInstance() will do the right thing.
            sipReleaseInstance(qp, sipClass_QPoint, state);
        }

        // Return the instance.
        *sipCppPtr = ql;

        // The instance should be regarded as temporary (and be destroyed as
        // soon as it has been used) unless it has been transferred from
        // Python.  sipGetState() is a convenience function that implements
        // this common transfer behaviour.
        return sipGetState(sipTransferObj);
    %End

When used in a class specification the handwritten code replaces the code that
would normally be automatically generated.  This means that the handwritten
code must also handle instances of the class itself and not just the additional
types that are being supported.  This should be done by making calls to
`sipCanConvertToInstance()`_ to check the object type and
`sipConvertToInstance()`_ to convert the object.  The ``SIP_NO_CONVERTORS``
flag *must* be passed to both these functions to prevent recursive calls to the
handwritten code.


%Copying
--------

.. parsed-literal::

    %Copying
        *text*
    %End

This directive is used to specify some arbitrary text that will be included at
the start of all source files generated by SIP.  It is normally used to
include copyright and licensing terms.

For example::

    %Copying
    Copyright (c) 2007 Riverbank Computing Limited
    %End


%Doc
----

.. parsed-literal::

    %Doc
        *text*
    %End

This directive is used to specify some arbitrary text that will be extracted
by SIP when the ``-d`` command line option is used.  The directive can be
specified any number of times and SIP will concatenate all the separate pieces
of text in the order that it sees them.

Documentation that is specified using this directive is local to the module in
which it appears.  It is ignored by modules that `%Import`_ it.  Use the
`%ExportedDoc`_ directive for documentation that should be included by all
modules that `%Import`_ this one.

For example::

    %Doc
    <h1>An Example</h1>
    <p>
    This fragment of documentation is HTML and is local to the module in
    which it is defined.
    </p>
    %End


%End
----

This isn't a directive in itself, but is used to terminate a number of
directives that allow a block of handwritten code or text to be specified.


%Exception
----------

.. parsed-literal::

    %Exception *name* [(*base-exception)]
    {
        [*header-code*]
        *raise-code*
    };

This directive is used to define new Python exceptions, or to provide a stub
for existing Python exceptions.  It allows handwritten code to be provided
that implements the translation between C++ exceptions and Python exceptions.
The arguments to ``throw ()`` specifiers must either be names of classes or the
names of Python exceptions defined by this directive.

*name* is the name of the exception.

*base-exception* is the optional base exception.  This may be either one of
the standard Python exceptions or one defined with a previous `%Exception`_
directive.

*header-code* is the optional `%TypeHeaderCode`_ used to specify any external
interface to the exception being defined.

*raise-code* is the `%RaiseCode`_ used to specify the handwritten code that
converts a reference to the C++ exception to the Python exception.

For example::

    %Exception std::exception(SIP_Exception) /PyName=StdException/
    {
    %TypeHeaderCode
    #include <exception>
    %End
    %RaiseCode
            const char *detail = sipExceptionReference.what();

            SIP_BLOCK_THREADS
            PyErr_SetString(sipException_StdException, detail);
            SIP_UNBLOCK_THREADS
    %End
    };

In this example we map the standard C++ exception to a new Python exception.
The new exception is called ``StdException`` and is derived from the standard
Python exception ``Exception``.


%ExportedDoc
------------

.. parsed-literal::

    %ExportedDoc
        *text*
    %End

This directive is used to specify some arbitrary text that will be extracted
by SIP when the ``-d`` command line option is used.  The directive can be
specified any number of times and SIP will concatenate all the separate pieces
of text in the order that it sees them.

Documentation that is specified using this directive will also be included by
modules that `%Import`_ it.

For example::

    %ExportedDoc
    ==========
    An Example
    ==========
    
    This fragment of documentation is reStructuredText and will appear in the
    module in which it is defined and all modules that %Import it.
    %End


%ExportedHeaderCode
-------------------

.. parsed-literal::

    %ExportedHeaderCode
        *code*
    %End

This directive is used to specify handwritten code, typically the declarations
of types, that is placed in a header file that is included by all generated
code for all modules.  It should not include function declarations because
Python modules should not explicitly call functions in another Python module.

See also `%ModuleCode`_ and `%ModuleHeaderCode`_.


%Feature
--------

.. parsed-literal::

    %Feature *name*

This directive is used to declare a feature.  Features (along with
`%Platforms`_ and `%Timeline`_) are used by the `%If`_ directive to control
whether or not parts of a specification are processed or ignored.

Features are mutually independent of each other - any combination of features
may be enabled or disable.  By default all features are enabled.  The SIP
``-x`` command line option is used to disable a feature.

If a feature is enabled then SIP will automatically generate a corresponding C
preprocessor symbol for use by handwritten code.  The symbol is the name of
the feature prefixed by ``SIP_FEATURE_``.

For example::

    %Feature FOO_SUPPORT

    %If (FOO_SUPPORT)
    void foo();
    %End


%GCClearCode
------------

.. parsed-literal::

    %GCClearCode
        *code*
    %End

Python has a cyclic garbage collector which can identify and release unneeded
objects even when their reference counts are not zero.  If a wrapped C
structure or C++ class keeps its own reference to a Python object then, if the
garbage collector is to do its job, it needs to provide some handwritten code
to traverse and potentially clear those embedded references.

See the section *Supporting cyclic garbage collection* in `Embedding and
Extending the Python Interpreter <http://www.python.org/dev/doc/devel/ext/>`__
for the details.

This directive is used to specify the code that clears any embedded references.
(See `%GCTraverseCode`_ for specifying the code that traverses any embedded
references.)

The following variables are made available to the handwritten code:

*type* \*sipCpp
    This is a pointer to the structure or class instance.  Its *type* is a
    pointer to the structure or class.

int sipRes
    The handwritten code should set this to the result to be returned.

The following simplified example is taken from PyQt.  The ``QCustomEvent``
class allows arbitary data to be attached to the event.  In PyQt this data is
always a Python object and so should be handled by the garbage collector::

    %GCClearCode
        PyObject *obj;

        // Get the object.
        obj = reinterpret_cast<PyObject *>(sipCpp -> data());

        // Clear the pointer.
        sipCpp -> setData(0);

        // Clear the reference.
        Py_XDECREF(obj);

        // Report no error.
        sipRes = 0;
    %End


%GCTraverseCode
---------------

.. parsed-literal::

    %GCTraverseCode
        *code*
    %End

This directive is used to specify the code that traverses any embedded
references for Python's cyclic garbage collector.  (See `%GCClearCode`_ for a
full explanation.)

The following variables are made available to the handwritten code:

*type* \*sipCpp
    This is a pointer to the structure or class instance.  Its *type* is a
    pointer to the structure or class.

visitproc sipVisit
    This is the visit function provided by the garbage collector.

void \*sipArg
    This is the argument to the visit function provided by the garbage
    collector.

int sipRes
    The handwritten code should set this to the result to be returned.

The following simplified example is taken from PyQt's ``QCustomEvent`` class::

    %GCTraverseCode
        PyObject *obj;

        // Get the object.
        obj = reinterpret_cast<PyObject *>(sipCpp -> data());

        // Call the visit function if there was an object.
        if (obj)
            sipRes = sipVisit(obj, sipArg);
        else
            sipRes = 0;
    %End


%GetCode
--------

.. parsed-literal::

    %GetCode
        *code*
    %End

This directive is used after the declaration of a C++ class variable or C
structure member to specify handwritten code to convert it to a Python object.
It is usually used to handle types that SIP cannot deal with automatically.

The following variables are made available to the handwritten code:

*type* \*sipCpp
    This is a pointer to the structure or class instance.  Its *type* is a
    pointer to the structure or class.  It is not made available if the
    variable being wrapped is a static class variable.

PyObject \*sipPy
    The handwritten code must set this to the Python representation of the
    class variable or structure member.  If there is an error then the code
    must raise an exception and set this to ``NULL``.

For example::

    struct Entity
    {
        /*
         * In this contrived example the C library we are wrapping actually
         * defines this as char buffer[100] which SIP cannot handle
         * automatically.
         */
        char *buffer;
    %GetCode
            sipPy = PyString_FromStringAndSize(sipCpp -> buffer, 100);
    %End
    %SetCode
            char *ptr;
            int length;

            if (PyString_AsStringAndSize(sipPy, &ptr, &length) == -1)
                sipErr = 1;
            else if (length != 100)
            {
                /*
                 * Raise an exception because the length isn't exactly right.
                 */

                PyErr_SetString(PyExc_ValueError, "an Entity.buffer must be exactly 100 bytes");
                sipErr = 1;
            }
            else
                memcpy(sipCpp -> buffer, ptr, 100);
    %End
    }


%If
---

.. parsed-literal::

    %If (*expression*)
        *specification*
    %End

where

.. parsed-literal::

    *expression* ::= [*ored-qualifiers* | *range*]

    *ored-qualifiers* ::= [*qualifier* | *qualifier* ``||`` *ored-qualifiers*]

    *qualifier* ::= [``!``] [*feature* | *platform*]

    *range* ::= [*version*] ``-`` [*version*]

This directive is used in conjunction with features (see `%Feature`_),
platforms (see `%Platforms`_) and versions (see `%Timeline`_) to control
whether or not parts of a specification are processed or not.

A *range* of versions means all versions starting with the lower bound up to
but excluding the upper bound.  If the lower bound is omitted then it is
interpreted as being before the earliest version.  If the upper bound is
omitted then it is interpreted as being after the latest version.

For example::

    %Feature SUPPORT_FOO
    %Platforms {WIN32_PLATFORM POSIX_PLATFORM MACOS_PLATFORM}
    %Timeline {V1_0 V1_1 V2_0 V3_0}

    %If (!SUPPORT_FOO)
        // Process this if the SUPPORT_FOO feature is disabled.
    %End

    %If (POSIX_PLATFORM || MACOS_PLATFORM)
        // Process this if either the POSIX_PLATFORM or MACOS_PLATFORM
        // platforms are enabled.
    %End

    %If (V1_0 - V2_0)
        // Process this if either V1_0 or V1_1 is enabled.
    %End

    %If (V2_0 - )
        // Process this if either V2_0 or V3_0 is enabled.
    %End

    %If ( - )
        // Always process this.
    %End

Note that this directive is not implemented as a preprocessor.  Only the
following parts of a specification are affected by it:

    - ``class``
    - `%ConvertFromTypeCode`_
    - `%ConvertToSubClassCode`_
    - `%ConvertToTypeCode`_
    - ``enum``
    - `%ExportedHeaderCode`_
    - functions
    - `%GCClearCode`_
    - `%GCTraverseCode`_
    - `%If`_
    - `%MappedType`_
    - `%MethodCode`_
    - `%ModuleCode`_
    - `%ModuleHeaderCode`_
    - ``namespace``
    - `%PostInitialisationCode`_
    - `%PreInitialisationCode`_
    - ``struct``
    - ``typedef``
    - `%TypeCode`_
    - `%TypeHeaderCode`_
    - `%UnitCode`_
    - variables
    - `%VirtualCatcherCode`_

Also note that the only way to specify the logical and of qualifiers is to use
nested `%If`_ directives.


%Import
-------

.. parsed-literal::

    %Import *filename*

This directive is used to import the specification of another module.  This is
needed if the current module makes use of any types defined in the imported
module, e.g. as an argument to a function, or to sub-class.

If *filename* cannot be opened then SIP prepends *filename* with the name of
the directory containing the current specification file (i.e. the one
containing the `%Import`_ directive) and tries again.  If this also fails then
SIP prepends *filename* with each of the directories, in turn, specified by
the ``-I`` command line option.

For example::

    %Import qt/qtmod.sip


%Include
--------

.. parsed-literal::

    %Include *filename*

This directive is used to include contents of another file as part of the
specification of the current module.  It is the equivalent of the C
preprocessor's ``#include`` directive and is used to structure a large module
specification into manageable pieces.

`%Include`_ follows the same search process as `%Import`_ when trying to open
*filename*.

For example::

    %Include qwidget.sip


%License
--------

.. parsed-literal::

    %License /*license-annotations*/

This directive is used to specify the contents of an optional license
dictionary.  The license dictionary is called ``__license__`` and is stored in
the module dictionary.  The elements of the dictionary are specified using the
Licensee_, Signature_, Timestamp_ and Type_ annotations.  Only the Type_
annotation is compulsory.

Note that this directive isn't an attempt to impose any licensing restrictions
on a module.  It is simply a method for easily embedding licensing information
in a module so that it is accessible to Python scripts.

For example::

    %License /Type="GPL"/


%MappedType
-----------

.. parsed-literal::

    template<*type-list*>
    %MappedType *type*
    {
        [*header-code*]
        [*convert-to-code*]
        [*convert-from-code*]
    };

    %MappedType *type*
    {
        [*header-code*]
        [*convert-to-code*]
        [*convert-from-code*]
    };

This directive is used to define an automatic mapping between a C or C++ type
and a Python type.  It can be used as part of a template, or to map a specific
type.

When used as part of a template *type* cannot itself refer to a template.  Any
occurrences of any of the type names (but not any ``*`` or ``&``) in
*type-list* will be replaced by the actual type names used when the template is
instantiated.  Template mapped types are instantiated automatically as required
(unlike template classes which are only instantiated using ``typedef``).

Any explicit mapped type will be used in preference to any template that maps
the same type, ie. a template will not be automatically instantiated if there
is an explicit mapped type.

*header-code* is the `%TypeHeaderCode`_ used to specify the library interface
to the type being mapped.

*convert-to-code* is the `%ConvertToTypeCode`_ used to specify the handwritten
code that converts a Python object to an instance of the mapped type.

*convert-from-code* is the `%ConvertFromTypeCode`_ used to specify the
handwritten code that converts an instance of the mapped type to a Python
object.

For example::

    template<Type *>
    %MappedType QList
    {
    %TypeHeaderCode
    // Include the library interface to the type being mapped.
    #include <qlist.h>
    %End

    %ConvertToTypeCode
        // See if we are just being asked to check the type of the Python
        // object.
        if (sipIsErr == NULL)
        {
            // Check it is a list.
            if (!PyList_Check(sipPy))
                return 0;

            // Now check each element of the list is of the type we expect.
            // The template is for a pointer type so we don't disallow None.
            for (int i = 0; i < PyList_GET_SIZE(sipPy); ++i)
                if (!sipCanConvertToInstance(PyList_GET_ITEM(sipPy, i),
                                             sipClass_Type, 0))
                    return 0;

            return 1;
        }

        // Create the instance on the heap.
        QList<Type *> *ql = new QList<Type *>;

        for (int i = 0; i < PyList_GET_SIZE(sipPy); ++i)
        {
            // Use the SIP API to convert the Python object to the
            // corresponding C++ instance.  Note that we apply any ownership
            // transfer to the list itself, not the individual elements.
            Type *t = reinterpret_cast<Type *>(sipConvertToInstance(
                                                PyList_GET_ITEM(sipPy, i),
                                                sipClass_Type, 0, 0, 0,
                                                sipIsErr));

            if (*sipIsErr)
            {
                // Tidy up.
                delete ql;

                // There is nothing on the heap.
                return 0;
            }

            // Add the pointer to the C++ instance.
            ql -> append(t);
        }

        // Return the instance on the heap.
        *sipCppPtr = ql;

        // Apply the normal transfer.
        return sipGetState(sipTransferObj);
    %End

    %ConvertFromTypeCode
        PyObject *l;

        // Create the Python list of the correct length.
        if ((l = PyList_New(sipCpp -> size())) == NULL)
            return NULL;

        // Go through each element in the C++ instance and convert it to the
        // corresponding Python object.
        for (int i = 0; i < sipCpp -> size(); ++i)
        {
            Type *t = sipCpp -> at(i);
            PyObject *tobj;

            if ((tobj = sipConvertFromInstance(t, sipClass_Type, sipTransferObj)) == NULL)
            {
                // There was an error so garbage collect the Python list.
                Py_DECREF(l);
                return NULL;
            }

            PyList_SET_ITEM(l, i, tobj);
        }

        // Return the Python list.
        return l;
    %End
    }

Using this we can use, for example, ``QList<QObject *>`` throughout the
module's specification files (and in any module that imports this one).  The
generated code will automatically map this to and from a Python list of QObject
instances when appropriate.


%MethodCode
-----------

.. parsed-literal::

    %MethodCode
        *code*
    %End

This directive is used as part of the specification of a global function, class
method, operator, constructor or destructor to specify handwritten code that
replaces the normally generated call to the function being wrapped.  It is
usually used to handle argument types and results that SIP cannot deal with
automatically.

The specified code is embedded in-line after the function's arguments have
been successfully converted from Python objects to their C or C++ equivalents.
The specified code must not include any ``return`` statements.

In the context of a destructor the specified code is embedded in-line in the
Python type's deallocation function.  Unlike other contexts it supplements
rather than replaces the normally generated code, so it must not include code
to return the C structure or C++ class instance to the heap.  The code is only
called if ownership of the structure or class is with Python.

The specified code must also handle the Python Global Interpreter Lock (GIL).
If compatibility with SIP v3.x is required then the GIL must be released
immediately before the C++ call and reacquired immediately afterwards as shown
in this example fragment::

    Py_BEGIN_ALLOW_THREADS
    sipCpp -> foo();
    Py_END_ALLOW_THREADS

If compatibility with SIP v3.x is not required then this is optional but
should be done if the C++ function might block the current thread or take a
significant amount of time to execute.  (See `The Python Global Interpreter
Lock`_ and the ReleaseGIL_ and HoldGIL_ annotations.)

The following variables are made available to the handwritten code:

*type* a0
    There is a variable for each argument of the Python signature (excluding
    any ``self`` argument) named ``a0``, ``a1``, etc.  The *type* of the
    variable is the same as the type defined in the specification with the
    following exceptions:

    - if the argument is only used to return a value (e.g. it is an ``int *``
      without an In_ annotation) then the type has one less level of
      indirection (e.g. it will be an ``int``)
    - if the argument is a structure or class (or a reference or a pointer to a
      structure or class) then *type* will always be a pointer to the structure
      or class.

    Note that handwritten code for destructors never has any arguments.

PyObject \*a0Wrapper
    This variable is made available only if the corresponding argument wraps a
    C structure or C++ class instance and the GetWrapper_ annotation is
    specified.  The variable is a pointer to the Python object that wraps the
    argument.

*type* \*sipCpp
    If the directive is used in the context of a class constructor then this
    must be set by the handwritten code to the constructed instance.  In any
    other context then this is a pointer to the C structure or C++ class
    instance.  Its *type* is a pointer to the structure or class.

int sipIsErr
    The handwritten code should set this to a non-zero value, and raise an
    appropriate Python exception, if an error is detected.

    ``sipIsErr`` is not provided for destructors.

*type* sipRes
    The handwritten code should set this to the result to be returned.  The
    *type* of the variable is the same as the type defined in the Python
    signature in the specification with the following exception:

    - if the argument is a structure or class (or a reference or a pointer to a
      structure or class) then *type* will always be a pointer to the structure
      or class.

    ``sipRes`` is not provided for inplace operators (e.g. ``+=`` or
    ``__imul__``) as their results are handled automatically, nor for class
    constructors.

PyObject \*sipSelf
    If the directive is used in the context of a class constructor or method
    then this is the Python object that wraps the the structure or class
    instance, i.e. ``self``.

bool sipSelfWasArg
    This is only made available for non-abstract, virtual methods.  It is set
    if ``self`` was explicitly passed as the first argument of the method
    rather than being bound to the method.  In other words, the call was::

        Klass.foo(self, ...)

    rather than::

        self.foo(...)

The following is a complete example::

    class Klass
    {
    public:
        virtual int foo(SIP_PYTUPLE);
    %MethodCode
            // The C++ API takes a 2 element array of integers but passing a
            // two element tuple is more Pythonic.

            int iarr[2];

            if (PyArg_ParseTuple(a0, "ii", &iarr[0], &iarr[1]))
            {
                Py_BEGIN_ALLOW_THREADS
                sipRes = sipSelfWasArg ? sipCpp -> Klass::foo(iarr)
                                       : sipCpp -> foo(iarr);
                Py_END_ALLOW_THREADS
            }
            else
            {
                // PyArg_ParseTuple() will have raised the exception.
                sipIsErr = 1;
            }
    %End
    };

As the example is a virtual method [#]_, note the use of ``sipSelfWasArg`` to
determine exactly which implementation of ``foo()`` to call.

If a method is in the ``protected`` section of a C++ class then the call
should instead be::

    sipRes = sipCpp -> sipProtectVirt_foo(sipSelfWasArg, iarr);

If a method is in the ``protected`` section of a C++ class but is not virtual
then the call should instead be::

    sipRes = sipCpp -> sipProtect_foo(iarr);

.. [#] See `%VirtualCatcherCode`_ for a description of how SIP generated code
       handles the reimplementation of C++ virtual methods in Python.


%Module
-------

.. parsed-literal::

    %Module *name* [*version*]

This directive is used to identify that the library being wrapped is a C++
library and to define the name of the module and it's optional version number.

The name may contain periods to specify that the module is part of a Python
package.

The optional version number is useful if you (or others) might create other
modules that build on this module, i.e. if another module might `%Import`_
this module.  Under the covers, a module exports an API that is used by modules
that `%Import`_ it and the API is given a version number.  A module built on
that module knows the version number of the API that it is expecting.  If,
when the modules are imported at run-time, the version numbers do not match
then a Python exception is raised.  The dependent module must then be re-built
using the correct specification files for the base module.

The version number should be incremented whenever a module is changed.  Some
changes don't affect the exported API, but it is good practice to change the
version number anyway.

For example::

    %Module qt 5


%ModuleCode
-----------

.. parsed-literal::

    %ModuleCode
        *code*
    %End

This directive is used to specify handwritten code, typically the
implementations of utility functions, that can be called by other handwritten
code in the module.

For example::

    %ModuleCode
    // Print an object on stderr for debugging purposes.
    void dump_object(PyObject *o)
    {
        PyObject_Print(o, stderr, 0);
        fprintf(stderr, "\n");
    }
    %End

See also `%ExportedHeaderCode`_ and `%ModuleHeaderCode`_.


%ModuleHeaderCode
-----------------

.. parsed-literal::

    %ModuleHeaderCode
        *code*
    %End

This directive is used to specify handwritten code, typically the declarations
of utility functions, that is placed in a header file that is included by all
generated code for the same module.

For example::

    %ModuleHeaderCode
    void dump_object(PyObject *o);
    %End

See also `%ExportedHeaderCode`_ and `%ModuleCode`_.


%OptionalInclude
----------------

.. parsed-literal::

    %OptionalInclude *filename*

This directive is identical to the `%Include`_ directive except that SIP
silently continues processing if *filename* could not be opened.

For example::

    %OptionalInclude license.sip


%Platforms
----------

.. parsed-literal::

    %Platforms {*name* *name* ...}

This directive is used to declare a set of platforms.  Platforms (along with
`%Feature`_ and `%Timeline`_) are used by the `%If`_ directive to control
whether or not parts of a specification are processed or ignored.

Platforms are mutually exclusive - only one platform can be enabled at a time.
By default all platforms are disabled.  The SIP ``-t`` command line option is
used to enable a platform.

For example::

    %Platforms {WIN32_PLATFORM POSIX_PLATFORM MACOS_PLATFORM}

    %If (WIN32_PLATFORM)
    void undocumented();
    %End

    %If (POSIX_PLATFORM)
    void documented();
    %End


%PostInitialisationCode
-----------------------

.. parsed-literal::

    %PostInitialisationCode
        *code*
    %End

This directive is used to specify handwritten code that is embedded in-line
at the very end of the generated module initialisation code.

The following variables are made available to the handwritten code:

PyObject \*sipModule
    This is the module object returned by ``Py_InitModule()``.

PyObject \*sipModuleDict
    This is the module's dictionary object returned by ``Py_ModuleGetDict()``.

For example::

    %PostInitialisationCode
        // The code will be executed when the module is first imported and
        // after all other initialisation has been completed.
    %End


%PreInitialisationCode
----------------------

.. parsed-literal::

    %PreInitialisationCode
        *code*
    %End

This directive is used to specify handwritten code that is embedded in-line
at the very start of the generated module initialisation code.

For example::

    %PreInitialisationCode
        // The code will be executed when the module is first imported and
        // before other initialisation has been completed.
    %End


%RaiseCode
----------

.. parsed-literal::

    %RaiseCode
        *code*
    %End

This directive is used as part of the definition of an exception using the
`%Exception`_ directive to specify handwritten code that raises a Python
exception when a C++ exception has been caught.  The code is embedded in-line
as the body of a C++ ``catch ()`` clause.

The specified code must handle the Python Global Interpreter Lock (GIL) if
necessary.  The GIL must be acquired before any calls to the Python API and
released after the last call as shown in this example fragment::

    SIP_BLOCK_THREADS
    PyErr_SetNone(PyErr_Exception);
    SIP_UNBLOCK_THREADS

Finally, the specified code must not include any ``return`` statements.

The following variable is made available to the handwritten code:

*type* &sipExceptionRef
    This is a reference to the caught C++ exception.  The *type* of the
    reference is the same as the type defined in the ``throw ()`` specifier.

See the `%Exception`_ directive for an example.


%SetCode
--------

.. parsed-literal::

    %SetCode
        *code*
    %End

This directive is used after the declaration of a C++ class variable or C
structure member to specify handwritten code to convert it from a Python
object.  It is usually used to handle types that SIP cannot deal with
automatically.

The following variables are made available to the handwritten code:

*type* \*sipCpp
    This is a pointer to the structure or class instance.  Its *type* is a
    pointer to the structure or class.  It is not made available if the
    variable being wrapped is a static class variable.

int sipErr
    If the conversion failed then the handwritten code should raise a Python
    exception and set this to a non-zero value.  Its initial value will be
    automatically set to zero.

PyObject \*sipPy
    This is the Python object that the handwritten code should convert.

See the `%GetCode`_ directive for an example.


%SIPOptions
-----------

This directive sets one or more options that controls different aspects of
SIP's behaviour.  In this version all the available options are provided
specifically to support PyQt and so are not documented.


%Timeline
---------

.. parsed-literal::

    %Timeline {*name* *name* ...}

This directive is used to declare a set of versions released over a period of
time.  Versions (along with `%Feature`_ and `%Platforms`_) are used by the
`%If`_ directive to control whether or not parts of a specification are
processed or ignored.

Versions are mutually exclusive - only one version can be enabled at a time.
By default all versions are disabled.  The SIP ``-t`` command line option is
used to enable a version.

For example::

    %Timeline {V1_0 V1_1 V2_0 V3_0}

    %If (V1_0 - V2_0)
    void foo();
    %End

    %If (V2_0 -)
    void foo(int = 0);
    %End

`%Timeline`_ can be used any number of times in a module to allow multiple
libraries to be wrapped in the same module.


%TypeCode
---------

.. parsed-literal::

    %TypeCode
        *code*
    %End

This directive is used as part of the specification of a C structure or a C++
class to specify handwritten code, typically the implementations of utility
functions, that can be called by other handwritten code in the structure or
class.

For example::

    class Klass
    {
    %TypeCode
    // Print an instance on stderr for debugging purposes.
    static void dump_klass(const Klass *k)
    {
        fprintf(stderr,"Klass %s at %p\n", k -> name(), k);
    }
    %End

        // The rest of the class specification.

    };

Because the scope of the code is normally within the generated file that
implements the type, any utility functions would normally be declared
``static``.  However a naming convention should still be adopted to prevent
clashes of function names within a module in case the SIP ``-j`` command line
option is used.


%TypeHeaderCode
---------------

.. parsed-literal::

    %TypeHeaderCode
        *code*
    %End

This directive is used to specify handwritten code that defines the interface
to a C or C++ type being wrapped, either a structure, a class, or a template.
It is used within a class definition or a `%MappedType`_ directive.

Normally *code* will be a pre-processor ``#include`` statement.

For example::

    // Wrap the Klass class.
    class Klass
    {
    %TypeHeaderCode
    #include <klass.h>
    %End

        // The rest of the class specification.
    };


%UnitCode
---------

.. parsed-literal::

    %UnitCode
        *code*
    %End

This directive is used to specify handwritten code that it included at the very
start of a generated compilation unit (ie. C or C++ source file).  It is
typically used to ``#include`` a C++ precompiled header file.


%VirtualCatcherCode
-------------------

.. parsed-literal::

    %VirtualCatcherCode
        *code*
    %End

For most classes there are corresponding `generated derived classes`_ that
contain reimplementations of the class's virtual methods.  These methods (which
SIP calls catchers) determine if there is a corresponding Python
reimplementation and call it if so.  If there is no Python reimplementation
then the method in the original class is called instead.

This directive is used to specify handwritten code that replaces the normally
generated call to the Python reimplementation and the handling of any returned
results.  It is usually used to handle argument types and results that SIP
cannot deal with automatically.

This directive can also be used in the context of a class destructor to
specify handwritten code that is embedded in-line in the internal derived
class's destructor.

In the context of a method the Python Global Interpreter Lock (GIL) is
automatically acquired before the specified code is executed and automatically
released afterwards.

In the context of a destructor the specified code must handle the GIL.  The
GIL must be acquired before any calls to the Python API and released after the
last call as shown in this example fragment::

    SIP_BLOCK_THREADS
    Py_DECREF(obj);
    SIP_UNBLOCK_THREADS

The following variables are made available to the handwritten code in the
context of a method:

*type* a0
    There is a variable for each argument of the C++ signature named ``a0``,
    ``a1``, etc.  The *type* of the variable is the same as the type defined in
    the specification.

int sipIsErr
    The handwritten code should set this to a non-zero value, and raise an
    appropriate Python exception, if an error is detected.

PyObject \*sipMethod
    This object is the Python reimplementation of the virtual C++ method.  It
    is normally passed to `sipCallMethod()`_.

*type* sipRes
    The handwritten code should set this to the result to be returned.  The
    *type* of the variable is the same as the type defined in the C++ signature
    in the specification.

No variables are made available in the context of a destructor.

For example::

    class Klass
    {
    public:
        virtual int foo(SIP_PYTUPLE) [int (int *)];
    %MethodCode
            // The C++ API takes a 2 element array of integers but passing a
            // two element tuple is more Pythonic.

            int iarr[2];

            if (PyArg_ParseTuple(a0, "ii", &iarr[0], &iarr[1]))
            {
                Py_BEGIN_ALLOW_THREADS
                sipRes = sipCpp -> Klass::foo(iarr);
                Py_END_ALLOW_THREADS
            }
            else
            {
                // PyArg_ParseTuple() will have raised the exception.
                sipIsErr = 1;
            }
    %End
    %VirtualCatcherCode
            // Convert the 2 element array of integers to the two element
            // tuple.

            PyObject *result;

            result = sipCallMethod(&sipIsErr, sipMethod, "ii", a0[0], a0[1]);

            if (result != NULL)
            {
                // Convert the result to the C++ type.
                sipParseResult(&sipIsErr, sipMethod, result, "i", &sipRes);

                Py_DECREF(result);
            }
    %End
    };


SIP Annotations
===============

In this section we describe each of the annotations that can be used in
specification files.

Annotations can either be argument annotations, class annotations, enum
annotations, exception annotations, function annotations, license annotations,
or variable annotations depending on the context in which they can be used.

Annotations are placed between forward slashes (``/``).  Multiple annotations
are comma separated within the slashes.

Annotations have a type and, possibly, a value.  The type determines the
format of the value.  The name of an annotation and its value are separated by
``=``.

Annotations can have one of the following types:

boolean
    This type of annotation has no value and is implicitly true.

name
    The value is a name that is compatible with a C/C++ identifier.  In some
    cases the value is optional.

string
    The value is a double quoted string.

The following example shows argument and function annotations::

    void exec(QWidget * /Transfer/) /ReleaseGIL, PyName=call_exec/;

Note that the current version of SIP does not complain about unknown
annotations, or annotations used out of their correct context.


Argument Annotations
--------------------

AllowNone
*********

This boolean annotation specifies that the value of the corresponding argument
(which should be either SIP_PYCALLABLE_, SIP_PYDICT_, SIP_PYLIST_,
SIP_PYSLICE_, SIP_PYTUPLE_ or SIP_PYTYPE_) may be ``None``.


Array
*****

This boolean annotation specifies that the corresponding argument (which
should be either ``char *`` or ``unsigned char *``) refers to an array
rather than a ``'\0'`` terminated string.  There must be a corresponding
argument with the ArraySize_ annotation specified.  The annotation may only be
specified once in a list of arguments.


ArraySize
*********

This boolean annotation specifies that the corresponding argument (which
should be either ``short``, ``unsigned short``, ``int``, ``unsigned``,
``long`` or ``unsigned long``) refers to the size of an array.  There must be
a corresponding argument with the Array_ annotation specified.  The annotation
may only be specified once in a list of arguments.


Constrained
***********

Python will automatically convert between certain compatible types.  For
example, if a floating pointer number is expected and an integer supplied,
then the integer will be converted appropriately.  This can cause problems
when wrapping C or C++ functions with similar signatures.  For example::

    // The wrapper for this function will also accept an integer argument
    // which Python will automatically convert to a floating point number.
    void foo(double);

    // The wrapper for this function will never get used.
    void foo(int);

This boolean annotation specifies that the corresponding argument (which
should be either ``bool``, ``int``, ``float``, ``double`` or a wrapped class)
must match the type without any automatic conversions.  In the context of a
wrapped class the invocation of any `%ConvertToTypeCode`_ is suppressed.

The following example gets around the above problem::

    // The wrapper for this function will only accept floating point numbers.
    void foo(double /Constrained/);

    // The wrapper for this function will be used for anything that Python can
    // convert to an integer, except for floating point numbers.
    void foo(int);


GetWrapper
**********

This boolean annotation is only ever used in conjunction with handwritten code
specified with the `%MethodCode`_ directive.  It causes an extra variable to
be generated for the corresponding argument (which should be a wrapped C
structure or C++ class instance) which is a pointer to the Python object that
wraps the argument.

See the `%MethodCode`_ directive for more detail.


In
**

This boolean annotation is used to specify that the corresponding argument
(which should be a pointer type) is used to pass a value to the function.

For pointers to wrapped C structures or C++ class instances, ``char *`` and
``unsigned char *`` then this annotation is assumed unless the Out_ annotation
is specified.

For pointers to other types then this annotation must be explicitly specified
if required.  The argument will be dereferenced to obtain the actual value.

Both In_ and Out_ may be specified for the same argument.


Out
***

This boolean annotation is used to specify that the corresponding argument
(which should be a pointer type) is used by the function to return a value as
an element of a tuple.

For pointers to wrapped C structures or C++ class instances, ``char *`` and
``unsigned char *`` then this annotation must be explicitly specified if
required.

For pointers to other types then this annotation is assumed unless the In_
annotation is specified.

Both In_ and Out_ may be specified for the same argument.


Transfer
********

This boolean annotation is used to specify that ownership of the corresponding
argument (which should be a wrapped C structure or C++ class instance) is
transferred from Python to C++.  In addition, if the argument is of a class
method, then it is associated with the class instance with regard to the
cyclic garbage collector.

See `Ownership of Objects`_ for more detail.


TransferBack
************

This boolean annotation is used to specify that ownership of the corresponding
argument (which should be a wrapped C structure or C++ class instance) is
transferred back to Python from C++.  In addition, any association of the
argument with regard to the cyclic garbage collector with another instance is
removed.

Note that this can also be used as a function annotation.

See `Ownership of Objects`_ for more detail.


TransferThis
************

This boolean annotation is only used in C++ constructors or methods.  In the
context of a constructor or factory method it specifies that ownership of the
instance being created is transferred from Python to C++ if the corresponding
argument (which should be a wrapped C structure or C++ class instance) is not
``None``.  In addition, the newly created instance is associated with the
argument with regard to the cyclic garbage collector.

In the context of a non-factory method it specifies that ownership of ``this``
is transferred from Python to C++ if the corresponding argument is not
``None``.  If it is ``None`` then ownership is transferred to Python.

The annotation may be used more that once, in which case ownership is
transferred to last instance that is not ``None``.

See `Ownership of Objects`_ for more detail.


Class Annotations
-----------------

Abstract
********

This boolean annotation is used to specify that the class has additional pure
virtual methods that have not been specified and so it cannot be instantiated
or sub-classed from Python.


DelayDtor
*********

This boolean annotation is used to specify that the class's destructor should
not be called until the Python interpreter exits.  It would normally only be
applied to singleton classes.

When the Python interpreter exits the order in which any wrapped instances are
garbage collected is unpredictable.  However, the underlying C or C++ instances
may need to be destroyed in a certain order.  If this annotation is specified
then when the wrapped instance is garbage collected the C or C++ instance is
not destroyed but instead added to a list of delayed instances.  When the
interpreter exits then the function ``sipDelayedDtors`` is called with the
list of delayed instances.  ``sipDelayedDtors`` can then choose to call (or
ignore) the destructors in any desired order.

The ``sipDelayedDtors`` function must be specified using the `%ModuleCode`_
directive.  It's signature is as follows::

    static void sipDelayedDtors(const sipDelayedDtor *dd_list);

``dd_list`` is the linked list of delayed instances.  The following fields are
defined.

const char \*dd_name
    This is the name of the class excluding any package or module name.

void \*dd_ptr
    This is the address of the C or C++ instance to be destroyed.  It's exact
    type depends on the value of ``dd_isderived``.

int dd_isderived
    This is non-zero if the type of ``dd_ptr`` is actually the generated
    derived class.  This allows the correct destructor to be called.  See
    `Generated Derived Classes`_.

sipDelayedDtor \*dd_next
    This is the address of the next entry in the list or zero if this is the
    last one.

Note that the above applies only to C and C++ instances that are owned by
Python.


External
********

This boolean annotation is used to specify that the class is defined in another
module.  Declarations of external classes are private to the module in which
they appear.


NoDefaultCtors
**************

This boolean annotation is used to suppress the automatic generation of default
constructors for the class.


PyName
******

This name annotation specifies an alternative name for the class being wrapped
which is used when it is referred to from Python.  It is required when a class
name is the same as a Python keyword.  It may also be used to avoid name
clashes with other objects (e.g. enums, exceptions, functions) that have the
same name in the same C++ scope.


Enum Annotations
----------------

PyName
******

This name annotation specifies an alternative name for the enum or enum member
being wrapped which is used when it is referred to from Python.  It is required
when an enum or enum member name is the same as a Python keyword.  It may also
be used to avoid name clashes with other objects (e.g. classes, exceptions,
functions) that have the same name in the same C++ scope.


Exception Annotations
---------------------

PyName
******

This name annotation specifies an alternative name for the exception being
defined which is used when it is referred to from Python.  It is required when
an exception name is the same as a Python keyword.  It may also be used to
avoid name clashes with other objects (e.g. classes, enums, functions) that
have the same name.


Function Annotations
--------------------

AutoGen
*******

This optional name annotation is used with class methods to specify that the
method be automatically included in all sub-classes.  The value is the name of
a feature (specified using the `%Feature`_ directive) which must be enabled
for the method to be generated.


Default
*******

This boolean annotation is only used with C++ constructors.  Sometimes SIP
needs to create a class instance.  By default it uses a constructor with no
compulsory arguments if one is specified.  (SIP will automatically generate a
constructor with no arguments if no constructors are specified.)  This
annotation is used to explicitly specify which constructor to use.  Zero is
passed as the value of any arguments to the constructor.


Factory
*******

This boolean annotation specifies that the value returned by the function
(which should be a wrapped C structure or C++ class instance) is a newly
created instance and is owned by Python.

See `Ownership of Objects`_ for more detail.


HoldGIL
*******

This boolean annotation specifies that the Python Global Interpreter Lock (GIL)
is not released before the call to the underlying C or C++ function.  See
`The Python Global Interpreter Lock`_ and the ReleaseGIL_ annotation.


NewThread
*********

This boolean annotation specifies that the function will create a new thread.


NoDerived
*********

This boolean annotation is only used with C++ constructors.  In many cases SIP
generates a derived class for each class being wrapped (see `Generated Derived
Classes`_).  This derived class contains constructors with the same C++
signatures as the class being wrapped.  Sometimes you may want to define a
Python constructor that has no corresponding C++ constructor.  This annotation
is used to suppress the generation of the constructor in the derived class.


Numeric
*******

This boolean annotation specifies that the operator should be interpreted as a
numeric operator rather than a sequence operator.  Python uses the ``+``
operator for adding numbers and concatanating sequences, and the ``*`` operator
for multiplying numbers and repeating sequences.  SIP tries to work out which
is meant by looking at other operators that have been defined for the type.
If it finds either ``-``, ``-=``, ``/``, ``/=``, ``%`` or ``%=`` defined then
it assumes that ``+``, ``+=``, ``*`` and ``*=`` should be numeric operators.
Otherwise, if it finds either ``[]``, ``__getitem__()``, ``__setitem__()`` or
``__delitem__()`` defined then it assumes that they should be sequence
operators.  This annotation is used to force SIP to treat the operator as
numeric.


PostHook
********

This name annotation is used to specify the name of a Python builtin that is
called immediately after the call to the underlying C or C++ function or any
handwritten code.  The builtin is not called if an error occurred.  It is
primarily used to integrate with debuggers.


PreHook
*******

This name annotation is used to specify the name of a Python builtin that is
called immediately after the function's arguments have been successfully
parsed and before the call to the underlying C or C++ function or any
handwritten code.  It is primarily used to integrate with debuggers.


PyName
******

This name annotation specifies an alternative name for the function being
wrapped which is used when it is referred to from Python.  It is required when
a function or method name is the same as a Python keyword.  It may also be used
to avoid name clashes with other objects (e.g. classes, enums, exceptions) that
have the same name in the same C++ scope.


ReleaseGIL
**********

This boolean annotation specifies that the Python Global Interpreter Lock (GIL)
is released before the call to the underlying C or C++ function and reacquired
afterwards.  It should be used for functions that might block or take a
significant amount of time to execute.  See `The Python Global Interpreter
Lock`_ and the HoldGIL_ annotation.


TransferBack
************

This boolean annotation specifies that ownership of the value returned by the
function (which should be a wrapped C structure or C++ class instance) is
transferred back to Python from C++.  Normally returned values (unless they are
new references to already wrapped values) are owned by C++.  In addition, any
association of the returned value with regard to the cyclic garbage collector
with another instance is removed.

Note that this can also be used as an argument annotation.

See `Ownership of Objects`_ for more detail.


License Annotations
-------------------

Licensee
********

This optional string annotation specifies the license's licensee.  No
restrictions are placed on the contents of the string.

See the `%License`_ directive.


Signature
*********

This optional string annotation specifies the license's signature.  No
restrictions are placed on the contents of the string.

See the `%License`_ directive.


Timestamp
*********

This optional string annotation specifies the license's timestamp.  No
restrictions are placed on the contents of the string.

See the `%License`_ directive.


Type
****

This string annotation specifies the license's type.  No restrictions are
placed on the contents of the string.

See the `%License`_ directive.


Variable Annotations
--------------------

PyName
******

This name annotation specifies an alternative name for the variable being
wrapped which is used when it is referred to from Python.  It is required when
a variable name is the same as a Python keyword.  It may also be used to avoid
name clashes with other objects (e.g. classes, functions) that have the same
name in the same C++ scope.


SIP API for Handwritten Code
============================

In this section we describe the API that can be used by handwritten code in
specification files.


SIP_API_MAJOR_NR
----------------

This is a C preprocessor symbol that defines the major number of the SIP API.
Its value is a number.  There is no direct relationship between this and the
SIP version number.


SIP_API_MINOR_NR
----------------

This is a C preprocessor symbol that defines the minor number of the SIP API.
Its value is a number.  There is no direct relationship between this and the
SIP version number.


SIP_BLOCK_THREADS
-----------------

This is a C preprocessor macro that will make sure the Python Global
Interpreter Lock (GIL) is acquired.  Python API calls must only be made when
the GIL has been acquired.  There must be a corresponding
`SIP_UNBLOCK_THREADS`_ at the same lexical scope.


SIP_SSIZE_T
-----------

This is a C preprocessor macro that is defined as ``Py_ssize_t`` for Python
v2.5 and later, and as ``int`` for earlier versions of Python.  It makes it
easier to write PEP 353 compliant handwritten code.


SIP_UNBLOCK_THREADS
-------------------

This is a C preprocessor macro that will restore the Python Global Interpreter
Lock (GIL) to the state it was prior to the corresponding `SIP_BLOCK_THREADS`_.


SIP_VERSION
-----------

This is a C preprocessor symbol that defines the SIP version number
represented as a 3 part hexadecimal number (e.g. v4.0.0 is represented as
``0x040000``).


SIP_VERSION_STR
---------------

This is a C preprocessor symbol that defines the SIP version number
represented as a string.  For development snapshots it will start with
``snapshot-``.


sipBadCatcherResult()
---------------------

void sipBadCatcherResult(PyObject \*method)
    This raises a Python exception when the result of a Python reimplementation
    of a C++ method doesn't have the expected type.  It is normally called by
    handwritten code specified with the `%VirtualCatcherCode`_ directive.
    *method* is the Python method and would normally be the supplied
    ``sipMethod``.


sipBadLengthForSlice()
----------------------

void sipBadLengthForSlice(SIP_SSIZE_T seqlen, SIP_SSIZE_T slicelen)
    This raises a Python exception when the length of a slice object is
    inappropriate for a sequence-like object.  It is normally called by
    handwritten code specified for ``__setitem__()`` methods.  *seqlen* is the
    length of the sequence.  *slicelen* is the length of the slice.  With
    versions of Python prior to v2.5 the arguments have type ``int``.


sipBuildResult()
----------------

PyObject \*sipBuildResult(int \*iserr, const char \*format, ...)
    This creates a Python object based on a format string and associated
    values in a similar way to the Python ``Py_BuildValue()`` function.  If
    there was an error then ``NULL`` is returned and a Python exception is
    raised.  If *iserr* is not ``NULL`` then the location it points to is set
    to a non-zero value.  *format* is the string of format characters.

    If *format* begins and ends with parentheses then a tuple of objects is
    created.  If *format* contains more than one format character then
    parentheses must be specified.

    In the following description the first letter is the format character, the
    entry in parentheses is the Python object type that the format character
    will create, and the entry in brackets are the types of the C/C++ values
    to be passed. 

    ``a`` (string) [char \*, int]
        Convert a C/C++ character array and its length to a Python string.  If
        the array is ``NULL`` then the length is ignored and the result is
        ``Py_None``.

    ``b`` (boolean) [int]
        Convert a C/C++ ``int`` to a Python boolean.

    ``c`` (string) [char]
        Convert a C/C++ ``char`` to a Python string.

    ``d`` (float) [double]
        Convert a C/C++ ``double`` to a Python floating point number.

    ``e`` (integer) [enum]
        Convert an anonymous C/C++ ``enum`` to a Python integer.

    ``f`` (float) [float]
        Convert a C/C++ ``float`` to a Python floating point number.

    ``h`` (integer) [short]
        Convert a C/C++ ``short`` to a Python integer.

    ``i`` (integer) [int]
        Convert a C/C++ ``int`` to a Python integer.

    ``l`` (long) [long]
        Convert a C/C++ ``long`` to a Python integer.

    ``m`` (long) [unsigned long]
        Convert a C/C++ ``unsigned long`` to a Python long.

    ``n`` (long) [long long]
        Convert a C/C++ ``long long`` to a Python long.

    ``o`` (long) [unsigned long long]
        Convert a C/C++ ``unsigned long long`` to a Python long.

    ``s`` (string) [char \*]
        Convert a C/C++ ``'\0'`` terminated string to a Python string.  If the
        string pointer is ``NULL`` then the result is ``Py_None``.

    ``t`` (long) [unsigned short]
        Convert a C/C++ ``unsigned short`` to a Python long.

    ``u`` (long) [unsigned int]
        Convert a C/C++ ``unsigned int`` to a Python long.

    ``w`` (unicode) [wchar_t]
        Convert a C/C++ wide character to a Python unicode object.

    ``x`` (unicode) [wchar_t \*]
        Convert a C/C++ ``L'\0'`` terminated wide character string to a Python
        unicode object.  If the string pointer is ``NULL`` then the result is
        ``Py_None``.

    ``A`` (unicode) [wchar_t \*, int]
        Convert a C/C++ wide character array and its length to a Python unicode
        object.  If the array is ``NULL`` then the length is ignored and the
        result is ``Py_None``.

    ``B`` (wrapped instance) [*type* \*, sipWrapperType \*, PyObject \*]
        Convert a new C structure or a new C++ class instance to a Python class
        instance object.  Ownership of the structure or instance is determined
        by the ``PyObject *`` argument.  If it is ``NULL`` and the instance has
        already been wrapped then the ownership is unchanged.  If it is
        ``NULL`` or ``Py_None`` then ownership will be with Python.  Otherwise
        ownership will be with C/C++ and the instance associated with the
        ``PyObject *`` argument.  The Python class is influenced by any
        applicable `%ConvertToSubClassCode`_ code.

    ``C`` (wrapped instance) [*type* \*, sipWrapperType \*, PyObject \*]
        Convert a C structure or a C++ class instance to a Python class
        instance object.  If the structure or class instance has already been
        wrapped then the result is a new reference to the existing class
        instance object.  Ownership of the structure or instance is determined
        by the ``PyObject *`` argument.  If it is ``NULL`` and the instance has
        already been wrapped then the ownership is unchanged.  If it is
        ``NULL`` and the instance is newly wrapped then ownership will be with
        C/C++.  If it is ``Py_None`` then ownership is transferred to Python
        via a call to `sipTransferBack()`_.  Otherwise ownership is transferred
        to C/C++ and the instance associated with the ``PyObject *`` argument
        via a call to `sipTransferTo()`_.  The Python class is influenced by
        any applicable `%ConvertToSubClassCode`_ code.

    ``D`` (object) [*type* \*, const sipMappedType \*, PyObject \*]
        Convert a C structure or a C++ class instance wrapped as a mapped type
        to a Python object.  Ownership of the structure or instance is
        determined by the ``PyObject *`` argument.  If it is ``NULL`` then the
        ownership is unchanged.  If it is ``Py_None`` then ownership is
        transferred to Python via a call to `sipTransferBack()`_.  Otherwise
        ownership is transferred to C/C++ and the instance associated with the
        ``PyObject *`` argument via a call to `sipTransferTo()`_.

    ``E`` (wrapped enum) [enum, PyTypeObject \*]
        Convert a named C/C++ ``enum`` to an instance of the corresponding
        Python named enum type.

    ``M`` (wrapped instance) [*type* \*, sipWrapperType \*]
        Convert a C structure or a C++ class instance to a Python class
        instance object.  If the structure or class instance has already been
        wrapped then the result is a new reference to the existing class
        instance object.  If the instance has already been wrapped then the
        ownership is unchanged.  If the instance is newly wrapped then
        ownership will be with C/C++.  The Python class is influenced by any
        applicable `%ConvertToSubClassCode`_ code.  This is deprecated from
        SIP v4.4.

    ``N`` (wrapped instance) [*type* \*, sipWrapperType \*]
        Convert a C structure or a C++ class instance to a Python class
        instance object.  This should not be used if the structure or class
        instance might already have been wrapped.  Ownership of the structure
        or instance will be with Python.  The Python class is influenced by
        any applicable `%ConvertToSubClassCode`_ code.  This is deprecated
        from SIP v4.4.

    ``O`` (wrapped instance) [*type* \*, sipWrapperType \*]
        Convert a C structure or a C++ class instance to a Python class
        instance object.  If the structure or class instance has already been
        wrapped then the result is a new reference to the existing class
        instance object.  Ownership of the structure or instance will be with
        C/C++.  This is deprecated from SIP v4.4.

    ``P`` (wrapped instance) [*type* \*, sipWrapperType \*]
        Convert a C structure or a C++ class instance to a Python class
        instance object.  This should not be used if the structure or class
        instance might already have been wrapped.  Ownership of the structure
        or instance will be with Python.  This is deprecated from SIP v4.4.

    ``R`` (object) [PyObject \*]
        The result is value passed without any conversions.  The reference
        count is unaffected, i.e. a reference is taken.

    ``S`` (object) [PyObject \*]
        The result is value passed without any conversions.  The reference
        count is incremented.

    ``T`` (object) [void \*, PyObject \*(\*)(void \*cppptr)]
        Convert a C structure or a C++ class instance to a Python object using
        a convertor function.  See `Generated Type Convertors`_.  This is
        deprecated from SIP v4.4.

    ``V`` (sip.voidptr) [void \*]
        Convert a C/C++ ``void *`` Python ``sip.voidptr`` object.


sipCallMethod()
---------------

PyObject \*sipCallMethod(int \*iserr, PyObject \*method, const char \*format, ...)
    This calls a Python method passing a tuple of arguments based on a format
    string and associated values in a similar way to the Python
    ``PyObject_CallObject()`` function.  If there was an error then ``NULL`` is
    returned and a Python exception is raised.  If *iserr* is not ``NULL``
    then the location it points to is set to a non-zero value.  *method* is the
    Python bound method to call.  *format* is the string of format characters
    (see `sipBuildResult()`_).

    This is normally called by handwritten code specified with the
    `%VirtualCatcherCode`_ directive with *method* being the supplied
    ``sipMethod``.


sipCanConvertToInstance()
-------------------------

int sipCanConvertToInstance(PyObject \*obj, sipWrapperType \*type, int flags)
    This returns a non-zero value if a Python object can be converted to an
    instance of a C structure or C++ class.  *obj* is the Python object.
    *type* is the generated type corresponding to the C/C++ type being checked.
    *flags* is any combination of the following values used to fine tune the
    check.

        - ``SIP_NOT_NONE`` causes the check to fail if *obj* is ``None``.

        - ``SIP_NO_CONVERTORS`` suppresses the use of of any
          `%ConvertToTypeCode`_ for *type*.


sipCanConvertToMappedType()
---------------------------

int sipCanConvertToMappedType(PyObject \*obj, const sipMappedType \*mt, int flags)
    This returns a non-zero value if a Python object can be converted to an
    instance of a C structure or C++ class which has been implemented as a
    mapped type.  *obj* is the Python object.  *mt* is an opaque structure
    returned by `sipFindMappedType()`_.  *flags* is any combination of the
    following values used to fine tune the check.

        - ``SIP_NOT_NONE`` causes the check to fail if *obj* is ``None``.


sipClassName()
--------------

PyObject \*sipClassName(PyObject \*obj)
    This returns the class name of a wrapped instance as a Python string.  It
    comes with a reference.


sipConnectRx()
--------------

PyObject \*sipConnectRx(PyObject \*sender, const char \*signal, PyObject \*receiver, const char \*slot, int type)
    This connects a signal to a signal or slot and returns ``Py_True`` if the
    signal was connected or ``Py_False`` if not.  If there was some other
    error then a Python exception is raised and ``NULL`` is returned.  *sender*
    is the wrapped ``QObject`` derived instance that emits the signal.
    *signal* is the typed name of the signal.  *receiver* is the wrapped
    ``QObject`` derived instance or Python callable that the signal is
    connected to.  *slot* is the typed name of the slot, or ``NULL`` if
    *receiver* is a Python callable.  *type* is the type of connection and is
    cast from Qt::ConnectionType.  It is normally only used by PyQt to
    implement ``QObject.connect()``.


sipConvertFromInstance()
------------------------

PyObject \*sipConvertFromInstance(void \*cpp, sipWrapperType \*type, PyObject \*transferObj)
    Convert a C structure or a C++ class instance to a Python class instance
    object.  *cpp* is the C/C++ instance.  If the instance has already been
    wrapped then the result is a new reference to the existing instance object.
    *type* is the generated type corresponding to the C/C++ type.
    *transferObj* controls the ownership of the returned value.  If the
    structure or class instance has already been wrapped then the result is a
    new reference to the existing class instance object.  If it is ``NULL`` and
    the instance has already been wrapped then the ownership is unchanged.  If
    it is ``NULL`` and the instance is newly wrapped then ownership will be
    with C/C++.  If it is ``Py_None`` then ownership is transferred to Python
    via a call to `sipTransferBack()`_.  Otherwise ownership is transferred to
    C/C++ and the instance associated with *transferObj* via a call to
    `sipTransferTo()`_.  The Python class is influenced by any applicable
    `%ConvertToSubClassCode`_ code.


sipConvertFromMappedType()
--------------------------

PyObject \*sipConvertFromMappedType(void \*cpp, const sipMappedType \*mt, PyObject \*transferObj)
    Convert a C structure or a C++ class instance wrapped as a mapped type to a
    Python object.  *cpp* is the C/C++ instance.  *mt* is the opaque structure
    returned by `sipFindMappedType()`_.  *transferObj* controls any ownership
    changes to *obj*.  If it is ``NULL`` then the ownership is unchanged.  If
    it is ``Py_None`` then ownership is transferred to Python via a call to
    `sipTransferBack()`_.  Otherwise ownership is transferred to C/C++ and the
    instance associated with the ``PyObject *`` argument via a call to
    `sipTransferTo()`_.


sipConvertFromNamedEnum()
-------------------------

PyObject \*sipConvertFromNamedEnum(int eval, PyTypeObject \*type)
    Convert a named C/C++ ``enum`` to an instance of the corresponding Python
    named enum type.  *eval* is the enumerated value to convert.  *type* is the
    generated Python type object (see `Generated Named Enum Type Objects`_).


sipConvertFromNewInstance()
---------------------------

PyObject \*sipConvertFromNewInstance(void \*cpp, sipWrapperType \*type, PyObject \*transferObj)
    Convert a new C structure or a new C++ class instance to a Python class
    instance object.  *cpp* is the C/C++ instance.  *type* is the generated
    type corresponding to the C/C++ type.  *transferObj* controls the ownership
    of the returned value.  If it is ``NULL`` or ``Py_None`` then ownership
    will be with Python.  Otherwise ownership will be with C/C++ and the
    instance associated with *transferObj*.  The Python class is influenced by
    any applicable `%ConvertToSubClassCode`_ code.


sipConvertFromSequenceIndex()
-----------------------------

SIP_SSIZE_T sipConvertFromSequenceIndex(SIP_SSIZE_T idx, SIP_SSIZE_T len)
    This converts a Python sequence index (i.e. where a negative value refers
    to the offset from the end of the sequence) to a C/C++ array index.  If the
    index was out of range then a negative value is returned and a Python
    exception raised.  With versions of Python prior to v2.5 the result and the
    arguments have type ``int``.


sipConvertFromSliceObject()
---------------------------

int sipConvertFromSliceObject(PyObject \*slice, SIP_SSIZE_T length, SIP_SSIZE_T \*start, SIP_SSIZE_T \*stop, SIP_SSIZE_T \*step, SIP_SSIZE_T \*slicelength)
    This is a thin wrapper around the Python ``PySlice_GetIndicesEx()``
    function provided to make it easier to write handwritten code that is
    compatible with SIP v3.x and versions of Python earlier that v2.3.


sipConvertToCpp()
-----------------

void \*sipConvertToCpp(PyObject \*obj, sipWrapperType \*type, int \*iserr)
    This function is deprecated from SIP v4.4.  It is equivalent to::

        sipConvertToInstance(obj, type, NULL, SIP_NO_CONVERTORS, NULL, iserr);


sipConvertToInstance()
----------------------

void \*sipConvertToInstance(PyObject \*obj, sipWrapperType \*type, PyObject \*transferObj, int flags, int \*state, int \*iserr)
    This converts a Python object to an instance of a C structure or C++ class
    assuming that a previous call to `sipCanConvertToInstance()`_ has been
    successful.  *obj* is the Python object.  *type* is the generated type
    corresponding to the C/C++ type returned.  It may be any class in the
    object's class hierarchy.  *transferObj* controls any ownership changes to
    *obj*.  If it is ``NULL`` then the ownership is unchanged.  If it is
    ``Py_None`` then ownership is transferred to Python via a call to
    `sipTransferBack()`_.  Otherwise ownership is transferred to C/C++ and
    *obj* associated with *transferObj* via a call to `sipTransferTo()`_.
    *flags* is any combination of the following values used to fine tune the
    check.

        - ``SIP_NOT_NONE`` causes the check to fail if *obj* is ``None``.

        - ``SIP_NO_CONVERTORS`` suppresses the use of of any
          `%ConvertToTypeCode`_ for *type*.

    If *state* is not ``NULL`` then the location it points to is set to
    describe the state of the returned C/C++ instance and is the value returned
    by any `%ConvertToTypeCode`_.  The calling code must then release the value
    at some point to prevent a memory leak by calling `sipReleaseInstance()`_.
    If there is an error then the location *iserr* points to is set to a
    non-zero value.  If it was initially a non-zero value then the conversion
    isn't attempted in the first place.  (This allows several calls to be made
    that share the same error flag so that it only needs to be tested once
    rather than after each call.)


sipConvertToMappedType()
------------------------

void \*sipConvertToMappedType(PyObject \*obj, const sipMappedType \*mt, PyObject \*transferObj, int flags, int \*state, int \*iserr)
    This converts a Python object to an instance of a C structure or C++
    class that is implemented as a mapped type assuming that a previous call to
    `sipCanConvertToMappedType()`_ has been successful.  *obj* is the Python
    object.  *mt* is the opaque structure returned by `sipFindMappedType()`_.
    *transferObj* controls any ownership changes to *obj*.  If it is ``NULL``
    then the ownership is unchanged.  If it is ``Py_None`` then ownership is
    transferred to Python via a call to `sipTransferBack()`_.  Otherwise
    ownership is transferred to C/C++ and *obj* associated with *transferObj*
    via a call to `sipTransferTo()`_.  *flags* is any combination of the
    following values used to fine tune the check.

        - ``SIP_NOT_NONE`` causes the check to fail if *obj* is ``None``.

    If *state* is not ``NULL`` then the location it points to is set to
    describe the state of the returned C/C++ instance and is the value returned
    by any `%ConvertToTypeCode`_.  The calling code must then release the value
    at some point to prevent a memory leak by calling
    `sipReleaseMappedType()`_.  If there is an error then the location *iserr*
    points to is set to a non-zero value.  If it was initially a non-zero value
    then the conversion isn't attempted in the first place.  (This allows
    several calls to be made that share the same error flag so that it only
    needs to be tested once rather than after each call.)


sipDisconnectRx()
-----------------

PyObject \*sipDisconnectRx(PyObject \*sender, const char \*signal, PyObject \*receiver, const char \*slot)
    This disconnects a signal from a signal or slot and returns ``Py_True`` if
    the signal was disconnected or ``Py_False`` if not.  If there was some
    other error then a Python exception is raised and ``NULL`` is returned.
    *sender* is the wrapped ``QObject`` derived instance that emits the signal.
    *signal* is the typed name of the signal.  *receiver* is the wrapped
    ``QObject`` derived instance or Python callable that the signal is
    connected to.  *slot* is the typed name of the slot, or ``NULL`` if
    *receiver* is a Python callable.  It is normally only used by PyQt to
    implement ``QObject.disconnect()``.


sipEmitSignal()
---------------

int sipEmitSignal(PyObject \*txobj, const char \*signal, PyObject \*args)
    This emits a signal and returns zero if there was no error.  If there was
    an error then a Python exception is raised and a negative value is
    returned.  *txobj* is the wrapped ``QObject`` derived instance that emits
    the signal.  *signal* is the typed name of the signal.  *args* is a Python
    tuple of the signal arguments.  It is normally only used by PyQt to
    implement ``QObject.emit()``.


sipExportSymbol()
-----------------

int sipExportSymbol(const char \*name, void \*sym)
    Python does not allow extension modules to directly access symbols in
    another extension module.  This exports a symbol, referenced by a name,
    that can subsequently be imported, using `sipImportSymbol()`_, by another
    module.  *name* is the name of the symbol and *sym* is its value.  Zero is
    returned if there was no error.  A negative value is returned if *name* is
    already associated with a symbol or there was some other error.


sipFindClass()
--------------

sipWrapperType \*sipFindClass(const char \*type)
    This returns a pointer to the generated type corresponding to a C/C++ type.
    *type* is the C/C++ declaration of the type.  ``NULL`` is returned if the
    C/C++ type doesn't exist.  The value of the pointer will not change and
    may be saved in a static cache.


sipFindMappedType()
-------------------

const sipMappedType \*sipFindMappedType(const char \*type)
    This returns a pointer to an opaque structure describing a mapped type.
    *type* is the C/C++ declaration of the type.  ``NULL`` is returned if the
    mapped type doesn't exist.  The value of the pointer will not change and
    may be saved in a static cache.


sipFindNamedEnum()
------------------

PyTypeObject \*sipFindNamedEnum(const char \*type)
    This returns a pointer to the generated type corresponding to a named C/C++
    enum.  *type* is the C/C++ declaration of the enum.  ``NULL`` is returned
    if the named C/C++ enum doesn't exist.  The value of the pointer will not
    change and may be saved in a static cache.


sipForceConvertToInstance()
---------------------------

void \*sipForceConvertToInstance(PyObject \*obj, sipWrapperType \*type, PyObject \*transferObj, int flags, int \*state, int \*iserr)
    This converts a Python object to an instance of a C structure or C++ class
    by calling `sipCanConvertToInstance()`_ and, if it is successfull, calling
    `sipConvertToInstance()`_.  See `sipConvertToInstance()`_ for a full
    description of the arguments.


sipForceConvertToMappedType()
-----------------------------

void \*sipForceConvertToMappedType(PyObject \*obj, const sipMappedType \*mt, PyObject \*transferObj, int flags, int \*state, int \*iserr)
    This converts a Python object to an instance of a C structure or C++ class
    which has been implemented as a mapped type by calling
    `sipCanConvertToMappedType()`_ and, if it is successfull, calling
    `sipConvertToMappedType()`_.  See `sipConvertToMappedType()`_ for a full
    description of the arguments.


sipFree()
---------

void sipFree(void \*mem)
    This returns an area of memory allocated by `sipMalloc()`_ to the heap.
    *mem* is a pointer to the area of memory.


sipGetSender()
--------------

const void \*sipGetSender()
    This returns a pointer to the last ``QObject`` instance that emitted a Qt
    signal.  It is normally only used by PyQt to implement
    ``QObject.sender()``.


sipGetWrapper()
---------------

PyObject \*sipGetWrapper(void \*cppptr, sipWrapperType \*type)
    This returns a borrowed reference to the wrapped instance object for a C
    structure or C++ class instance.  If the structure or class instance
    hasn't been wrapped then ``NULL`` is returned (and no Python exception is
    raised).  *cppptr* is the pointer to the structure or class instance.
    *type* is the generated type corresponding to the C/C++ type.


sipImportSymbol()
-----------------

void \*sipImportSymbol(const char \*name)
    Python does not allow extension modules to directly access symbols in
    another extension module.  This imports a symbol, referenced by a name,
    that has previously been exported, using `sipExportSymbol()`_, by another
    module.  *name* is the name of the symbol.  The value of the symbol is
    returned if there was no error.  ``NULL`` is returned if there is no such
    symbol.


sipIntTypeClassMap
------------------

This C structure is used with `sipMapIntToClass()`_ to define a mapping
between integer based RTTI and `generated type objects`_.  The structure
elements are as follows.

int typeInt
    The integer RTTI.

sipWrapperType \*\*pyType.
    A pointer to the corresponding Python type object.


sipIsSubClassInstance()
-----------------------

int sipIsSubClassInstance(PyObject \*obj, sipWrapperType \*type)
    This function is deprecated from SIP v4.4.  It is equivalent to::

        sipCanConvertToInstance(obj, type, SIP_NOT_NONE | SIP_NO_CONVERTORS);


sipLong_AsUnsignedLong()
------------------------

unsigned long sipLong_AsUnsignedLong(PyObject \*obj)
    This function is a thin wrapper around PyLong_AsUnsignedLong() that works
    around a bug in Python v2.3.x and earlier when converting integer objects.


sipMalloc()
-----------

void \*sipMalloc(size_t nbytes)
    This allocates an area of memory of size *nytes* on the heap using the
    Python ``PyMem_Malloc()`` function.  If there was an error then ``NULL`` is
    returned and a Python exception raised.  See `sipFree()`_.


sipMapIntToClass()
------------------

sipWrapperType \*sipMapIntToClass(int type, const sipIntTypeClassMap \*map, int maplen)
    This is used in `%ConvertToSubClassCode`_ code as a convenient way of
    converting integer based RTTI to the corresponding Python type object.
    *type* is the RTTI.  *map* is the table of known RTTI and the corresponding
    type objects (see sipIntTypeClassMap_).  The entries in the table must be
    sorted in ascending order of RTTI.  *maplen* is the number of entries in
    the table.  The corresponding Python type object is returned, or ``NULL``
    if *type* wasn't in *map*.


sipMapStringToClass()
---------------------

sipWrapperType \*sipMapStringToClass(char \*type, const sipStringTypeClassMap \*map, int maplen)
    This is used in `%ConvertToSubClassCode`_ code as a convenient way of
    converting ``'\0'`` terminated string based RTTI to the corresponding
    Python type object.  *type* is the RTTI.  *map* is the table of known RTTI
    and the corresponding type objects (see sipStringTypeClassMap_).  The
    entries in the table must be sorted in ascending order of RTTI.  *maplen*
    is the number of entries in the table.  The corresponding Python type
    object is returned, or ``NULL`` if *type* wasn't in *map*.


sipParseResult()
----------------

int sipParseResult(int \*iserr, PyObject \*method, PyObject \*result, const char \*format, ...)
    This converts a Python object (usually returned by a method) to C/C++ based
    on a format string and associated values in a similar way to the Python
    ``PyArg_ParseTuple()`` function.  If there was an error then a negative
    value is returned and a Python exception is raised.  If *iserr* is not
    ``NULL`` then the location it points to is set to a non-zero value.
    *method* is the Python bound method that returned the *result* object.
    *format* is the string of format characters.

    This is normally called by handwritten code specified with the
    `%VirtualCatcherCode`_ directive with *method* being the supplied
    ``sipMethod`` and ``result`` being the value returned by
    `sipCallMethod()`_.

    If *format* begins and ends with parentheses then *result* must be a Python
    tuple and the rest of *format* is applied to the tuple contents.

    In the following description the first letter is the format character, the
    entry in parentheses is the Python object type that the format character
    will convert, and the entry in brackets are the types of the C/C++ values
    to be passed. 

    ``a`` (string) [char \*\*, int \*]
        Convert a Python string to a C/C++ character array and its length.  If
        the Python object is ``Py_None`` then the array and length are ``NULL``
        and zero respectively.

    ``b`` (integer) [bool \*]
        Convert a Python integer to a C/C++ ``bool``.

    ``c`` (string) [char \*]
        Convert a Python string of length 1 to a C/C++ ``char``.

    ``d`` (float) [double \*]
        Convert a Python floating point number to a C/C++ ``double``.

    ``e`` (integer) [enum \*]
        Convert a Python integer to an anonymous C/C++ ``enum``.

    ``f`` (float) [float \*]
        Convert a Python floating point number to a C/C++ ``float``.

    ``h`` (integer) [short \*]
        Convert a Python integer to a C/C++ ``short``.

    ``i`` (integer) [int \*]
        Convert a Python integer to a C/C++ ``int``.

    ``l`` (long) [long \*]
        Convert a Python long to a C/C++ ``long``.

    ``m`` (long) [unsigned long \*]
        Convert a Python long to a C/C++ ``unsigned long``.

    ``n`` (long) [long long \*]
        Convert a Python long to a C/C++ ``long long``.

    ``o`` (long) [unsigned long long \*]
        Convert a Python long to a C/C++ ``unsigned long long``.

    ``s`` (string) [char \*\*]
        Convert a Python string to a C/C++ ``'\0'`` terminated string.  If the
        Python object is ``Py_None`` then the string is ``NULL``.

    ``t`` (long) [unsigned short \*]
        Convert a Python long to a C/C++ ``unsigned short``.

    ``u`` (long) [unsigned int \*]
        Convert a Python long to a C/C++ ``unsigned int``.

    ``w`` (unicode) [wchar_t \*]
        Convert a Python unicode object of length 1 to a C/C++ wide character.

    ``x`` (unicode) [wchar_t \*\*]
        Convert a Python unicode object to a C/C++ ``L'\0'`` terminated wide
        character string.  If the Python object is ``Py_None`` then the string
        is ``NULL``.

    ``A`` (unicode) [wchar_t \*\*, int \*]
        Convert a Python unicode object to a C/C++ wide character array and its
        length.  If the Python object is ``Py_None`` then the array and length
        are ``NULL`` and zero respectively.

    ``Cf`` (wrapped class) [sipWrapperType \*, int \*, void \*\*]
        Convert a Python object to a C structure or a C++ class instance and
        return its state as described in `sipConvertToInstance()`_.  ``f`` is a
        combination of the following flags encoded as an ASCII character by
        adding ``0`` to the combined value:

            0x01 disallows the conversion of ``Py_None`` to ``NULL``

            0x02 implements the `Factory`_ annotation

            0x04 suppresses the return of the state of the returned C/C++
                 instance.  Note that the ``int *`` used to return the state is
                 not passed if this flag is specified.

    ``Df`` (mapped type) [const sipMappedType \*, int \*, void \*\*]
        Convert a Python object to a C structure or a C++ class instance
        implemented as a mapped type and return its state as described in
        `sipConvertToMappedType()`_.  ``f`` is a combination of the following
        flags encoded as an ASCII character by adding ``0`` to the combined
        value:

            0x01 disallows the conversion of ``Py_None`` to ``NULL``

            0x02 implements the `Factory`_ annotation

            0x04 suppresses the return of the state of the returned C/C++
                 instance.  Note that the ``int *`` used to return the state is
                 not passed if this flag is specified.

    ``E`` (wrapped enum) [PyTypeObject \*, enum \*]
        Convert a Python named enum type to the corresponding C/C++ ``enum``.

    ``L`` (object) [*type* \*(\*)(PyObject \*obj, int \*iserr), void \*\*]
        Convert a Python object to a C structure or a C++ class instance using
        a convertor function.  See `Generated Type Convertors`_.  This is
        deprecated from SIP v4.4.

    ``M`` (object) [*type* \*(\*)(PyObject \*obj, int \*iserr), void \*\*]
        Convert a Python object to a C structure or a C++ class instance using
        a convertor function.  If the structure or class instance pointer is
        ``NULL`` then return an error.  See `Generated Type Convertors`_.  This
        is deprecated from SIP v4.4.

    ``N`` (object) [PyTypeObject \*, PyObject \*\*]
        A Python object is checked to see if it is a certain type and then
        returned without any conversions.  The reference count is incremented.
        The Python object may be ``Py_None``.

    ``O`` (object) [PyObject \*\*]
        A Python object is returned without any conversions.  The reference
        count is incremented.

    ``T`` (object) [PyTypeObject \*, PyObject \*\*]
        A Python object is checked to see if it is a certain type and then
        returned without any conversions.  The reference count is incremented.
        The Python object may not be ``Py_None``.

    ``V`` (sip.voidptr) [void \*]
        Convert a Python ``sip.voidptr`` object to a C/C++ ``void *``.

    ``Z`` (object) []
        Check that a Python object is ``Py_None``.  No value is returned.


sipReleaseInstance()
--------------------

void sipReleaseInstance(void \*cpp, sipWrapperType \*type, int state)
    This destroys a wrapped C/C++ instance if it was a temporary instance.  It
    is called after a call to either `sipConvertToInstance()`_ or
    `sipForceConvertToInstance()`_.  *cpp* is the wrapped C/C++ instance.
    *type* is the generated type corresponding to *cpp*.  *state* describes the
    state of the instance.


sipReleaseMappedType()
----------------------

void sipReleaseMappedType(void \*cpp, const sipMappedType \*mt, int state)
    This destroys a wrapped C/C++ mapped type if it was a temporary instance.
    It is called after a call to either `sipConvertToMappedType()`_ or
    `sipForceConvertToMappedType()`_.  *cpp* is the wrapped C/C++ instance.
    *mt* is the opaque structure returned by `sipFindMappedType()`_.  *state*
    describes the state of the instance.


sipStringTypeClassMap
---------------------

This C structure is used with `sipMapStringToClass()`_ to define a mapping
between ``'\0'`` terminated string based RTTI and `generated type objects`_.
The structure elements are as follows.

char \*typeString
    The ``'\0'`` terminated string RTTI.

sipWrapperType \*\*pyType.
    A pointer to the corresponding Python type object.


sipTransfer()
-------------

void sipTransfer(PyObject \*obj, int tocpp)
    This function is deprecated from SIP v4.3.  If *tocpp* is non-zero then the
    equivalent call is::

        sipTransferTo(obj, obj);

    If *tocpp* is zero then the equivalent call is::

        sipTransferBack(obj);


sipTransferBack()
-----------------

void sipTransferBack(PyObject \*obj)
    This transfers ownership of a Python wrapped instance to Python (see
    `Ownership of Objects`_).  *obj* is the wrapped instance.  In addition,
    any association of the instance with regard to the cyclic garbage
    collector with another instance is removed.


sipTransferTo()
---------------

void sipTransferTo(PyObject \*obj, PyObject \*owner)
    This transfers ownership of a Python wrapped instance to C++ (see
    `Ownership of Objects`_).  *obj* is the wrapped instance.  *owner* is an
    optional wrapped instance that *obj* becomes associated with with regard
    to the cyclic garbage collector.  If *owner* is ``NULL`` then no such
    association is made.  If *owner* is the same value as *obj* then any
    reference cycles involving *obj* can never be detected or broken by the
    cyclic garbage collector.  Responsibility for calling the C++ instance's
    destructor is always transfered to C++.


sipWrapper
----------

This is a C structure that represents a Python wrapped instance.  It is an
extension of the Python ``PyObject`` structure and so may be safely cast to
``PyObject``.  It includes a member called ``user`` which is of type
``PyObject *``.  This can be used for any purpose by handwritten code and will
automatically be garbage collected at the appropriate time.


sipWrapper_Check()
------------------

int sipWrapper_Check(PyObject \*obj)
    This returns a non-zero value if a Python object is a wrapped instance.
    *obj* is the Python object.


sipWrapperType
--------------

This is a C structure that represents a SIP generated type object.  It is an
extension of the Python ``PyTypeObject`` structure (which is itself an
extension of the Python ``PyObject`` structure) and so may be safely cast to
``PyTypeObject`` (and ``PyObject``).


Generated Type Convertors
-------------------------

These functions are deprecated from SIP v4.4.

SIP generates functions for all types being wrapped (including mapped types
defined with the `%MappedType`_ directive) that convert a Python object to the
C structure or C++ class instance.  The name of this convertor is the name of
the structure or class prefixed by ``sipForceConvertTo_``.

void \*sipForceConvertTo_*class*(PyObject \*obj, int \*iserr)
    *obj* is the Python object to convert.  If *obj* is ``NULL`` or the
    location pointed to by *iserr* is non-zero then the conversion is not
    attempted and ``NULL`` is returned.  If there was an error then the
    location pointed to by *iserr* is set to a non-zero value, a Python
    exception is raised, and ``NULL`` is returned.

SIP also generates functions for mapped types that convert a C structure or
C++ class instance to a Python object.  The name of this convertor is the name
of the structure or class prefixed by ``sipConvertFrom_``.

PyObject \*sipConvertFrom_*class*(void \*cppptr)
    *cppptr* is a pointer to the C structure or C++ class instance to convert.
    If there was an error then ``NULL`` is returned and a Python exception
    raised.

The convertor functions of all imported types are available to handwritten
code.


Generated Type Objects
----------------------

SIP generates a type object for each C structure or C++ class being wrapped.
These are sipWrapperType_ structures and are used extensively by the SIP API.

These objects are named with the structure or class name prefixed by
``sipClass_``.  For example, the type object for class ``Klass`` is
``sipClass_Klass``.

The type objects of all imported classes are available to handwritten code.


Generated Named Enum Type Objects
---------------------------------

SIP generates a type object for each named enum being wrapped.  These are
PyTypeObject structures.  (Anonymous enums are wrapped as Python integers.)

These objects are named with the fully qualified enum name (i.e. including any
enclosing scope) prefixed by ``sipEnum_``.  For example, the type object for
enum ``Enum`` defined in class ``Klass`` is ``sipEnum_Klass_Enum``.

The type objects of all imported named enums are available to handwritten code.


Generated Derived Classes
-------------------------

For most C++ classes being wrapped SIP generates a derived class with the same
name prefixed by ``sip``.  For example, the derived class for class ``Klass``
is ``sipKlass``.

If a C++ class doesn't have any virtual or protected methods in it or any of
it's super-class hierarchy, or does not emit any Qt signals, then a derived
class is not generated.

Most of the time handwritten code should ignore the derived classes.  The only
exception is that handwritten constructor code specified using the
`%MethodCode`_ directive should call the derived class's constructor (which
has the same C++ signature) rather then the wrapped class's constructor.


Generated Exception Objects
---------------------------

SIP generates a Python object for each exception defined with the `%Exception_`
directive.

These objects are named with the fully qualified exception name (i.e. including
any enclosing scope) prefixed by ``sipException_``.  For example, the type
object for enum ``Except`` defined in class ``Klass`` is
``sipException_Klass_Except``.

The objects of all imported exceptions are available to handwritten code.


Using the SIP Module in Applications
====================================

The main purpose of the SIP module is to provide functionality common to all
SIP generated bindings.  It is loaded automatically and most of the time you
will completely ignore it.  However, it does expose some functionality that can
be used by applications.

cast(obj, type)
    This does the Python equivalent of casting a C++ instance to one of its
    sub or super-class types.  *obj* is the Python object and *type* is the
    type.  A new Python object is returned that wraps the same C++ instance as
    *obj*, but has the type *type*.

delete(obj)
    For C++ instances this calls the C++ destructor.  For C structures it
    returns the structure's memory to the heap.  *obj* is the Python object.

isdeleted(obj)
    This returns True if the C++ instance or C structure has been destroyed or
    returned to the heap.  *obj* is the Python object.

setdeleted(obj)
    This marks the C++ instance or C structure as having been destroyed or
    returned to the heap so that future references to it raise an exception
    rather than cause a program crash.  Normally SIP handles such things
    automatically, but there are circumstances where this isn't possible.
    *obj* is the Python object.

settracemask(mask)
    If the bindings have been created with SIP's ``-r`` command line option
    then the generated code will produce debugging statements that trace the
    execution of the code.  (It is particularly useful when trying to
    understand the operation of a C++ library's virtual function calls.)

    Debugging statements are generated at the following points:

    - in a C++ virtual function (*mask* is ``0x0001``)
    - in a C++ constructor (*mask* is ``0x0002``)
    - in a C++ destructor (*mask* is ``0x0004``)
    - in a Python type's __init__ method (*mask* is ``0x0008``)
    - in a Python type's __del__ method (*mask* is ``0x0010``)
    - in a Python type's ordinary method (*mask* is ``0x0020``).

    By default the trace mask is zero and all debugging statements are
    disabled.

SIP_VERSION
    This is a Python integer object that represents the SIP version number as
    a 3 part hexadecimal number (e.g. v4.0.0 is represented as ``0x040000``).
    It was first implemented in SIP v4.2.

SIP_VERSION_STR
    This is a Python string object that defines the SIP version number as
    represented as a string.  For development snapshots it will start with
    ``snapshot-``.  It was first implemented in SIP v4.3.

transfer(obj, direction)
    This function is deprecated from SIP v4.3.  If *direction* is non-zero then
    the equivalent call is::

        sip.transferto(obj, None)

    If *direction* is zero then the equivalent call is::

        sip.transferback(obj)

transferback(obj)
    This function is a wrapper around `sipTransferBack()`_.

transferto(obj, owner)
    This function is a wrapper around `sipTransferTo()`_.

unwrapinstance(obj)
    Return the address, as a number, of the wrapped C/C++ structure or class
    instance *obj*.

voidptr
    This is the type object for the type SIP uses to represent a C/C++
    ``void *``.  The type constructor takes a single argument that must either
    be another ``voidptr``, ``None``, a Python CObject, or an integer.  The
    type has the following methods:

    __int__()
        This returns the pointer as an integer.

    __hex__()
        This returns the pointer as a hexadecimal string.

    ascobject()
        This returns the pointer as a Python CObject.

    asstring(nbytes)
        This returns a copy of the first *nbytes* of memory at the pointer as a
        Python string.

wrapinstance(addr, type)
    A C/C++ structure or class instance is wrapped and the Python object
    created is returned.  If the instance has already been wrapped then a new
    reference to the existing object is returned.  *addr* is the address of
    the instance represented as a number.  *type* is the type of the object
    (e.g. ``qt.QWidget``).

wrapper
    This is the type object of the base type of all instances wrapped by SIP.

wrappertype
    This is the type object of the metatype of the ``wrapper`` type.


The SIP Build System
====================

The purpose of the build system is to make it easy for you to write
configuration scripts in Python for your own bindings.  The build system takes
care of the details of particular combinations of platform and compiler.  It
supports over 50 different platform/compiler combinations.

The build system is implemented as a pure Python module called ``sipconfig``
that contains a number of classes and functions.  Using this module you can
write bespoke configuration scripts (e.g. PyQt's ``configure.py``) or use it
with other Python based build systems (e.g.
`Distutils <http://www.python.org/sigs/distutils-sig/distutils.html>`_ and
`SCons <http://www.scons.org>`_).

An important feature of SIP is the ability to generate bindings that are built
on top of existing bindings.  For example, both
`PyKDE <http://www.riverbankcomputing.co.uk/pykde/>`_ and
`PyQwt <http://pyqwt.sourceforge.net/>`_ are built on top of PyQt but all three
packages are maintained by different developers.  To make this easier PyQt
includes its own configuration module, ``pyqtconfig``, that contains additional
classes intended to be used by the configuration scripts of bindings built on
top of PyQt.  The SIP build system includes facilities that do a lot of the
work of creating these additional configuration modules.


``sipconfig`` Functions
-----------------------

create_config_module(module, template, content, macros=None)
    This creates a configuration module (e.g. ``pyqtconfig``) from a template
    file and a string.

    ``module`` is the name of the configuration module file to create.

    ``template`` is the name of the template file.

    ``content`` is a string which replaces every occurence of the pattern
    ``@SIP_CONFIGURATION@`` in the template file.  The content string is
    usually created from a Python dictionary using
    ``sipconfig.create_content()``.  ``content`` may also be a dictionary, in
    which case ``sipconfig.create_content()`` is automatically called to
    convert it to a string.

    ``macros`` is an optional dictionary of platform specific build macros.  It
    is only used if ``sipconfig.create_content()`` is called automatically to
    convert a ``content`` dictionary to a string.

create_content(dict, macros=None)
    This converts a Python dictionary to a string that can be parsed by the
    Python interpreter and converted back to an equivalent dictionary.  It is
    typically used to generate the content string for
    ``sipconfig.create_config_module()``.

    ``dict`` is the Python dictionary to convert.

    ``macros`` is the optional dictionary of platform specific build macros.

    Returns the dictionary as a string.

create_wrapper(script, wrapper, gui=0)
    This creates a platform dependent executable wrapper around a Python
    script.

    ``script`` is the full pathname of the script.

    ``wrapper`` is the pathname of the wrapper to create.

    ``gui`` is non-zero if a GUI enabled version of the interpreter should be
    used on platforms that require it.

    Returns the platform specific name of the wrapper.

error(msg)
    This displays an error message on ``stderr`` and calls ``sys.exit()`` with
    a value of 1.

    ``msg`` is the text of the message and should not include any newline
    characters.

format(msg, leftmargin=0, rightmargin=78)
    This formats a message by inserting newline characters at appropriate
    places.

    ``msg`` is the text of the message and should not include any newline
    characters.

    ``leftmargin`` is the optional position of the left margin.

    ``rightmargin`` is the optional position of the right margin.

inform(msg)
    This displays an information message on ``stdout``.

    ``msg`` is the text of the message and should not include any newline
    characters.

parse_build_macros(filename, names, overrides=None, properties=None)
    This parses a qmake compatible file of build system macros and converts it
    to a dictionary.  A macro is a name/value pair.  The dictionary is returned
    or None if any of the overrides was invalid.

    ``filename`` is the name of the file to parse.

    ``names`` is a list of the macro names to extract from the file.

    ``overrides`` is an optional list of macro names and values that modify
    those found in the file.  They are of the form *name=value* (in which case
    the value replaces the value found in the file) or *name+=value* (in which
    case the value is appended to the value found in the file).

    ``properties`` is an optional dictionary of property name and values that
    are used to resolve any expressions of the form ``$[name]`` in the file.

read_version(filename, description, numdefine=None, strdefine=None)
    This extracts version information for a package from a file, usually a C or
    C++ header file.  The version information must each be specified as a
    ``#define`` of a numeric (hexadecimal or decimal) value and/or a string
    value.

    ``filename`` is the name of the file to read.

    ``description`` is a descriptive name of the package used in error
    messages.

    ``numdefine`` is the optional name of the ``#define`` of the version as a
    number.  If it is ``None`` then the numeric version is ignored.

    ``strdefine`` is the optional name of the ``#define`` of the version as a
    string.  If it is ``None`` then the string version is ignored.

    Returns a tuple of the numeric and string versions.  ``sipconfig.error()``
    is called if either were required but could not be found.

version_to_sip_tag(version, tags, description)
    This converts a version number to a SIP version tag.  SIP uses the
    `%Timeline`_ directive to define the chronology of the different versions
    of the C/C++ library being wrapped.  Typically it is not necessary to
    define a version tag for every version of the library, but only for those
    versions that affect the library's API as SIP sees it.

    ``version`` is the numeric version number of the C/C++ library being
    wrapped.  If it is negative then the latest version is assumed.  (This is
    typically useful if a snapshot is indicated by a negative version number.)

    ``tags`` is the dictionary of SIP version tags keyed by the corresponding
    C/C++ library version number.  The tag used is the one with the smallest
    key (i.e. earliest version) that is greater than ``version``.

    ``description`` is a descriptive name of the C/C++ library used in error
    messages.

    Returns the SIP version tag.  ``sipconfig.error()`` is called if the C/C++
    library version number did not correspond to a SIP version tag.

version_to_string(v)
    This converts a 3 part version number encoded as a hexadecimal value to a
    string.

    ``v`` is the version number.

    Returns a string.


``sipconfig`` Classes
---------------------

Configuration
    This class encapsulates configuration values that can be accessed as
    instance objects.  A sub-class may provide a dictionary of additional
    configuration values in its constructor the elements of which will have
    precedence over the super-class's values.

    The following configuration values are provided:

        default_bin_dir
            The name of the directory where executables should be installed by
            default.

        default_mod_dir
            The name of the directory where SIP generated modules should be
            installed by default.

        default_sip_dir
            The name of the base directory where the ``.sip`` files for SIP
            generated modules should be installed by default.  A sub-directory
            with the same name as the module should be created and its ``.sip``
            files should be installed in the sub-directory.  The ``.sip``
            files only need to be installed if you might want to build other
            bindings based on them.

        platform
            The name of the platform/compiler for which the build system has
            been configured for.

        py_conf_inc_dir
            The name of the directory containing the ``pyconfig.h`` header
            file.

        py_inc_dir
            The name of the directory containing the ``Python.h`` header file.

        py_lib_dir
            The name of the directory containing the Python interpreter
            library.

        py_version
            The Python version as a 3 part hexadecimal number (e.g. v2.3.3 is
            represented as ``0x020303``).

        sip_bin
            The full pathname of the SIP executable.

        sip_config_args
            The command line passed to ``configure.py`` when SIP was
            configured.

        sip_inc_dir
            The name of the directory containing the ``sip.h`` header file.

        sip_mod_dir
            The name of the directory containing the SIP module.

        sip_version
            The SIP version as a 3 part hexadecimal number (e.g. v4.0.0 is
            represented as ``0x040000``).

        sip_version_str
            The SIP version as a string.  For development snapshots it will
            start with ``snapshot-``.

        universal
            The name of the MacOS/X SDK used when creating universal binaries.

    __init__(self, sub_cfg=None)
        Initialise the instance.

        ``sub_cfg`` is an optional list of sub-class configurations.  It should
        only be used by the ``__init__()`` method of a sub-class to append its
        own dictionary of configuration values before passing the list to its
        super-class.

    build_macros(self)
        Return the dictionary of platform specific build macros.

    set_build_macros(self, macros)
        Set the dictionary of platform specific build macros to be use when
        generating Makefiles.  Normally there is no need to change the default
        macros.

Makefile
    This class encapsulates a Makefile.  It is intended to be sub-classed to
    generate Makefiles for particular purposes.  It handles all platform and
    compiler specific flags, but allows them to be adjusted to suit the
    requirements of a particular module or program.  These are defined using a
    number of macros which can be accessed as instance objects.

    The following instance objects are provided to help in fine tuning the
    generated Makefile:

        chkdir
            A string that will check for the existence of a directory.

        config
            A reference to the ``configuration`` argument that was passed to
            the constructor.

        console
            A reference to the ``console`` argument that was passed to the
            constructor.

        copy
            A string that will copy a file.

        extra_cflags
            A list of additional flags passed to the C compiler.

        extra_cxxflags
            A list of additional flags passed to the C++ compiler.

        extra_defines
            A list of additional macro names passed to the C/C++ preprocessor.

        extra_include_dirs
            A list of additional include directories passed to the C/C++
            preprocessor.

        extra_lflags
            A list of additional flags passed to the linker.

        extra_lib_dirs
            A list of additional library directories passed to the linker.

        extra_libs
            A list of additional libraries passed to the linker.  The names of
            the libraries must be in platform neutral form (i.e. without any
            platform specific prefixes, version numbers or extensions).

        generator
            A string that defines the platform specific style of Makefile.  The
            only supported values are ``UNIX`` and something else that is not
            ``UNIX``.

        mkdir
            A string that will create a directory.

        rm
            A string that will remove a file.

    __init__(self, configuration, console=0, qt=0, opengl=0, python=0, threaded=0, warnings=None, debug=0, dir=None, makefile="Makefile", installs=None, universal='')
        Initialise the instance.

        ``configuration`` is the current configuration and is an instance of
        the ``Configuration`` class or a sub-class.

        ``console`` is set if the target is a console (rather than GUI) target.
        This only affects Windows and is ignored on other platforms.

        ``qt`` is set if the target uses Qt.  For Qt v4 a list of Qt libraries
        may be specified and a simple non-zero value implies QtCore and QtGui.

        ``opengl`` is set if the target uses OpenGL.

        ``python`` is set if the target uses Python.h.

        ``threaded`` is set if the target requires thread support.  It is set
        automatically if the target uses Qt and Qt has thread support enabled.

        ``warnings`` is set if compiler warning messages should be enabled.
        The default of ``None`` means that warnings are enabled for SIP v4.x
        and disabled for SIP v3.x.

        ``debug`` is set if debugging symbols should be generated.

        ``dir`` is the name of the directory where build files are read from
        and Makefiles are written to.  The default of ``None`` means the
        current directory is used.

        ``makefile`` is the name of the generated Makefile.

        ``installs`` is a list of extra install targets.  Each element is a two
        part list, the first of which is the source and the second is the
        destination.  If the source is another list then it is a list of source
        files and the destination is a directory.

        ``universal`` is the name of the SDK if universal binaries are to be
        created under MacOS/X.

    clean_build_file_objects(self, mfile, build)
        This generates the Makefile commands that will remove any files
        generated during the build of the default target.

        ``mfile`` is the Python file object of the Makefile.

        ``build`` is the dictionary created from parsing the build file.

    finalise(self)
        This is called just before the Makefile is generated to ensure that it
        is fully configured.  It must be reimplemented by a sub-class.

    generate(self)
        This generates the Makefile.

    generate_macros_and_rules(self, mfile)
        This is the default implementation of the Makefile macros and rules
        generation.

        ``mfile`` is the Python file object of the Makefile.

    generate_target_clean(self, mfile)
        This is the default implementation of the Makefile clean target
        generation.

        ``mfile`` is the Python file object of the Makefile.

    generate_target_default(self, mfile)
        This is the default implementation of the Makefile default target
        generation.

        ``mfile`` is the Python file object of the Makefile.

    generate_target_install(self, mfile)
        This is the default implementation of the Makefile install target
        generation.

        ``mfile`` is the Python file object of the Makefile.

    install_file(self, mfile, src, dst, strip=0)
        This generates the Makefile commands to install one or more files to a
        directory.

        ``mfile`` is the Python file object of the Makefile.

        ``src`` is the name of a single file to install or a list of a number
        of files to install.

        ``dst`` is the name of the destination directory.

        ``strip`` is set if the files should be stripped of unneeded symbols
        after having been installed.

    optional_list(self, name)
        This returns an optional Makefile macro as a list.

        ``name`` is the name of the macro.

        Returns the macro as a list.

    optional_string(self, name, default="")
        This returns an optional Makefile macro as a string.

        ``name`` is the name of the macro.

        ``default`` is the optional default value of the macro.

        Returns the macro as a string.

    parse_build_file(self, filename)
        This parses a build file (created with the ``-b`` SIP command line
        option) and converts it to a dictionary.  It can also validate an
        existing dictionary created through other means.

        ``filename`` is the name of the build file, or is a dictionary to be
        validated.  A valid dictionary will contain the name of the target to
        build (excluding any platform specific extension) keyed by ``target``;
        the names of all source files keyed by ``sources``; and, optionally,
        the names of all header files keyed by ``headers``.

        Returns a dictionary corresponding to the parsed build file.

    platform_lib(self, clib, framework=0)
        This converts a library name to a platform specific form.

        ``clib`` is the name of the library in cannonical form.

        ``framework`` is set if the library is implemented as a MacOS
        framework.

        Return the platform specific name.

    ready(self)
        This is called to ensure that the Makefile is fully configured.  It is
        normally called automatically when needed.

    required_string(self, name)
        This returns a required Makefile macro as a string.

        ``name`` is the name of the macro.

        Returns the macro as a string.  An exception is raised if the macro
        does not exist or has an empty value.

ModuleMakefile(Makefile)
    This class encapsulates a Makefile to build a generic Python extension
    module.

    __init__(self, configuration, build_file, install_dir=None, static=0, console=0, opengl=0, threaded=0, warnings=None, debug=0, dir=None, makefile="Makefile", installs=None, strip=1, export_all=0, universal='')
        Initialise the instance.

        ``configuration`` - see ``sipconfig.Makefile.__init__()``.

        ``build_file`` is the name of the build file.  Build files are
        generated using the ``-b`` SIP command line option.

        ``install_dir`` is the name of the directory where the module will be
        optionally installed.

        ``static`` is set if the module should be built as a static library
        (see `Builtin Modules and Custom Interpreters`_).

        ``console`` - see ``sipconfig.Makefile.__init__()``.

        ``qt`` - see ``sipconfig.Makefile.__init__()``.

        ``opengl`` - see ``sipconfig.Makefile.__init__()``.

        ``threaded`` - see ``sipconfig.Makefile.__init__()``.

        ``warnings`` - see ``sipconfig.Makefile.__init__()``.

        ``debug`` - see ``sipconfig.Makefile.__init__()``.

        ``dir`` - see ``sipconfig.Makefile.__init__()``.

        ``makefile`` - see ``sipconfig.Makefile.__init__()``.

        ``installs`` - see ``sipconfig.Makefile.__init__()``.

        ``strip`` is set if the module should be stripped of unneeded symbols
        after installation.  It is ignored if either ``debug`` or ``static`` is
        set, or if the platform doesn't support it.

        ``export_all`` is set if all of the module's symbols should be exported
        rather than just the module's initialisation function.  Exporting all
        symbols increases the size of the module and slows down module load
        times but may avoid problems with modules that use C++ exceptions.  All
        symbols are exported if either ``debug`` or ``static`` is set, or if
        the platform doesn't support it.

    finalise(self)
        This is a reimplementation of ``sipconfig.Makefile.finalise()``.

    generate_macros_and_rules(self, mfile)
        This is a reimplementation of
        ``sipconfig.Makefile.generate_macros_and_rules()``.

    generate_target_clean(self, mfile)
        This is a reimplementation of
        ``sipconfig.Makefile.generate_target_clean()``.

    generate_target_default(self, mfile)
        This is a reimplementation of
        ``sipconfig.Makefile.generate_target_default()``.

    generate_target_install(self, mfile)
        This is a reimplementation of
        ``sipconfig.Makefile.generate_target_install()``.

    module_as_lib(self, mname)
        This returns the name of a SIP v3.x module for when it is used as a
        library to be linked against.  An exception will be raised if it is
        used with SIP v4.x modules.

        ``mname`` is the name of the module.

        Returns the corresponding library name.

ParentMakefile(Makefile)
    This class encapsulates a Makefile that sits above a number of other
    Makefiles in sub-directories.

    __init__(self, configuration, subdirs, dir=None, makefile="Makefile", installs=None)
        Initialise the instance.

        ``configuration`` - see ``sipconfig.Makefile.__init__()``.

        ``subdirs`` is the sequence of sub-directories.

        ``dir`` - see ``sipconfig.Makefile.__init__()``.

        ``makefile`` - see ``sipconfig.Makefile.__init__()``.

        ``installs`` - see ``sipconfig.Makefile.__init__()``.

    generate_macros_and_rules(self, mfile)
        This is a reimplementation of
        ``sipconfig.Makefile.generate_macros_and_rules()``.

    generate_target_clean(self, mfile)
        This is a reimplementation of
        ``sipconfig.Makefile.generate_target_clean()``.

    generate_target_default(self, mfile)
        This is a reimplementation of
        ``sipconfig.Makefile.generate_target_default()``.

    generate_target_install(self, mfile)
        This is a reimplementation of
        ``sipconfig.Makefile.generate_target_install()``.

ProgramMakefile(Makefile)
    This class encapsulates a Makefile to build an executable program.

    __init__(self, configuration, build_file=None, install_dir=None, console=0, qt=0, opengl=0, python=0, threaded=0, warnings=None, debug=0, dir=None, makefile="Makefile", installs=None, universal='')
        Initialise the instance.

        ``configuration`` - see ``sipconfig.Makefile.__init__()``.

        ``build_file`` is the name of the optional build file.  Build files are
        generated using the ``-b`` SIP command line option.

        ``install_dir`` is the name of the directory where the executable
        program will be optionally installed.

        ``console`` - see ``sipconfig.Makefile.__init__()``.

        ``qt`` - see ``sipconfig.Makefile.__init__()``.

        ``opengl`` - see ``sipconfig.Makefile.__init__()``.

        ``python`` - see ``sipconfig.Makefile.__init__()``.

        ``threaded`` - see ``sipconfig.Makefile.__init__()``.

        ``warnings`` - see ``sipconfig.Makefile.__init__()``.

        ``debug`` - see ``sipconfig.Makefile.__init__()``.

        ``dir`` - see ``sipconfig.Makefile.__init__()``.

        ``makefile`` - see ``sipconfig.Makefile.__init__()``.

        ``installs`` - see ``sipconfig.Makefile.__init__()``.

    build_command(self, source)
        This creates a single command line that will create an executable
        program from a single source file.

        ``source`` is the name of the source file.

        Returns a tuple of the name of the executable that will be created and
        the command line.

    finalise(self)
        This is a reimplementation of ``sipconfig.Makefile.finalise()``.

    generate_macros_and_rules(self, mfile)
        This is a reimplementation of
        ``sipconfig.Makefile.generate_macros_and_rules()``.

    generate_target_clean(self, mfile)
        This is a reimplementation of
        ``sipconfig.Makefile.generate_target_clean()``.

    generate_target_default(self, mfile)
        This is a reimplementation of
        ``sipconfig.Makefile.generate_target_default()``.

    generate_target_install(self, mfile)
        This is a reimplementation of
        ``sipconfig.Makefile.generate_target_install()``.

PythonModuleMakefile(Makefile)
    This class encapsulates a Makefile that installs a pure Python module.

    __init__(self, configuration, dstdir, srcdir=None, dir=None, makefile="Makefile", installs=None)
        Initialise the instance.

        ``configuration`` - see ``sipconfig.Makefile.__init__()``.

        ``dstdir`` is the name of the directory in which the module's Python
        code will be installed.

        ``srcdir`` is the name of the directory (relative to ``dir``)
        containing the module's Python code.  It defaults to the same
        directory.

        ``dir`` - see ``sipconfig.Makefile.__init__()``.

        ``makefile`` - see ``sipconfig.Makefile.__init__()``.

        ``installs`` - see ``sipconfig.Makefile.__init__()``.

    generate_macros_and_rules(self, mfile)
        This is a reimplementation of
        ``sipconfig.Makefile.generate_macros_and_rules()``.

    generate_target_install(self, mfile)
        This is a reimplementation of
        ``sipconfig.Makefile.generate_target_install()``.

SIPModuleMakefile(ModuleMakefile)
    This class encapsulates a Makefile to build a SIP generated Python
    extension module.

    finalise(self)
        This is a reimplementation of ``sipconfig.Makefile.finalise()``.


Building Your Extension with distutils
======================================

To build the example in `A Simple C++ Example`_ using distutils, it is
sufficient to create a standard ``setup.py``, listing ``word.sip`` among the
files to build, and hook-up SIP into distutils::

    from distutils.core import setup, Extension
    import sipdistutils

    setup(
      name = 'word',
      versione = '1.0',
      ext_modules=[
        Extension("word", ["word.sip", "word.cpp"]),
        ],

      cmdclass = {'build_ext': sipdistutils.build_ext}
    )

As we can see, the above is a normal distutils setup script, with just a
special line which is needed so that SIP can see and process ``word.sip``.
Then, running ``setup.py build`` will build our extension module.


Builtin Modules and Custom Interpreters
=======================================

Sometimes you want to create a custom Python interpreter with some modules
built in to the interpreter itself rather than being dynamically loaded.  To
do this the module must be created as a static library and linked with a
custom stub and the normal Python library.

To build the SIP module as a static library you must pass the ``-k`` command
line option to ``configure.py``.  You should then build and install SIP as
normal.  (Note that, because the module is now a static library, you will not
be able to import it.)

To build a module you have created for your own library you must modify your
own configuration script to pass a non-zero value as the ``static`` argument
of the ``__init__()`` method of the ``ModuleMakefile`` class (or any derived
class you have created).  Normally you would make this configurable using a
command line option in the same way that SIP's ``configure.py`` handles it.

The next stage is to create a custom stub and a Makefile.  The SIP distribution
contains a directory called ``custom`` which contains example stubs and a
Python script that will create a correct Makefile.  Note that, if your copy of
SIP was part of a standard Linux distribution, the ``custom`` directory may
not be installed on your system.

The ``custom`` directory contains the following files.  They are provided as
examples - each needs to be modified according to your particular
requirements.

    - ``mkcustom.py`` is a Python script that will create a Makefile which is
      then used to build the custom interpreter.  Comments in the file describe
      how it should be modified.

    - ``custom.c`` is a stub for a custom interpreter on Linux/UNIX.  It
      should also be used for a custom console interpreter on Windows (i.e.
      like ``python.exe``).  Comments in the file describe how it should be
      modified.

    - ``customw.c`` is a stub for a custom GUI interpreter on Windows (i.e.
      like ``pythonw.exe``).  Comments in the file describe how it should be
      modified.

Note that this technique does not restrict how the interpreter can be used.
For example, it still allows users to write their own applications that can
import your builtin modules.  If you want to prevent users from doing that,
perhaps to protect a proprietary API, then take a look at the
`VendorID <http://www.riverbankcomputing.co.uk/vendorid/>`__ package.