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 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>SWIG and Python</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="Python">36 SWIG and Python</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Python_nn2">Overview</a>
<li><a href="#Python_nn3">Preliminaries</a>
<ul>
<li><a href="#Python_nn4">Running SWIG</a>
<li><a href="#Python_nn6">Using distutils</a>
<li><a href="#Python_nn7">Hand compiling a dynamic module</a>
<li><a href="#Python_nn8">Static linking</a>
<li><a href="#Python_nn9">Using your module</a>
<li><a href="#Python_nn10">Compilation of C++ extensions</a>
<li><a href="#Python_nn11">Compiling for 64-bit platforms</a>
<li><a href="#Python_nn12">Building Python Extensions under Windows</a>
</ul>
<li><a href="#Python_nn13">A tour of basic C/C++ wrapping</a>
<ul>
<li><a href="#Python_nn14">Modules</a>
<li><a href="#Python_nn15">Functions</a>
<li><a href="#Python_nn16">Global variables</a>
<li><a href="#Python_nn17">Constants and enums</a>
<li><a href="#Python_nn18">Pointers</a>
<li><a href="#Python_nn19">Structures</a>
<li><a href="#Python_nn20">C++ classes</a>
<li><a href="#Python_nn21">C++ inheritance</a>
<li><a href="#Python_nn22">Pointers, references, values, and arrays</a>
<li><a href="#Python_nn23">C++ overloaded functions</a>
<li><a href="#Python_nn24">C++ operators</a>
<li><a href="#Python_nn25">C++ namespaces</a>
<li><a href="#Python_nn26">C++ templates</a>
<li><a href="#Python_nn27">C++ Smart Pointers</a>
<ul>
<li><a href="#Python_smart_pointers_shared_ptr">The shared_ptr Smart Pointer</a>
<li><a href="#Python_smart_pointers_generic">Generic Smart Pointers</a>
</ul>
<li><a href="#Python_nn27a">C++ reference counted objects</a>
</ul>
<li><a href="#Python_nn28">Further details on the Python class interface</a>
<ul>
<li><a href="#Python_nn29">Proxy classes</a>
<li><a href="#Python_builtin_types">Built-in Types</a>
<ul>
<li><a href="#Python_builtin_limitations">Limitations</a>
<li><a href="#Python_builtin_overloads">Operator overloads and slots -- use them!</a>
</ul>
<li><a href="#Python_nn30">Memory management</a>
<li><a href="#Python_nn31">Python 2.2 and classic classes</a>
</ul>
<li><a href="#Python_directors">Cross language polymorphism</a>
<ul>
<li><a href="#Python_nn33">Enabling directors</a>
<li><a href="#Python_nn34">Director classes</a>
<li><a href="#Python_nn35">Ownership and object destruction</a>
<li><a href="#Python_nn36">Exception unrolling</a>
<li><a href="#Python_nn37">Overhead and code bloat</a>
<li><a href="#Python_nn38">Typemaps</a>
<li><a href="#Python_nn39">Miscellaneous</a>
</ul>
<li><a href="#Python_nn40">Common customization features</a>
<ul>
<li><a href="#Python_nn41">C/C++ helper functions</a>
<li><a href="#Python_nn42">Adding additional Python code</a>
<li><a href="#Python_nn43">Class extension with %extend</a>
<li><a href="#Python_nn44">Exception handling with %exception</a>
</ul>
<li><a href="#Python_nn45">Tips and techniques</a>
<ul>
<li><a href="#Python_nn46">Input and output parameters</a>
<li><a href="#Python_nn47">Simple pointers</a>
<li><a href="#Python_nn48">Unbounded C Arrays</a>
<li><a href="#Python_nn49">String handling</a>
<li><a href="#Python_default_args">Default arguments</a>
</ul>
<li><a href="#Python_nn53">Typemaps</a>
<ul>
<li><a href="#Python_nn54">What is a typemap?</a>
<li><a href="#Python_nn55">Python typemaps</a>
<li><a href="#Python_nn56">Typemap variables</a>
<li><a href="#Python_nn57">Useful Python Functions</a>
</ul>
<li><a href="#Python_nn58">Typemap Examples</a>
<ul>
<li><a href="#Python_nn59">Converting Python list to a char ** </a>
<li><a href="#Python_nn60">Expanding a Python object into multiple arguments</a>
<li><a href="#Python_nn61">Using typemaps to return arguments</a>
<li><a href="#Python_nn62">Mapping Python tuples into small arrays</a>
<li><a href="#Python_nn63">Mapping sequences to C arrays</a>
<li><a href="#Python_nn64">Pointer handling</a>
</ul>
<li><a href="#Python_nn65">Docstring Features</a>
<ul>
<li><a href="#Python_nn66">Module docstring</a>
<li><a href="#Python_nn67">%feature("autodoc")</a>
<ul>
<li><a href="#Python_nn68">%feature("autodoc", "0")</a>
<li><a href="#Python_nn69">%feature("autodoc", "1")</a>
<li><a href="#Python_autodoc2">%feature("autodoc", "2")</a>
<li><a href="#Python_autodoc3">%feature("autodoc", "3")</a>
<li><a href="#Python_nn70">%feature("autodoc", "docstring")</a>
</ul>
<li><a href="#Python_nn71">%feature("docstring")</a>
</ul>
<li><a href="#Python_nn72">Python Packages</a>
<ul>
<li><a href="#Python_modulepackage">Setting the Python package</a>
<li><a href="#Python_absrelimports">Absolute and relative imports</a>
<li><a href="#Python_absimport">Enforcing absolute import semantics</a>
<li><a href="#Python_importfrominit">Importing from __init__.py</a>
<li><a href="#Python_implicit_namespace_packages">Implicit Namespace Packages</a>
<li><a href="#Python_package_search">Searching for the wrapper module</a>
<ul>
<li><a href="#Python_package_search_both_package_modules">Both modules in the same package</a>
<li><a href="#Python_package_search_wrapper_split">Split modules</a>
<li><a href="#Python_package_search_both_global_modules">Both modules are global</a>
<li><a href="#Python_package_search_static">Statically linked C modules</a>
</ul>
</ul>
<li><a href="#Python_python3support">Python 3 Support</a>
<ul>
<li><a href="#Python_nn74">Function annotation</a>
<li><a href="#Python_nn75">Buffer interface</a>
<li><a href="#Python_nn76">Abstract base classes</a>
<li><a href="#Python_nn77">Byte string output conversion</a>
<li><a href="#Python_2_unicode">Python 2 Unicode</a>
</ul>
</ul>
</div>
<!-- INDEX -->
<p>
<b>Caution: This chapter is under repair!</b>
</p>
<p>
This chapter describes SWIG's support of Python. SWIG is compatible
with most recent Python versions including Python 3.0 and Python 2.6,
as well as older versions dating back to Python 2.0. For the best results,
consider using Python 2.3 or newer.
</p>
<p>
This chapter covers most SWIG features, but certain low-level details
are covered in less depth than in earlier chapters. At the
very least, make sure you read the "<a href="SWIG.html#SWIG">SWIG
Basics</a>" chapter.
</p>
<H2><a name="Python_nn2">36.1 Overview</a></H2>
<p>
To build Python extension modules, SWIG uses a layered approach in which
parts of the extension module are defined in C and other parts are
defined in Python. The C layer contains low-level wrappers whereas Python code
is used to define high-level features.
</p>
<p>
This layered approach recognizes the fact that certain aspects of
extension building are better accomplished in each language (instead
of trying to do everything in C or C++). Furthermore, by generating code in both
languages, you get a lot more flexibility since you can enhance the extension
module with support code in either language.
</p>
<p>
In describing the Python interface, this chapter starts by covering the
basics of configuration, compiling, and installing Python modules.
Next, the Python interface to common C and C++ programming features is
described. Advanced customization features such as typemaps are then
described followed by a discussion of low-level implementation
details.
</p>
<H2><a name="Python_nn3">36.2 Preliminaries</a></H2>
<H3><a name="Python_nn4">36.2.1 Running SWIG</a></H3>
<p>
Suppose that you defined a SWIG module such as the following:
</p>
<div class="code">
<pre>
/* File: example.i */
%module example
%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}
int fact(int n);
</pre>
</div>
<p>
The <tt>#define SWIG_FILE_WITH_INIT</tt> line inserts a macro that specifies that the
resulting C file should be built as a python extension, inserting the module
<tt>init</tt> code. This <tt>.i</tt> file wraps the following simple C file:
</p>
<div class="code">
<pre>
/* File: example.c */
#include "example.h"
int fact(int n) {
if (n < 0){ /* This should probably return an error, but this is simpler */
return 0;
}
if (n == 0) {
return 1;
}
else {
/* testing for overflow would be a good idea here */
return n * fact(n-1);
}
}
</pre>
</div>
<p>
With the header file:
</p>
<div class="code">
<pre>
/* File: example.h */
int fact(int n);
</pre>
</div>
<p>
To build a Python module, run SWIG using the <tt>-python</tt> option:
</p>
<div class="shell"><pre>
$ swig -python example.i
</pre></div>
<p>
If building a C++ extension, add the <tt>-c++</tt> option:
</p>
<div class="shell"><pre>
$ swig -c++ -python example.i
</pre></div>
<p>
This creates two different files; a C/C++ source file <tt>example_wrap.c</tt> or
<tt>example_wrap.cxx</tt> and a Python source file <tt>example.py</tt>. The generated C
source file contains the low-level wrappers that need to be compiled and linked with the
rest of your C/C++ application to create an extension module. The Python source file
contains high-level support code. This is the file that you will import to use the module.
</p>
<p>
The name of the wrapper file is derived from the name of the input file. For example, if the
input file is <tt>example.i</tt>, the name of the wrapper file is <tt>example_wrap.c</tt>.
To change this, you can use the <tt>-o</tt> option. The name of the Python file is derived
from the module name specified with <tt>%module</tt>. If the module name is <tt>example</tt>,
then a file <tt>example.py</tt> is created.
</p>
<p>
The following sections have further practical examples and details on
how you might go about compiling and using the generated files.
</p>
<H3><a name="Python_nn6">36.2.2 Using distutils</a></H3>
<p>
The preferred approach to building an extension module for python is to compile it with
distutils, which comes with all recent versions of python
(<a href="https://docs.python.org/library/distutils.html">Distutils Docs</a>).
</p>
<p>
Distutils takes care of making sure that your extension is built with all the correct
flags, headers, etc. for the version of Python it is run with. Distutils will compile your
extension into a shared object file or DLL (<tt>.so</tt> on Linux, <tt>.pyd</tt> on
Windows, etc). In addition, distutils can handle installing your package into
site-packages, if that is desired. A configuration file (conventionally called: <tt>setup.py</tt>)
describes the extension (and related python modules). The distutils will
then generate all the right compiler directives to build it for you.
</p>
<p>
Here is a sample <tt>setup.py</tt> file for the above example:
</p>
<div class="code">
<pre>
#!/usr/bin/env python
"""
setup.py file for SWIG example
"""
from distutils.core import setup, Extension
example_module = Extension('_example',
sources=['example_wrap.c', 'example.c'],
)
setup (name = 'example',
version = '0.1',
author = "SWIG Docs",
description = """Simple swig example from docs""",
ext_modules = [example_module],
py_modules = ["example"],
)
</pre>
</div>
<p>
In this example, the line: <tt>example_module = Extension(....)</tt> creates an Extension
module object, defining the name as <tt>_example</tt>, and using the source code files:
<tt>example_wrap.c</tt>, generated by swig, and <tt>example.c</tt>, your original c
source. The swig (and other python extension modules) tradition is for the compiled
extension to have the name of the python portion, prefixed by an underscore. If the name
of your python module is "<tt>example.py</tt>", then the name of the corresponding object file
will be"<tt>_example.so</tt>"
</p>
<p>
The <tt>setup</tt> call then sets up distutils to build your package, defining
some meta data, and passing in your extension module object.
Once this is saved as <tt>setup.py</tt>, you can build your extension with these commands:
</p>
<div class="shell"><pre>
$ swig -python example.i
$ python setup.py build_ext --inplace
</pre></div>
<p>
And a .so, or .pyd or... will be created for you. It will build a version that matches the
python that you run the command with. Taking apart the command line:
</p>
<ul>
<li> <tt>python</tt> -- the version of python you want to build for
<li> <tt>setup.py</tt> -- the name of your setup script (it can be called anything, but
setup.py is the tradition)
<li> <tt>build_ext</tt> -- telling distutils to build extensions
<li> <tt>--inplace</tt> -- this tells distutils to put the extension lib in the current dir.
Otherwise, it will put it inside a build hierarchy, and you'd have to move it to use it.
</ul>
<p>
The distutils have many other features, consult the python distutils docs for details.
</p>
<p>
This same approach works on all platforms if the appropriate compiler is installed. (it
can even build extensions to the standard Windows Python using MingGW)
</p>
<H3><a name="Python_nn7">36.2.3 Hand compiling a dynamic module</a></H3>
<p>
While the preferred approach to building an extension module is to use the distutils, some
people like to integrate building extensions with a larger build system, and thus may wish
to compile their modules without the distutils. To do this, you need to compile your
program using commands like this (shown for Linux):
</p>
<div class="shell"><pre>
$ swig -python example.i
$ gcc -O2 -fPIC -c example.c
$ gcc -O2 -fPIC -c example_wrap.c -I/usr/local/include/python2.5
$ gcc -shared example.o example_wrap.o -o _example.so
</pre></div>
<p>
The exact commands for doing this vary from platform to platform.
However, SWIG tries to guess the right options when it is installed. Therefore,
you may want to start with one of the examples in the <tt>SWIG/Examples/python</tt>
directory. If that doesn't work, you will need to read the man-pages for
your compiler and linker to get the right set of options. You might also
check the <a href="https://github.com/swig/swig/wiki">SWIG Wiki</a> for
additional information.
</p>
<p>
When linking the module, <b>the name of the output file has to match the name
of the module prefixed by an underscore</b>. If the name of your module is "<tt>example</tt>", then the
name of the corresponding object file should be
"<tt>_example.so</tt>" or "<tt>_examplemodule.so</tt>".
The name of the module is specified using the <tt>%module</tt> directive or the
<tt>-module</tt> command line option.
</p>
<p>
<b>Compatibility Note:</b> In SWIG-1.3.13 and earlier releases, module
names did not include the leading underscore. This is because modules
were normally created as C-only extensions without the extra Python
support file (instead, creating Python code was supported as an optional
feature). This has been changed in SWIG-1.3.14 and is consistent with
other Python extension modules. For example, the <tt>socket</tt>
module actually consists of two files; <tt>socket.py</tt> and
<tt>_socket.so</tt>. Many other built-in Python modules follow a similar convention.
</p>
<H3><a name="Python_nn8">36.2.4 Static linking</a></H3>
<p>
An alternative approach to dynamic linking is to rebuild the Python
interpreter with your extension module added to it. In the past,
this approach was sometimes necessary due to limitations in dynamic loading
support on certain machines. However, the situation has improved greatly
over the last few years and you should not consider this approach
unless there is really no other option.
</p>
<p>
The usual procedure for adding a new module to Python involves finding
the Python source, adding an entry to the <tt>Modules/Setup</tt> file,
and rebuilding the interpreter using the Python Makefile. However,
newer Python versions have changed the build process. You may need to edit
the 'setup.py' file in the Python distribution instead.
</p>
<p>
In earlier versions of SWIG, the <tt>embed.i</tt> library file could be used to
rebuild the interpreter. For example:
</p>
<div class="code"><pre>
%module example
%inline %{
extern int fact(int);
extern int mod(int, int);
extern double My_variable;
%}
%include "embed.i" // Include code for a static version of Python
</pre></div>
<p>
The <tt>embed.i</tt> library file includes supporting code that
contains everything needed to rebuild Python. To rebuild the interpreter,
you simply do something like this:
</p>
<div class="shell"><pre>
$ swig -python -lembed.i example.i
$ gcc example.c example_wrap.c \
-Xlinker -export-dynamic \
-DHAVE_CONFIG_H -I/usr/include/python2.7 \
-I/usr/lib/python2.7/config-x86_64-linux-gnu \
-I/usr/lib/python2.7/config \
-L/usr/lib/python2.7/config -lpython2.7 -lm -ldl \
-o mypython
</pre></div>
<p>
You will need to supply the same libraries that were used to build Python the first
time. This may include system libraries such as <tt>-lsocket</tt>, <tt>-lnsl</tt>,
and <tt>-lpthread</tt>. Assuming this actually works, the new version of Python
should be identical to the default version except that your extension module will be
a built-in part of the interpreter.
</p>
<p>
<b>Comment:</b> In practice, you should probably try to avoid static
linking if possible. Some programmers may be inclined
to use static linking in the interest of getting better performance.
However, the performance gained by static linking tends to be rather
minimal in most situations (and quite frankly not worth the extra
hassle in the opinion of this author).
</p>
<p>
<b>Compatibility note:</b> The <tt>embed.i</tt> library file is
deprecated and has not been actively maintained for many years. Even though it
appears to "work" with Python 2.7, no future support is guaranteed.
If using static linking, you might want to rely on a different approach
(perhaps using distutils).
</p>
<H3><a name="Python_nn9">36.2.5 Using your module</a></H3>
<p>
To use your module, simply use the Python <tt>import</tt> statement. If
all goes well, you will be able to run this:
</p>
<div class="targetlang"><pre>
$ python
>>> import example
>>> example.fact(4)
24
>>>
</pre></div>
<p>
A common error received by first-time users is the following:
</p>
<div class="targetlang">
<pre>
>>> import example
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "example.py", line 2, in ?
import _example
ImportError: No module named _example
</pre>
</div>
<p>
If you get this message, it means that you either forgot to compile the wrapper
code into an extension module or you didn't give the extension module the right
name. Make sure that you compiled the wrappers into a module called <tt>_example.so</tt>. And
don't forget the leading underscore (_).
</p>
<p>
Another possible error is the following:
</p>
<div class="targetlang">
<pre>
>>> import example
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ImportError: dynamic module does not define init function (init_example)
>>>
</pre>
</div>
<p>
This error is almost always caused when a bad name is given to the shared object file.
For example, if you created a file <tt>example.so</tt> instead of <tt>_example.so</tt> you would
get this error. Alternatively, this error could arise if the name of the module is
inconsistent with the module name supplied with the <tt>%module</tt> directive.
Double-check the interface to make sure the module name and the shared object
filename match. Another possible cause of this error is forgetting to link the SWIG-generated
wrapper code with the rest of your application when creating the extension module.
</p>
<p>
Another common error is something similar to the following:
</p>
<div class="targetlang">
<pre>
Traceback (most recent call last):
File "example.py", line 3, in ?
import example
ImportError: ./_example.so: undefined symbol: fact
</pre>
</div>
<p>
This error usually indicates that you forgot to include some object
files or libraries in the linking of the shared library file. Make
sure you compile both the SWIG wrapper file and your original program
into a shared library file. Make sure you pass all of the required libraries
to the linker.
</p>
<p>
Sometimes unresolved symbols occur because a wrapper has been created
for a function that doesn't actually exist in a library. This usually
occurs when a header file includes a declaration for a function that
was never actually implemented or it was removed from a library
without updating the header file. To fix this, you can either edit
the SWIG input file to remove the offending declaration or you can use
the <tt>%ignore</tt> directive to ignore the declaration.
</p>
<p>
Finally, suppose that your extension module is linked with another library like this:
</p>
<div class="shell">
<pre>
$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib <b>-lfoo</b> \
-o _example.so
</pre>
</div>
<p>
If the <tt>foo</tt> library is compiled as a shared library, you might encounter the following
problem when you try to use your module:
</p>
<div class="targetlang">
<pre>
>>> import example
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ImportError: libfoo.so: cannot open shared object file: No such file or directory
>>>
</pre>
</div>
<p>
This error is generated because the dynamic linker can't locate the
<tt>libfoo.so</tt> library. When shared libraries are loaded, the
system normally only checks a few standard locations such as
<tt>/usr/lib</tt> and <tt>/usr/local/lib</tt>. To fix this problem,
there are several things you can do. First, you can recompile your extension
module with extra path information. For example, on Linux you can do this:
</p>
<div class="shell">
<pre>
$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
<b>-Xlinker -rpath /home/beazley/projects/lib </b> \
-o _example.so
</pre>
</div>
<p>
Alternatively, you can set the <tt>LD_LIBRARY_PATH</tt> environment variable to
include the directory with your shared libraries.
If setting <tt>LD_LIBRARY_PATH</tt>, be aware that setting this variable can introduce
a noticeable performance impact on all other applications that you run.
To set it only for Python, you might want to do this instead:
</p>
<div class="shell">
<pre>
$ env LD_LIBRARY_PATH=/home/beazley/projects/lib python
</pre>
</div>
<p>
Finally, you can use a command such as <tt>ldconfig</tt> (Linux) or
<tt>crle</tt> (Solaris) to add additional search paths to the default
system configuration (this requires root access and you will need to
read the man pages).
</p>
<H3><a name="Python_nn10">36.2.6 Compilation of C++ extensions</a></H3>
<p>
Compilation of C++ extensions has traditionally been a tricky problem.
Since the Python interpreter is written in C, you need to take steps to
make sure C++ is properly initialized and that modules are compiled
correctly. This should be a non-issue if you're using distutils, as
it takes care of all that for you. The following is included for
historical reasons, and in case you need to compile on your own.
</p>
<p>
On most machines, C++ extension modules should be linked using the C++
compiler. For example:
</p>
<div class="shell"><pre>
$ swig -c++ -python example.i
$ g++ -O2 -fPIC -c example.cxx
$ g++ -O2 -fPIC -c example_wrap.cxx -I/usr/local/include/python2.5
$ g++ -shared example.o example_wrap.o -o _example.so
</pre></div>
<p>
The -fPIC option tells GCC to generate position-independent code (PIC)
which is required for most architectures (it's not vital on x86, but
still a good idea as it allows code pages from the library to be shared between
processes). Other compilers may need a different option specified instead of
-fPIC.
</p>
<p>
In addition to this, you may need to include additional library
files to make it work. For example, if you are using the Sun C++ compiler on
Solaris, you often need to add an extra library <tt>-lCrun</tt> like this:
</p>
<div class="shell"><pre>
$ swig -c++ -python example.i
$ CC -c example.cxx
$ CC -c example_wrap.cxx -I/usr/local/include/python2.5
$ CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o _example.so -lCrun
</pre></div>
<p>
Of course, the extra libraries to use are completely non-portable---you will
probably need to do some experimentation.
</p>
<p>
Sometimes people have suggested that it is necessary to relink the
Python interpreter using the C++ compiler to make C++ extension modules work.
In the experience of this author, this has never actually appeared to be
necessary. Relinking the interpreter with C++ really only includes the
special run-time libraries described above---as long as you link your extension
modules with these libraries, it should not be necessary to rebuild Python.
</p>
<p>
If you aren't entirely sure about the linking of a C++ extension, you
might look at an existing C++ program. On many Unix machines, the
<tt>ldd</tt> command will list library dependencies. This should give
you some clues about what you might have to include when you link your
extension module. For example:
</p>
<div class="shell">
<pre>
$ ldd swig
libstdc++-libc6.1-1.so.2 => /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
libm.so.6 => /lib/libm.so.6 (0x4005b000)
libc.so.6 => /lib/libc.so.6 (0x40077000)
/lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
</pre>
</div>
<p>
As a final complication, a major weakness of C++ is that it does not
define any sort of standard for binary linking of libraries. This
means that C++ code compiled by different compilers will not link
together properly as libraries nor is the memory layout of classes and
data structures implemented in any kind of portable manner. In a
monolithic C++ program, this problem may be unnoticed. However, in Python, it
is possible for different extension modules to be compiled with
different C++ compilers. As long as these modules are self-contained,
this probably won't matter. However, if these modules start sharing data,
you will need to take steps to avoid segmentation faults and other
erratic program behavior. If working with lots of software components, you
might want to investigate using a more formal standard such as COM.
</p>
<H3><a name="Python_nn11">36.2.7 Compiling for 64-bit platforms</a></H3>
<p>
On platforms that support 64-bit applications (Solaris, Irix, etc.),
special care is required when building extension modules. On these
machines, 64-bit applications are compiled and linked using a different
set of compiler/linker options. In addition, it is not generally possible to mix
32-bit and 64-bit code together in the same application.
</p>
<p>
To utilize 64-bits, the Python executable will need to be recompiled
as a 64-bit application. In addition, all libraries, wrapper code,
and every other part of your application will need to be compiled for
64-bits. If you plan to use other third-party extension modules, they
will also have to be recompiled as 64-bit extensions.
</p>
<p>
If you are wrapping commercial software for which you have no source
code, you will be forced to use the same linking standard as used by
that software. This may prevent the use of 64-bit extensions. It may
also introduce problems on platforms that support more than one
linking standard (e.g., -o32 and -n32 on Irix).
</p>
<p> On the Linux x86_64 platform (Opteron or EM64T), besides of the
required compiler option -fPIC discussed above, you will need to be
careful about the libraries you link with or the library path you
use. In general, a Linux distribution will have two set of libraries,
one for native x86_64 programs (under /usr/lib64), and another for 32
bits compatibility (under /usr/lib). Also, the compiler options -m32
and -m64 allow you to choose the desired binary format for your python
extension.
</p>
<H3><a name="Python_nn12">36.2.8 Building Python Extensions under Windows</a></H3>
<p>
Building a SWIG extension to Python under Windows is roughly similar to
the process used with Unix. Using the distutils, it is essentially
identical. If you have the same version of the MS compiler that Python
was built with (the python2.4 and python2.5 distributed by python.org
are built with Visual Studio 2003), the standard <tt>python setup.py
build</tt> should just work.
</p>
<p>
As of python2.5, the distutils support building extensions with MingGW out
of the box. Following the instruction here:
<a href="http://boodebr.org/main/python/build-windows-extensions">Building
Python extensions for Windows with only free tools</a> should get you started.
</p>
<p>
If you need to build it on your own, the following notes are provided:
</p>
<p>
You will need to create a DLL that can be loaded into the interpreter.
This section briefly describes the use of SWIG with Microsoft Visual
C++. As a starting point, many of SWIG's examples include project
files (.dsp files) for Visual C++ 6. These can be opened by more
recent versions of Visual Studio.
You might want to take a quick look at these examples in addition to
reading this section.
</p>
<p>
In Developer Studio, SWIG should be invoked as a custom build option.
This is usually done as follows:
</p>
<ul>
<li>Open up a new workspace and use the AppWizard to select a DLL
project.
<li>Add both the SWIG interface file (the .i file), any supporting C
files, and the name of the wrapper file that will be created by SWIG
(ie. <tt>example_wrap.c</tt>). Note : If using C++, choose a
different suffix for the wrapper file such as
<tt>example_wrap.cxx</tt>. Don't worry if the wrapper file doesn't
exist yet--Developer Studio keeps a reference to it.
<li>Select the SWIG interface file and go to the settings menu. Under
settings, select the "Custom Build" option.
<li>Enter "SWIG" in the description field.
<li>Enter "<tt>swig -python -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)</tt>" in the "Build command(s) field"
<li>Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>" in the "Output files(s) field".
<li>Next, select the settings for the entire project and go to
"C++:Preprocessor". Add the include directories for your Python
installation under "Additional include directories".
<li>Define the symbol __WIN32__ under preprocessor options.
<li>Finally, select the settings for the entire project and go to
"Link Options". Add the Python library file to your link libraries.
For example "python21.lib". Also, set the name of the output file to
match the name of your Python module, ie. _example.pyd - Note that _example.dll also worked with Python-2.4 and earlier.
<li>Build your project.
</ul>
<p>
If all went well, SWIG will be automatically invoked whenever
you build your project. Any changes made to the interface file will
result in SWIG being automatically executed to produce a new version of
the wrapper file.
</p>
<p>
To run your new Python extension, simply run Python
and use the <tt>import</tt> command as normal. For example :
</p>
<div class="targetlang"><pre>
$ python
>>> import example
>>> print example.fact(4)
24
>>>
</pre></div>
<p>
If you get an <tt>ImportError</tt> exception when importing the module, you may
have forgotten to include additional library files when you built your module.
If you get an access violation or some kind of general protection fault
immediately upon import, you have a more serious problem. This
is often caused by linking your extension module against the wrong
set of Win32 debug or thread libraries. You will have to fiddle around with
the build options of project to try and track this down.
</p>
<p>
A 'Debug' build of the wrappers requires a debug build of the Python interpreter.
This normally requires building the Python interpreter from source, which is not a
job for the feint-hearted. Alternatively you can use the 'Release' build of the
Python interpreter with a 'Debug' build of your wrappers by defining the <tt>SWIG_PYTHON_INTERPRETER_NO_DEBUG</tt>
symbol under the preprocessor options. Or you can ensure this macro is defined at the beginning
of the wrapper code using the following in your interface file, where <tt>_MSC_VER</tt> ensures it is
only used by the Visual Studio compiler:
</p>
<div class="code"><pre>
%begin %{
#ifdef _MSC_VER
#define SWIG_PYTHON_INTERPRETER_NO_DEBUG
#endif
%}
</pre></div>
<p>
Some users have reported success in building extension modules using Cygwin
and other compilers. However, the problem of building usable DLLs with these
compilers tends to be rather problematic. For the latest information,
you may want to consult the <a href="https://github.com/swig/swig/wiki">
SWIG Wiki</a>.
</p>
<H2><a name="Python_nn13">36.3 A tour of basic C/C++ wrapping</a></H2>
<p>
By default, SWIG tries to build a very natural Python interface
to your C/C++ code. Functions are wrapped as functions, classes are wrapped as classes, and so forth.
This section briefly covers the essential aspects of this wrapping.
</p>
<H3><a name="Python_nn14">36.3.1 Modules</a></H3>
<p>
The SWIG <tt>%module</tt> directive specifies the name of the Python
module. If you specify `<tt>%module example</tt>', then everything is
wrapped into a Python '<tt>example</tt>' module. Underneath the covers,
this module consists of a Python source file <tt>example.py</tt> and a low-level
extension module <tt>_example.so</tt>. When choosing a
module name, make sure you don't use the same name as a built-in
Python command or standard module name.
</p>
<H3><a name="Python_nn15">36.3.2 Functions</a></H3>
<p>
Global functions are wrapped as new Python built-in functions. For example,
</p>
<div class="code"><pre>
%module example
int fact(int n);
</pre></div>
<p>
creates a built-in function <tt>example.fact(n)</tt> that works exactly
like you think it does:
</p>
<div class="targetlang"><pre>
>>> import example
>>> print example.fact(4)
24
>>>
</pre></div>
<H3><a name="Python_nn16">36.3.3 Global variables</a></H3>
<p>
C/C++ global variables are fully supported by SWIG. However, the underlying
mechanism is somewhat different than you might expect due to the way that
Python assignment works. When you type the following in Python
</p>
<div class="targetlang"><pre>
a = 3.4
</pre></div>
<p>
"a" becomes a name for an object containing the value 3.4. If you later type
</p>
<div class="targetlang"><pre>
b = a
</pre></div>
<p>
then "a" and "b" are both names for the object containing the value
3.4. Thus, there is only one object containing 3.4 and "a"
and "b" are both names that refer to it. This is quite
different than C where a variable name refers to a memory location in which
a value is stored (and assignment copies data into that location).
Because of this, there is no direct way to map variable
assignment in C to variable assignment in Python.
</p>
<p>
To provide access to C global variables, SWIG creates a special
object called `<tt>cvar</tt>' that is added to each SWIG generated
module. Global variables are then accessed as attributes of this object.
For example, consider this interface
</p>
<div class="code"><pre>
// SWIG interface file with global variables
%module example
...
%inline %{
extern int My_variable;
extern double density;
%}
...
</pre></div>
<p>
Now look at the Python interface:
</p>
<div class="targetlang"><pre>
>>> import example
>>> # Print out value of a C global variable
>>> print example.cvar.My_variable
4
>>> # Set the value of a C global variable
>>> example.cvar.density = 0.8442
>>> # Use in a math operation
>>> example.cvar.density = example.cvar.density*1.10
</pre></div>
<p>
If you make an error in variable assignment, you will receive an
error message. For example:
</p>
<div class="targetlang"><pre>
>>> example.cvar.density = "Hello"
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: C variable 'density (double )'
>>>
</pre></div>
<p>
If a variable is declared as <tt>const</tt>, it is wrapped as a
read-only variable. Attempts to modify its value will result in an
error.
</p>
<p>
To make ordinary variables read-only, you can use the <tt>%immutable</tt> directive. For example:
</p>
<div class="code">
<pre>
%{
extern char *path;
%}
%immutable;
extern char *path;
%mutable;
</pre>
</div>
<p>
The <tt>%immutable</tt> directive stays in effect until it is explicitly disabled or cleared using
<tt>%mutable</tt>.
See the <a href="SWIG.html#SWIG_readonly_variables">Creating read-only variables</a> section for further details.
</p>
<p>
If you just want to make a specific variable immutable, supply a declaration name. For example:
</p>
<div class="code">
<pre>
%{
extern char *path;
%}
%immutable path;
...
extern char *path; // Read-only (due to %immutable)
</pre>
</div>
<p>
If you would like to access variables using a name other than "<tt>cvar</tt>", it can be
changed using the <tt>-globals</tt> option :
</p>
<div class="shell"><pre>
$ swig -python -globals myvar example.i
</pre></div>
<p>
Some care is in order when importing multiple SWIG modules.
If you use the "<tt>from <file> import *</tt>" style of
importing, you will get a name clash on the variable `<tt>cvar</tt>'
and you will only be able to access global variables from the last
module loaded. To prevent this, you might consider renaming
<tt>cvar</tt> or making it private to the module by giving it a name
that starts with a leading underscore. SWIG does not create <tt>cvar</tt>
if there are no global variables in a module.
</p>
<H3><a name="Python_nn17">36.3.4 Constants and enums</a></H3>
<p>
C/C++ constants are installed as Python objects containing the
appropriate value. To create a constant, use <tt>#define</tt>, <tt>enum</tt>, or the
<tt>%constant</tt> directive. For example:
</p>
<div class="code">
<pre>
#define PI 3.14159
#define VERSION "1.0"
enum Beverage { ALE, LAGER, STOUT, PILSNER };
%constant int FOO = 42;
%constant const char *path = "/usr/local";
</pre>
</div>
<p>
For enums, make sure that the definition of the enumeration actually appears in a header
file or in the wrapper file somehow---if you just stick an enum in a SWIG interface without
also telling the C compiler about it, the wrapper code won't compile.
</p>
<p>
Note: declarations declared as <tt>const</tt> are wrapped as read-only variables and
will be accessed using the <tt>cvar</tt> object described in the previous section. They
are not wrapped as constants. For further discussion about this, see the <a href="SWIG.html#SWIG">SWIG Basics</a> chapter.
</p>
<p>
Constants are not guaranteed to remain constant in Python---the name
of the constant could be accidentally reassigned to refer to some
other object. Unfortunately, there is no easy way for SWIG to
generate code that prevents this. You will just have to be careful.
</p>
<p>
By default, swig just emits enum's values as Python integer variables. For example, the
following code
</p>
<div class="code">
<pre>
enum Beverage { ALE, LAGER, STOUT, PILSNER };
</pre>
</div>
<p>will generate Python variables <tt>ALE</tt>, <tt>LAGER</tt>, <tt>STOUT</tt>
and <tt>PILSNER</tt> in module's namespace:</p>
<div class="targetlang">
<pre>
>>> dir()
['ALE', 'LAGER', 'PILSNER', 'STOUT', 'SWIG_PyInstanceMethod_New', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
</pre>
</div>
<p>and they all will be integers:</p>
<div class="targetlang">
<pre>
>>> type(ALE)
<class 'int'>
</pre>
</div>
<p>This "degeneration" of enums to a single (int) type has its implications.
For example, overloaded functions do not work with enums. Consider the
following code, where <tt>print()</tt> is supposed to print enum names:</p>
<div class="code">
<pre>
enum Beverage1 { ALE, LAGER };
enum Beverage2 { STOUT, PILSNER };
void print(Beverage1 x);
void print(Beverage2 x);
%{
#include <stdio.h>
enum Beverage1 { ALE, LAGER };
enum Beverage2 { STOUT, PILSNER };
void print(Beverage1 x) { if(x == ALE) { printf("ALE\n"); } else { printf("LAGER\n"); } }
void print(Beverage2 x) { if(x == STOUT ) { printf("STOUT\n"); } else { printf("PILSNER\n"); } }
%}
</pre>
</div>
<p>A Python wrapper generated for the above code has rather unexpected
behavior:</p>
<div class="targetlang">
<pre>
>>> print(ALE)
ALE
>>> print(STOUT)
ALE
</pre>
</div>
<p>Another issue with enums is scoping. All the enum symbols land by default in
global namespace (or a namespace of embedding class). Name clashes may
occur.</p>
<p>Swig 3.0.5 and later supports strongly typed enums and enum scoping. These
are experimental features. To enable them, you have to include
<tt>enums.swg</tt> module and use <tt>"python:enum"</tt> feature before enums
declarations, for example:</p>
<div class="code">
<pre>
%include <enums.swg>
%feature("python:enum",strong=1);
// ...
</pre>
</div>
<p>With strongly typed enum enabled (by the above directive
<tt>%feature("python:enum",strong=1)</tt>) overloaded functions may be
used</p>
<div class="targetlang">
<pre>
>>> print(ALE)
ALE
>>> print(STOUT)
STOUT
</pre>
</div>
<p>because now the generated enum values have distinguishable types</p>
<div class="targetlang">
<pre>
>>> type(ALE)
<class 'Beverage1'>
>>> type(STOUT)
<class 'Beverage2'>
>>> ALE
<Swig Object of type 'Beverage1 *' at 0x7f8269f8b3e8>
>>> STOUT
<Swig Object of type 'Beverage2 *' at 0x7f8267ff85e0>
</pre>
</div>
<p>The <tt>%feature("python:enum")</tt> may be used to enable either strongly
typed enums, scoped enums or both</p>
<div class="code">
<pre>
%include <enums.swg>
%feature("python:enum",strong=1) Color1;
%feature("python:enum",scoped=1) Color2;
%feature("python:enum",scoped=1, strong=1) Color3;
enum class Color1 : int { RED, GREEN, BLUE };
enum class Color2 : int { CYAN, MAGENTA, YELLOW, BLACK };
enum class Color3 : int { CYAN, MAGENTA, YELLOW, BLACK };
int intval(Color1 x);
int intval(Color3 x);
%{
enum class Color1 : int { RED, GREEN, BLUE };
enum class Color2 : int { CYAN = 20, MAGENTA = 21, YELLOW = 22, BLACK = 23 };
enum class Color3 : int { CYAN = 30, MAGENTA = 31, YELLOW = 32, BLACK = 33 };
int intval(Color1 x) { return static_cast<int>(x); }
int intval(Color3 x) { return static_cast<int>(x); }
%}
</pre>
</div>
<p>A Python wrapper for the above code works as follows</p>
<div class="targetlang">
<pre>
>>> dir()
['BLUE', 'Color1', 'Color2', 'Color3', 'GREEN', 'RED', 'SWIG_PyInstanceMethod_New', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'intval']
>>> intval(BLUE)
2;
>>> Color2.CYAN
20
>>> intval(Color3.CYAN)
30
</pre>
</div>
<p>The <tt>strong</tt> and <tt>scoped</tt> features do not work with anonymous
enums (which is quite obvious -- we need a named C++ type to generate Python
class for enum type and/or scope). Anonymous enums are wrapped in the usual way
(they emit int values to Python).</p>
<p>Another limitation is, that currently there is no "standard" interface to
access enum's value for strongly typed enums. If you need convert strongly
typed enums to integers in Python, wrap your own (global) C++ function for this
purpose (as the <tt>intval</tt> above). </p>
<p>Nesting strong/scoped enums within classes does not work (not implemented).
It is so, because C++ class nesting is not implemented for Python (and we
internally use Python classes to implement strong/scoped enums).</p>
<p>To enable strong/scoped enums globally (for all named enum types), use
<tt>-strongenum</tt> and/or <tt>-scopedenum</tt> swig CLI options. You may also
use <tt>-enumclass</tt> option to enable <tt>strong</tt> and <tt>scoped</tt>
features for all <tt>enum class</tt>es.<p>
<H3><a name="Python_nn18">36.3.5 Pointers</a></H3>
<p>
C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no
problem working with incomplete type information. Here is a rather
simple interface:
</p>
<div class="code">
<pre>
%module example
FILE *fopen(const char *filename, const char *mode);
int fputs(const char *, FILE *);
int fclose(FILE *);
</pre>
</div>
<p>
When wrapped, you will be able to use the functions in a natural way from Python. For example:
</p>
<div class="targetlang">
<pre>
>>> import example
>>> f = example.fopen("junk", "w")
>>> example.fputs("Hello World\n", f)
>>> example.fclose(f)
</pre>
</div>
<p>
If this makes you uneasy, rest assured that there is no
deep magic involved. Underneath the covers, pointers to C/C++ objects are
simply represented as opaque values using an especial python container object:
</p>
<div class="targetlang"><pre>
>>> print f
<Swig Object of type 'FILE *' at 0xb7d6f470>
</pre></div>
<p>
This pointer value can be freely passed around to different C functions that
expect to receive an object of type <tt>FILE *</tt>. The only thing you can't do is
dereference the pointer from Python. Of course, that isn't much of a concern in this example.
</p>
<p>
In older versions of SWIG (1.3.22 or older), pointers were represented
using a plain string object. If you have an old package that still
requires that representation, or you just feel nostalgic, you can
always retrieve it by casting the pointer object to a string:
</p>
<div class="targetlang"><pre>
>>> print str(f)
_c0671108_p_FILE
</pre></div>
<p>
Also, if you need to pass the raw pointer value to some external
python library, you can do it by casting the pointer object to an
integer:
</p>
<div class="targetlang"><pre>
>>> print int(f)
135833352
</pre></div>
<p>
However, the inverse operation is not possible, i.e., you can't build
a SWIG pointer object from a raw integer value.
</p>
<p>
Note also that the '0' or NULL pointer is always represented by
<tt>None</tt>, no matter what type swig is addressing. In the
previous example, you can call:
</p>
<div class="targetlang">
<pre>
>>> example.fclose(None)
</pre>
</div>
<p>
and that will be equivalent to the following, but not really useful, C
code:
</p>
<div class="code">
<pre>
FILE *f = NULL;
fclose(f);
</pre>
</div>
<p>
As much as you might be inclined to modify a pointer value directly
from Python, don't. The hexadecimal encoding is not necessarily the
same as the logical memory address of the underlying object. Instead
it is the raw byte encoding of the pointer value. The encoding will
vary depending on the native byte-ordering of the platform (i.e.,
big-endian vs. little-endian). Similarly, don't try to manually cast
a pointer to a new type by simply replacing the type-string. This may
not work like you expect, it is particularly dangerous when casting
C++ objects. If you need to cast a pointer or change its value,
consider writing some helper functions instead. For example:
</p>
<div class="code">
<pre>
%inline %{
/* C-style cast */
Bar *FooToBar(Foo *f) {
return (Bar *) f;
}
/* C++-style cast */
Foo *BarToFoo(Bar *b) {
return dynamic_cast<Foo*>(b);
}
Foo *IncrFoo(Foo *f, int i) {
return f+i;
}
%}
</pre>
</div>
<p>
Also, if working with C++, you should always try
to use the new C++ style casts. For example, in the above code, the
C-style cast may return a bogus result whereas as the C++-style cast will return
<tt>None</tt> if the conversion can't be performed.
</p>
<H3><a name="Python_nn19">36.3.6 Structures</a></H3>
<p>
If you wrap a C structure, it is wrapped by a Python class. This provides
a very natural interface. For example,
</p>
<div class="code"><pre>
struct Vector {
double x, y, z;
};
</pre></div>
<p>
is used as follows:
</p>
<div class="targetlang"><pre>
>>> v = example.Vector()
>>> v.x = 3.5
>>> v.y = 7.2
>>> print v.x, v.y, v.z
7.8 -4.5 0.0
>>>
</pre></div>
<p>
Similar access is provided for unions and the data members of C++ classes.
</p>
<p>
If you print out the value of <tt>v</tt> in the above example, you will see
something like this:
</p>
<div class="targetlang">
<pre>
>>> print v
<C Vector instance at _18e31408_p_Vector>
</pre>
</div>
<p>
This object is actually a Python instance that has been wrapped around a pointer to the low-level
C structure. This instance doesn't actually do anything--it just serves as a proxy.
The pointer to the C object can be found in the <tt>.this</tt>
attribute. For example:
</p>
<div class="targetlang">
<pre>
>>> print v.this
_18e31408_p_Vector
>>>
</pre>
</div>
<p>
Further details about the Python proxy class are covered a little later.
</p>
<p>
<tt>const</tt> members of a structure are read-only. Data members
can also be forced to be read-only using the <tt>%immutable</tt> directive. For example:
</p>
<div class="code">
<pre>
struct Foo {
...
%immutable;
int x; /* Read-only members */
char *name;
%mutable;
...
};
</pre>
</div>
<p>
When <tt>char *</tt> members of a structure are wrapped, the contents are assumed to be
dynamically allocated using <tt>malloc</tt> or <tt>new</tt> (depending on whether or not
SWIG is run with the -c++ option). When the structure member is set, the old contents will be
released and a new value created. If this is not the behavior you want, you will have to use
a typemap (described later).
</p>
<p>
If a structure contains arrays, access to those arrays is managed through pointers. For
example, consider this:
</p>
<div class="code">
<pre>
struct Bar {
int x[16];
};
</pre>
</div>
<p>
If accessed in Python, you will see behavior like this:
</p>
<div class="targetlang">
<pre>
>>> b = example.Bar()
>>> print b.x
_801861a4_p_int
>>>
</pre>
</div>
<p>
This pointer can be passed around to functions that expect to receive
an <tt>int *</tt> (just like C). You can also set the value of an array member using
another pointer. For example:
</p>
<div class="targetlang">
<pre>
>>> c = example.Bar()
>>> c.x = b.x # Copy contents of b.x to c.x
</pre>
</div>
<p>
For array assignment, SWIG copies the entire contents of the array starting with the data pointed
to by <tt>b.x</tt>. In this example, 16 integers would be copied. Like C, SWIG makes
no assumptions about bounds checking---if you pass a bad pointer, you may get a segmentation
fault or access violation.
</p>
<p>
When a member of a structure is itself a structure, it is handled as a
pointer. For example, suppose you have two structures like this:
</p>
<div class="code">
<pre>
struct Foo {
int a;
};
struct Bar {
Foo f;
};
</pre>
</div>
<p>
Now, suppose that you access the <tt>f</tt> attribute of <tt>Bar</tt> like this:
</p>
<div class="targetlang">
<pre>
>>> b = Bar()
>>> x = b.f
</pre>
</div>
<p>
In this case, <tt>x</tt> is a pointer that points to the <tt>Foo</tt> that is inside <tt>b</tt>.
This is the same value as generated by this C code:
</p>
<div class="code">
<pre>
Bar b;
Foo *x = &b->f; /* Points inside b */
</pre>
</div>
<p>
Because the pointer points inside the structure, you can modify the contents and
everything works just like you would expect. For example:
</p>
<div class="targetlang">
<pre>
>>> b = Bar()
>>> b.f.a = 3 # Modify attribute of structure member
>>> x = b.f
>>> x.a = 3 # Modifies the same structure
</pre>
</div>
<H3><a name="Python_nn20">36.3.7 C++ classes</a></H3>
<p>
C++ classes are wrapped by Python classes as well. For example, if you have this class,
</p>
<div class="code"><pre>
class List {
public:
List();
~List();
int search(char *item);
void insert(char *item);
void remove(char *item);
char *get(int n);
int length;
};
</pre></div>
<p>
you can use it in Python like this:
</p>
<div class="targetlang"><pre>
>>> l = example.List()
>>> l.insert("Ale")
>>> l.insert("Stout")
>>> l.insert("Lager")
>>> l.get(1)
'Stout'
>>> print l.length
3
>>>
</pre></div>
<p>
Class data members are accessed in the same manner as C structures.
</p>
<p>
Static class members present a special problem for Python. Prior to Python-2.2,
Python classes had no support for static methods and no version of Python
supports static member variables in a manner that SWIG can utilize. Therefore,
SWIG generates wrappers that try to work around some of these issues. To illustrate,
suppose you have a class like this:
</p>
<div class="code">
<pre>
class Spam {
public:
static void foo();
static int bar;
};
</pre>
</div>
<p>
In Python, the static member can be access in three different ways:
</p>
<div class="targetlang">
<pre>
>>> example.Spam_foo() # Spam::foo()
>>> s = example.Spam()
>>> s.foo() # Spam::foo() via an instance
>>> example.Spam.foo() # Spam::foo(). Python-2.2 only
</pre>
</div>
<p>
The first two methods of access are supported in all versions of Python. The
last technique is only available in Python-2.2 and later versions.
</p>
<p>
Static member variables are currently accessed as global variables. This means,
they are accessed through <tt>cvar</tt> like this:
</p>
<div class="targetlang">
<pre>
>>> print example.cvar.Spam_bar
7
</pre>
</div>
<H3><a name="Python_nn21">36.3.8 C++ inheritance</a></H3>
<p>
SWIG is fully aware of issues related to C++ inheritance. Therefore, if you have
classes like this
</p>
<div class="code">
<pre>
class Foo {
...
};
class Bar : public Foo {
...
};
</pre>
</div>
<p>
those classes are wrapped into a hierarchy of Python classes that reflect the same inheritance
structure. All of the usual Python utility functions work normally:
</p>
<div class="targetlang">
<pre>
>>> b = Bar()
>>> instance(b, Foo)
1
>>> issubclass(Bar, Foo)
1
>>> issubclass(Foo, Bar)
0
</pre>
</div>
<p>
Furthermore, if you have functions like this
</p>
<div class="code">
<pre>
void spam(Foo *f);
</pre>
</div>
<p>
then the function <tt>spam()</tt> accepts <tt>Foo *</tt> or a pointer to any class derived from <tt>Foo</tt>.
</p>
<p>
It is safe to use multiple inheritance with SWIG.
</p>
<H3><a name="Python_nn22">36.3.9 Pointers, references, values, and arrays</a></H3>
<p>
In C++, there are many different ways a function might receive
and manipulate objects. For example:
</p>
<div class="code">
<pre>
void spam1(Foo *x); // Pass by pointer
void spam2(Foo &x); // Pass by reference
void spam3(const Foo &x);// Pass by const reference
void spam4(Foo x); // Pass by value
void spam5(Foo x[]); // Array of objects
</pre>
</div>
<p>
In Python, there is no detailed distinction like this--specifically,
there are only "objects". There are no pointers, references, arrays,
and so forth. Because of this, SWIG unifies all of these types
together in the wrapper code. For instance, if you actually had the
above functions, it is perfectly legal to do this:
</p>
<div class="targetlang">
<pre>
>>> f = Foo() # Create a Foo
>>> spam1(f) # Ok. Pointer
>>> spam2(f) # Ok. Reference
>>> spam3(f) # Ok. Const reference
>>> spam4(f) # Ok. Value.
>>> spam5(f) # Ok. Array (1 element)
</pre>
</div>
<p>
Similar behavior occurs for return values. For example, if you had
functions like this,
</p>
<div class="code">
<pre>
Foo *spam6();
Foo &spam7();
Foo spam8();
const Foo &spam9();
</pre>
</div>
<p>
then all three functions will return a pointer to some <tt>Foo</tt> object.
Since the third function (spam8) returns a value, newly allocated memory is used
to hold the result and a pointer is returned (Python will release this memory
when the return value is garbage collected). The fourth case (spam9)
which returns a const reference, in most of the cases will be
treated as a returning value, and it will follow the same
allocation/deallocation process.
</p>
<H3><a name="Python_nn23">36.3.10 C++ overloaded functions</a></H3>
<p>
C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example,
if you have two functions like this:
</p>
<div class="code">
<pre>
void foo(int);
void foo(char *c);
</pre>
</div>
<p>
You can use them in Python in a straightforward manner:
</p>
<div class="targetlang">
<pre>
>>> foo(3) # foo(int)
>>> foo("Hello") # foo(char *c)
</pre>
</div>
<p>
Similarly, if you have a class like this,
</p>
<div class="code">
<pre>
class Foo {
public:
Foo();
Foo(const Foo &);
...
};
</pre>
</div>
<p>
you can write Python code like this:
</p>
<div class="targetlang">
<pre>
>>> f = Foo() # Create a Foo
>>> g = Foo(f) # Copy f
</pre>
</div>
<p>
Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG
can't disambiguate. For example:
</p>
<div class="code">
<pre>
void spam(int);
void spam(short);
</pre>
</div>
<p>
or
</p>
<div class="code">
<pre>
void foo(Bar *b);
void foo(Bar &b);
</pre>
</div>
<p>
If declarations such as these appear, you will get a warning message like this:
</p>
<div class="shell">
<pre>
example.i:12: Warning 509: Overloaded method spam(short) effectively ignored,
example.i:11: Warning 509: as it is shadowed by spam(int).
</pre>
</div>
<p>
To fix this, you either need to ignore or rename one of the methods. For example:
</p>
<div class="code">
<pre>
%rename(spam_short) spam(short);
...
void spam(int);
void spam(short); // Accessed as spam_short
</pre>
</div>
<p>
or
</p>
<div class="code">
<pre>
%ignore spam(short);
...
void spam(int);
void spam(short); // Ignored
</pre>
</div>
<p>
SWIG resolves overloaded functions and methods using a disambiguation scheme that ranks and sorts
declarations according to a set of type-precedence rules. The order in which declarations appear
in the input does not matter except in situations where ambiguity arises--in this case, the
first declaration takes precedence.
</p>
<p>
Please refer to the "SWIG and C++" chapter for more information about overloading.
</p>
<H3><a name="Python_nn24">36.3.11 C++ operators</a></H3>
<p>
Certain C++ overloaded operators can be handled automatically by SWIG. For example,
consider a class like this:
</p>
<div class="code">
<pre>
class Complex {
private:
double rpart, ipart;
public:
Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { }
Complex &operator=(const Complex &c);
Complex operator+=(const Complex &c) const;
Complex operator+(const Complex &c) const;
Complex operator-(const Complex &c) const;
Complex operator*(const Complex &c) const;
Complex operator-() const;
double re() const { return rpart; }
double im() const { return ipart; }
};
</pre>
</div>
<p>
When wrapped, it works like you expect:
</p>
<div class="targetlang">
<pre>
>>> c = Complex(3, 4)
>>> d = Complex(7, 8)
>>> e = c + d
>>> e.re()
10.0
>>> e.im()
12.0
>>> c += d
>>> c.re()
10.0
>>> c.im()
12.0
</pre>
</div>
<p>
One restriction with operator overloading support is that SWIG is not
able to fully handle operators that aren't defined as part of the class.
For example, if you had code like this
</p>
<div class="code">
<pre>
class Complex {
...
friend Complex operator+(double, const Complex &c);
...
};
</pre>
</div>
<p>
then SWIG ignores it and issues a warning. You can still wrap the operator,
but you may have to encapsulate it in a special function. For example:
</p>
<div class="code">
<pre>
%rename(Complex_add_dc) operator+(double, const Complex &);
</pre>
</div>
<p>
There are ways to make this operator appear as part of the class using the <tt>%extend</tt> directive.
Keep reading.
</p>
<p>
Also, be aware that certain operators don't map cleanly to Python. For instance,
overloaded assignment operators don't map to Python semantics and will be ignored.
</p>
<H3><a name="Python_nn25">36.3.12 C++ namespaces</a></H3>
<p>
SWIG is aware of C++ namespaces, but namespace names do not appear in
the module nor do namespaces result in a module that is broken up into
submodules or packages. For example, if you have a file like this,
</p>
<div class="code">
<pre>
%module example
namespace foo {
int fact(int n);
struct Vector {
double x, y, z;
};
};
</pre>
</div>
<p>
it works in Python as follows:
</p>
<div class="targetlang">
<pre>
>>> import example
>>> example.fact(3)
6
>>> v = example.Vector()
>>> v.x = 3.4
>>> print v.y
0.0
>>>
</pre>
</div>
<p>
If your program has more than one namespace, name conflicts (if any) can be resolved using <tt>%rename</tt>
For example:
</p>
<div class="code">
<pre>
%rename(Bar_spam) Bar::spam;
namespace Foo {
int spam();
}
namespace Bar {
int spam();
}
</pre>
</div>
<p>
If you have more than one namespace and your want to keep their
symbols separate, consider wrapping them as separate SWIG modules.
For example, make the module name the same as the namespace and create
extension modules for each namespace separately. If your program
utilizes thousands of small deeply nested namespaces each with
identical symbol names, well, then you get what you deserve.
</p>
<H3><a name="Python_nn26">36.3.13 C++ templates</a></H3>
<p>
C++ templates don't present a huge problem for SWIG. However, in order
to create wrappers, you have to tell SWIG to create wrappers for a particular
template instantiation. To do this, you use the <tt>%template</tt> directive.
For example:
</p>
<div class="code">
<pre>
%module example
%{
#include "pair.h"
%}
template<class T1, class T2>
struct pair {
typedef T1 first_type;
typedef T2 second_type;
T1 first;
T2 second;
pair();
pair(const T1&, const T2&);
~pair();
};
%template(pairii) pair<int, int>;
</pre>
</div>
<p>
In Python:
</p>
<div class="targetlang">
<pre>
>>> import example
>>> p = example.pairii(3, 4)
>>> p.first
3
>>> p.second
4
</pre>
</div>
<p>
Obviously, there is more to template wrapping than shown in this example.
More details can be found in the <a href="SWIGPlus.html#SWIGPlus">SWIG and C++</a> chapter.
Some more complicated
examples will appear later.
</p>
<H3><a name="Python_nn27">36.3.14 C++ Smart Pointers</a></H3>
<H4><a name="Python_smart_pointers_shared_ptr">36.3.14.1 The shared_ptr Smart Pointer</a></H4>
<p>
The C++11 standard provides <tt>std::shared_ptr</tt> which was derived from the Boost
implementation, <tt>boost::shared_ptr</tt>.
Both of these are available for Python in the SWIG library and usage is outlined
in the <a href="Library.html#Library_std_shared_ptr">shared_ptr smart pointer</a> library section.
</p>
<H4><a name="Python_smart_pointers_generic">36.3.14.2 Generic Smart Pointers</a></H4>
<p>
In certain C++ programs, it is common to use classes that have been wrapped by
so-called "smart pointers." Generally, this involves the use of a template class
that implements <tt>operator->()</tt> like this:
</p>
<div class="code">
<pre>
template<class T> class SmartPtr {
...
T *operator->();
...
}
</pre>
</div>
<p>
Then, if you have a class like this,
</p>
<div class="code">
<pre>
class Foo {
public:
int x;
int bar();
};
</pre>
</div>
<p>
A smart pointer would be used in C++ as follows:
</p>
<div class="code">
<pre>
SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown)
...
p->x = 3; // Foo::x
int y = p->bar(); // Foo::bar
</pre>
</div>
<p>
To wrap this in Python, simply tell SWIG about the <tt>SmartPtr</tt> class and the low-level
<tt>Foo</tt> object. Make sure you instantiate <tt>SmartPtr</tt> using <tt>%template</tt> if necessary.
For example:
</p>
<div class="code">
<pre>
%module example
...
%template(SmartPtrFoo) SmartPtr<Foo>;
...
</pre>
</div>
<p>
Now, in Python, everything should just "work":
</p>
<div class="targetlang">
<pre>
>>> p = example.CreateFoo() # Create a smart-pointer somehow
>>> p.x = 3 # Foo::x
>>> p.bar() # Foo::bar
</pre>
</div>
<p>
If you ever need to access the underlying pointer returned by <tt>operator->()</tt> itself,
simply use the <tt>__deref__()</tt> method. For example:
</p>
<div class="targetlang">
<pre>
>>> f = p.__deref__() # Returns underlying Foo *
</pre>
</div>
<H3><a name="Python_nn27a">36.3.15 C++ reference counted objects</a></H3>
<p>
The <a href="SWIGPlus.html#SWIGPlus_ref_unref">C++ reference counted objects</a> section contains
Python examples of memory management using referencing counting.
</p>
<H2><a name="Python_nn28">36.4 Further details on the Python class interface</a></H2>
<p>
In the previous section, a high-level view of Python wrapping was
presented. A key component of this wrapping is that structures and
classes are wrapped by Python proxy classes. This provides a very
natural Python interface and allows SWIG to support a number of
advanced features such as operator overloading. However, a number
of low-level details were omitted. This section provides a brief overview
of how the proxy classes work.
</p>
<p><b>New in SWIG version 2.0.4:</b>
The use of Python proxy classes has performance implications that may be
unacceptable for a high-performance library. The new <tt>-builtin</tt>
option instructs SWIG to forego the use of proxy classes, and instead
create wrapped types as new built-in Python types. When this option is used,
the following section ("Proxy classes") does not apply. Details on the use of
the <tt>-builtin</tt> option are in the <a href="#Python_builtin_types">Built-in Types</a>
section.
</p>
<H3><a name="Python_nn29">36.4.1 Proxy classes</a></H3>
<p>
In the <a href="SWIG.html#SWIG">"SWIG basics"</a> and <a href="SWIGPlus.html#SWIGPlus">"SWIG and C++"</a> chapters,
details of low-level structure and class wrapping are described. To summarize those chapters, if you
have a class like this
</p>
<div class="code">
<pre>
class Foo {
public:
int x;
int spam(int);
...
</pre>
</div>
<p>
then SWIG transforms it into a set of low-level procedural wrappers. For example:
</p>
<div class="code">
<pre>
Foo *new_Foo() {
return new Foo();
}
void delete_Foo(Foo *f) {
delete f;
}
int Foo_x_get(Foo *f) {
return f->x;
}
void Foo_x_set(Foo *f, int value) {
f->x = value;
}
int Foo_spam(Foo *f, int arg1) {
return f->spam(arg1);
}
</pre>
</div>
<p>
These wrappers can be found in the low-level extension module (e.g., <tt>_example</tt>).
</p>
<p>
Using these wrappers, SWIG generates a high-level Python proxy class (also known as a shadow class) like this (shown
for Python 2.2):
</p>
<div class="targetlang">
<pre>
import _example
class Foo(object):
def __init__(self):
self.this = _example.new_Foo()
self.thisown = 1
def __del__(self):
if self.thisown:
_example.delete_Foo(self.this)
def spam(self, arg1):
return _example.Foo_spam(self.this, arg1)
x = property(_example.Foo_x_get, _example.Foo_x_set)
</pre>
</div>
<p>
This class merely holds a pointer to the underlying C++ object (<tt>.this</tt>) and dispatches methods and
member variable access to that object using the low-level accessor functions. From a user's point of
view, it makes the class work normally:
</p>
<div class="targetlang">
<pre>
>>> f = example.Foo()
>>> f.x = 3
>>> y = f.spam(5)
</pre>
</div>
<p>
The fact that the class has been wrapped by a real Python class offers certain advantages. For instance,
you can attach new Python methods to the class and you can even inherit from it (something not supported
by Python built-in types until Python 2.2).
</p>
<H3><a name="Python_builtin_types">36.4.2 Built-in Types</a></H3>
<p>
The <tt>-builtin</tt> option provides a significant performance improvement
in the wrapped code. To understand the difference between proxy classes
and built-in types, let's take a look at what a wrapped object looks like
under both circumstances.
</p>
<p>When proxy classes are used, each wrapped object in python is an instance
of a pure python class. As a reminder, here is what the <tt>__init__</tt> method looks
like in a proxy class:
</p>
<div class="targetlang">
<pre>
class Foo(object):
def __init__(self):
self.this = _example.new_Foo()
self.thisown = 1
</pre>
</div>
<p>When a <tt>Foo</tt> instance is created, the call to <tt>_example.new_Foo()</tt>
creates a new C++ <tt>Foo</tt> instance; wraps that C++ instance inside an instance of
a python built-in type called <tt>SwigPyObject</tt>; and stores the <tt>SwigPyObject</tt>
instance in the 'this' field of the python Foo object. Did you get all that? So, the
python <tt>Foo</tt> object is composed of three parts:</p>
<ul>
<li> The python <tt>Foo</tt> instance, which contains...</li>
<li> ... an instance of <tt>struct SwigPyObject</tt>, which contains...</li>
<li> ... a C++ <tt>Foo</tt> instance</li>
</ul>
<p>When <tt>-builtin</tt> is used, the pure python layer is stripped off. Each
wrapped class is turned into a new python built-in type which inherits from
<tt>SwigPyObject</tt>, and <tt>SwigPyObject</tt> instances are returned directly
from the wrapped methods. For more information about python built-in extensions,
please refer to the python documentation:</p>
<p><a href="http://docs.python.org/extending/newtypes.html">http://docs.python.org/extending/newtypes.html</a></p>
<H4><a name="Python_builtin_limitations">36.4.2.1 Limitations</a></H4>
<p>Use of the <tt>-builtin</tt> option implies a couple of limitations:
<ul>
<li><p>python version support:</p>
<ul>
<li>Versions 2.5 and up are fully supported</li>
<li>Versions 2.3 and 2.4 are mostly supported; there are problems with director classes and/or sub-classing a wrapped type in python.</li>
<li>Versions older than 2.3 are not supported.</li>
</ul>
</li>
<li><p>Some legacy syntax is no longer supported; in particular:</p>
<ul>
<li>The functional interface is no longer exposed. For example, you may no longer call <tt>Whizzo.new_CrunchyFrog()</tt>. Instead, you must use <tt>Whizzo.CrunchyFrog()</tt>.</li>
<li>Static member variables are no longer accessed through the 'cvar' field (e.g., <tt>Dances.cvar.FishSlap</tt>).
They are instead accessed in the idiomatic way (<tt>Dances.FishSlap</tt>).</li>
</ul>
</li>
<li><p>Wrapped types may not be raised as python exceptions. Here's why: the python internals expect that all sub-classes of Exception will have this struct layout:</p>
<div class="code">
<pre>
typedef struct {
PyObject_HEAD
PyObject *dict;
PyObject *args;
PyObject *message;
} PyBaseExceptionObject;
</pre>
</div>
<p>But swig-generated wrappers expect that all swig-wrapped classes will have this struct layout:</p>
<div class="code">
<pre>
typedef struct {
PyObject_HEAD
void *ptr;
swig_type_info *ty;
int own;
PyObject *next;
PyObject *dict;
} SwigPyObject;
</pre>
</div>
<p>There are workarounds for this. For example, if you wrap this class:
<div class="code">
<pre>
class MyException {
public:
MyException (const char *msg_);
~MyException ();
const char *what () const;
private:
char *msg;
};
</pre>
</div>
<p>... you can define this python class, which may be raised as an exception:</p>
<div class="targetlang">
<pre>
class MyPyException(Exception):
def __init__(self, msg, *args):
Exception.__init__(self, *args)
self.myexc = MyException(msg)
def what(self):
return self.myexc.what()
</pre>
</div>
</li>
<li><p>Reverse binary operators (e.g., <tt>__radd__</tt>) are not supported.</p>
<p>To illustrate this point, if you have a wrapped class called <tt>MyString</tt>,
and you want to use instances of <tt>MyString</tt> interchangeably with native python
strings, you can define an <tt>'operator+ (const char*)'</tt> method :</p>
<div class="code">
<pre>
class MyString {
public:
MyString (const char *init);
MyString operator+ (const char *other) const;
...
};
</pre>
</div>
<p>
SWIG will automatically create an operator overload in python that will allow this:
</p>
<div class="targetlang">
<pre>
from MyModule import MyString
mystr = MyString("No one expects")
episode = mystr + " the Spanish Inquisition"
</pre>
</div>
<p>
This works because the first operand (<tt>mystr</tt>) defines a way
to add a native string to itself. However, the following will <b>not</b> work:
</p>
<div class="targetlang">
<pre>
from MyModule import MyString
mystr = MyString("Parrot")
episode = "Dead " + mystr
</pre>
</div>
<p>
The above code fails, because the first operand -- a native python string --
doesn't know how to add an instance of <tt>MyString</tt> to itself.
</p>
</li>
<li><p>If you have multiple SWIG modules that share type information (<a href="Modules.html#Modules_nn2">more info</a>),
the <tt>-builtin</tt> option requires a bit of extra discipline to ensure that base classes are initialized before derived classes. Specifically:</p>
<ul>
<li><p>There must be an unambiguous dependency graph for the modules.</p></li>
<li><p>Module dependencies must be explicitly stated with <tt>%import</tt> statements in the SWIG interface file.</p>
</ul>
<p>As an example, suppose module <tt>A</tt> has this interface in <tt>A.i</tt> :</p>
<div class="code"><pre>
%module "A";
class Base {
...
};
</pre></div>
<p>If you want to wrap another module containing a class that inherits from <tt>A</tt>, this is how it would look :</p>
<div class="code"><pre>
%module "B";
%import "A.i"
class Derived : public Base {
...
};
</pre></div>
<p>The <tt>import "A.i"</tt> statement is required, because module <tt>B</tt> depends on module <tt>A</tt>.</p>
<p>As long as you obey these requirements, your python code may import the modules in any order :</p>
<div class="targetlang"><pre>
import B
import A
assert(issubclass(B.Derived, A.Base))
</pre></div>
</li>
</ul>
<H4><a name="Python_builtin_overloads">36.4.2.2 Operator overloads and slots -- use them!</a></H4>
<p>The entire justification for the <tt>-builtin</tt> option is improved
performance. To that end, the best way to squeeze maximum performance out
of your wrappers is to <b>use operator overloads.</b>
Named method dispatch is slow in python, even when compared to other scripting languages.
However, python built-in types have a large number of "slots",
analogous to C++ operator overloads, which allow you to short-circuit named method dispatch
for certain common operations.
</p>
<p>By default, SWIG will translate most C++ arithmetic operator overloads into python
slot entries. For example, suppose you have this class:
<div class="code">
<pre>
class Twit {
public:
Twit operator+ (const Twit& twit) const;
// Forward to operator+
Twit add (const Twit& twit) const
{ return *this + twit; }
};
</pre>
</div>
<p>SWIG will automatically register <tt>operator+</tt> as a python slot operator for addition. You may write python code like this:</p>
<div class="targetlang">
<pre>
from MyModule import Twit
nigel = Twit()
emily = Twit()
percival = nigel + emily
percival = nigel.add(emily)
</pre>
</div>
<p>The last two lines of the python code are equivalent,
but <b>the line that uses the '+' operator is much faster</b>.
</p>
<p>In-place operators (e.g., <tt>operator+=</tt>) and comparison operators
(<tt>operator==, operator<</tt>, etc.) are also converted to python
slot operators. For a complete list of C++ operators that are
automatically converted to python slot operators, refer to the file
<tt>python/pyopers.swig</tt> in the SWIG library.
</p>
<p>
Read about all of the available python slots here:
<a href="http://docs.python.org/c-api/typeobj.html">http://docs.python.org/c-api/typeobj.html</a></p>
<p>
There are two ways to define a python slot function: dispatch to a
statically defined function; or dispatch to a method defined on the
operand.
</p>
<p>
To dispatch to a statically defined function, use %feature("python:<slot>"),
where <slot> is the name of a field in a <tt>PyTypeObject, PyNumberMethods,
PyMappingMethods, PySequenceMethods</tt> or <tt>PyBufferProcs</tt>.
You may override (almost) all of these slots.
</p>
<p>
Let's consider an example setting the <tt>tp_hash</tt> slot for the <tt>MyClass</tt> type.
This is akin to providing a <tt>__hash__</tt> method (for non-builtin types) to make a type hashable.
The hashable type can then for example be added to a Python <tt>dict</tt>.
</p>
<div class="code">
<pre>
%feature("python:tp_hash") MyClass "myHashFunc";
class MyClass {
public:
long field1;
long field2;
...
};
%{
#if PY_VERSION_HEX >= 0x03020000
static Py_hash_t myHashFunc(PyObject *pyobj)
#else
static long myHashFunc(PyObject *pyobj)
#endif
{
MyClass *cobj;
// Convert pyobj to cobj
return (cobj->field1 * (cobj->field2 << 7));
}
%}
</pre>
</div>
<p>
If you examine the generated code, the supplied hash function will now be
the function callback in the tp_hash slot for the builtin type for <tt>MyClass</tt>:
</p>
<div class="code">
<pre>
static PyHeapTypeObject SwigPyBuiltin__MyClass_type = {
...
(hashfunc) myHashFunc, /* tp_hash */
...
</pre>
</div>
<p>
NOTE: It is the responsibility of the programmer (that's you!) to ensure
that a statically defined slot function has the correct signature, the <tt>hashfunc</tt>
typedef in this case.
</p>
<p>
If, instead, you want to dispatch to an instance method, you can
use %feature("python:slot"). For example:
</p>
<div class="code">
<pre>
%feature("python:slot", "tp_hash", functype="hashfunc") MyClass::myHashFunc;
#if PY_VERSION_HEX < 0x03020000
#define Py_hash_t long
#endif
class MyClass {
public:
Py_hash_t myHashFunc() const;
...
};
</pre>
</div>
<p>
NOTE: Some python slots use a method signature which does not
match the signature of SWIG-wrapped methods. For those slots,
SWIG will automatically generate a "closure" function to re-marshal
the arguments before dispatching to the wrapped method. Setting
the "functype" attribute of the feature enables SWIG to generate
the chosen closure function.
</p>
<p>
There is further information on <tt>%feature("python:slot")</tt>
in the file <tt>python/pyopers.swig</tt> in the SWIG library.
</p>
<H3><a name="Python_nn30">36.4.3 Memory management</a></H3>
<p>NOTE: Although this section refers to proxy objects, everything here also applies
when the <tt>-builtin</tt> option is used.</p>
<p>
Associated with proxy object, is an ownership flag <tt>.thisown</tt> The value of this
flag determines who is responsible for deleting the underlying C++ object. If set to 1,
the Python interpreter will destroy the C++ object when the proxy class is
garbage collected. If set to 0 (or if the attribute is missing), then the destruction
of the proxy class has no effect on the C++ object.
</p>
<p>
When an object is created by a constructor or returned by value, Python automatically takes
ownership of the result. For example:
</p>
<div class="code">
<pre>
class Foo {
public:
Foo();
Foo bar();
};
</pre>
</div>
<p>
In Python:
</p>
<div class="targetlang">
<pre>
>>> f = Foo()
>>> f.thisown
1
>>> g = f.bar()
>>> g.thisown
1
</pre>
</div>
<p>
On the other hand, when pointers are returned to Python, there is often no way to know where
they came from. Therefore, the ownership is set to zero. For example:
</p>
<div class="code">
<pre>
class Foo {
public:
...
Foo *spam();
...
};
</pre>
</div>
<br>
<div class="targetlang">
<pre>
>>> f = Foo()
>>> s = f.spam()
>>> print s.thisown
0
>>>
</pre>
</div>
<p>
This behavior is especially important for classes that act as
containers. For example, if a method returns a pointer to an object
that is contained inside another object, you definitely don't want
Python to assume ownership and destroy it!
</p>
<p>
A good way to indicate that ownership should be set for a returned pointer
is to use the <a href="Library.html#Library_nn11">%newobject directive</a>.
</p>
<p>
Related to containers, ownership issues can arise whenever an object is assigned to a member
or global variable. For example, consider this interface:
</p>
<div class="code">
<pre>
%module example
struct Foo {
int value;
Foo *next;
};
Foo *head = 0;
</pre>
</div>
<p>
When wrapped in Python, careful observation will reveal that ownership changes whenever an object
is assigned to a global variable. For example:
</p>
<div class="targetlang">
<pre>
>>> f = example.Foo()
>>> f.thisown
1
>>> example.cvar.head = f
>>> f.thisown
0
>>>
</pre>
</div>
<p>
In this case, C is now holding a reference to the object---you probably don't want Python to destroy it.
Similarly, this occurs for members. For example:
</p>
<div class="targetlang">
<pre>
>>> f = example.Foo()
>>> g = example.Foo()
>>> f.thisown
1
>>> g.thisown
1
>>> f.next = g
>>> g.thisown
0
>>>
</pre>
</div>
<p>
For the most part, memory management issues remain hidden. However,
there are occasionally situations where you might have to manually
change the ownership of an object. For instance, consider code like this:
</p>
<div class="code">
<pre>
class Node {
Object *value;
public:
void set_value(Object *v) { value = v; }
...
};
</pre>
</div>
<p>
Now, consider the following Python code:
</p>
<div class="targetlang">
<pre>
>>> v = Object() # Create an object
>>> n = Node() # Create a node
>>> n.set_value(v) # Set value
>>> v.thisown
1
>>> del v
</pre>
</div>
<p>
In this case, the object <tt>n</tt> is holding a reference to
<tt>v</tt> internally. However, SWIG has no way to know that this
has occurred. Therefore, Python still thinks that it has ownership of the
object. Should the proxy object be destroyed, then the C++ destructor
will be invoked and <tt>n</tt> will be holding a stale-pointer. If
you're lucky, you will only get a segmentation fault.
</p>
<p>
To work around this, it is always possible to flip the ownership flag. For example,
</p>
<div class="targetlang">
<pre>
>>> v.thisown = 0
</pre>
</div>
<p>
It is also possible to deal with situations like this using
typemaps--an advanced topic discussed later.
</p>
<H3><a name="Python_nn31">36.4.4 Python 2.2 and classic classes</a></H3>
<p>
SWIG makes every attempt to preserve backwards compatibility with
older versions of Python to the extent that it is possible. However,
in Python-2.2, an entirely new type of class system was introduced.
This new-style class system offers many enhancements including static
member functions, properties (managed attributes), and class methods.
Details about all of these changes can be found on <a
href="https://www.python.org">www.python.org</a> and is not repeated here.
</p>
<p>
To address differences between Python versions, SWIG currently emits
dual-mode proxy class wrappers. In Python-2.2 and newer releases,
these wrappers encapsulate C++ objects in new-style classes that take
advantage of new features (static methods and properties). However,
if these very same wrappers are imported into an older version of Python,
old-style classes are used instead.
</p>
<p>
This dual-nature of the wrapper code means that you can create extension
modules with SWIG and those modules will work with all versions of Python
ranging from Python-2.0 to the very latest release. Moreover, the wrappers take
advantage of Python-2.2 features when available.
</p>
<p>
For the most part, the interface presented to users is the same regardless
of what version of Python is used. The only incompatibility lies in the handling
of static member functions. In Python-2.2, they can be accessed via the
class itself. In Python-2.1 and earlier, they have to be accessed as a global
function or through an instance (see the earlier section).
</p>
<H2><a name="Python_directors">36.5 Cross language polymorphism</a></H2>
<p>
Proxy classes provide a more natural, object-oriented way to access
extension classes. As described above, each proxy instance has an
associated C++ instance, and method calls to the proxy are passed to the
C++ instance transparently via C wrapper functions.
</p>
<p>
This arrangement is asymmetric in the sense that no corresponding
mechanism exists to pass method calls down the inheritance chain from
C++ to Python. In particular, if a C++ class has been extended in Python
(by extending the proxy class), these extensions will not be visible
from C++ code. Virtual method calls from C++ are thus not able access
the lowest implementation in the inheritance chain.
</p>
<p>
Changes have been made to SWIG 1.3.18 to address this problem and
make the relationship between C++ classes and proxy classes more
symmetric. To achieve this goal, new classes called directors are
introduced at the bottom of the C++ inheritance chain. The job of the
directors is to route method calls correctly, either to C++
implementations higher in the inheritance chain or to Python
implementations lower in the inheritance chain. The upshot is that C++
classes can be extended in Python and from C++ these extensions look
exactly like native C++ classes. Neither C++ code nor Python code needs
to know where a particular method is implemented: the combination of
proxy classes, director classes, and C wrapper functions takes care of
all the cross-language method routing transparently.
</p>
<H3><a name="Python_nn33">36.5.1 Enabling directors</a></H3>
<p>
The director feature is disabled by default. To use directors you
must make two changes to the interface file. First, add the "directors"
option to the %module directive, like this:
</p>
<div class="code">
<pre>
%module(directors="1") modulename
</pre>
</div>
<p>
Without this option no director code will be generated. Second, you
must use the %feature("director") directive to tell SWIG which classes
and methods should get directors. The %feature directive can be applied
globally, to specific classes, and to specific methods, like this:
</p>
<div class="code">
<pre>
// generate directors for all classes that have virtual methods
%feature("director");
// generate directors for all virtual methods in class Foo
%feature("director") Foo;
</pre>
</div>
<p>
You can use the %feature("nodirector") directive to turn off
directors for specific classes or methods. So for example,
</p>
<div class="code">
<pre>
%feature("director") Foo;
%feature("nodirector") Foo::bar;
</pre>
</div>
<p>
will generate directors for all virtual methods of class Foo except
bar().
</p>
<p>
Directors can also be generated implicitly through inheritance.
In the following, class Bar will get a director class that handles
the methods one() and two() (but not three()):
</p>
<div class="code">
<pre>
%feature("director") Foo;
class Foo {
public:
Foo(int foo);
virtual ~Foo();
virtual void one();
virtual void two();
};
class Bar: public Foo {
public:
virtual void three();
};
</pre>
</div>
<p>
then at the python side you can define
</p>
<div class="targetlang">
<pre>
import mymodule
class MyFoo(mymodule.Foo):
def __init__(self, foo):
mymodule.Foo.__init__(self, foo)
# super().__init__(foo) # Alternative construction for Python3
def one(self):
print "one from python"
</pre>
</div>
<H3><a name="Python_nn34">36.5.2 Director classes</a></H3>
<p>
For each class that has directors enabled, SWIG generates a new class
that derives from both the class in question and a special
<tt>Swig::Director</tt> class. These new classes, referred to as director
classes, can be loosely thought of as the C++ equivalent of the Python
proxy classes. The director classes store a pointer to their underlying
Python object and handle various issues related to object ownership.
Indeed, this is quite similar to the "this" and "thisown" members of the
Python proxy classes.
</p>
<p>
For simplicity let's ignore the <tt>Swig::Director</tt> class and refer to the
original C++ class as the director's base class. By default, a director
class extends all virtual methods in the inheritance chain of its base
class (see the preceding section for how to modify this behavior).
Thus all virtual method calls, whether they originate in C++ or in
Python via proxy classes, eventually end up in at the implementation in
the director class. The job of the director methods is to route these
method calls to the appropriate place in the inheritance chain. By
"appropriate place" we mean the method that would have been called if
the C++ base class and its extensions in Python were seamlessly
integrated. That seamless integration is exactly what the director
classes provide, transparently skipping over all the messy extension API
glue that binds the two languages together.
</p>
<p>
In reality, the "appropriate place" is one of only two possibilities:
C++ or Python. Once this decision is made, the rest is fairly easy. If
the correct implementation is in C++, then the lowest implementation of
the method in the C++ inheritance chain is called explicitly. If the
correct implementation is in Python, the Python API is used to call the
method of the underlying Python object (after which the usual virtual
method resolution in Python automatically finds the right
implementation).
</p>
<p>
Now how does the director decide which language should handle the method call?
The basic rule is to handle the method in Python, unless there's a good
reason not to. The reason for this is simple: Python has the most
"extended" implementation of the method. This assertion is guaranteed,
since at a minimum the Python proxy class implements the method. If the
method in question has been extended by a class derived from the proxy
class, that extended implementation will execute exactly as it should.
If not, the proxy class will route the method call into a C wrapper
function, expecting that the method will be resolved in C++. The wrapper
will call the virtual method of the C++ instance, and since the director
extends this the call will end up right back in the director method. Now
comes the "good reason not to" part. If the director method were to blindly
call the Python method again, it would get stuck in an infinite loop. We avoid this
situation by adding special code to the C wrapper function that tells
the director method to not do this. The C wrapper function compares the
pointer to the Python object that called the wrapper function to the
pointer stored by the director. If these are the same, then the C
wrapper function tells the director to resolve the method by calling up
the C++ inheritance chain, preventing an infinite loop.
</p>
<p>
One more point needs to be made about the relationship between director
classes and proxy classes. When a proxy class instance is created in
Python, SWIG creates an instance of the original C++ class and assigns
it to <tt>.this</tt>. This is exactly what happens without directors and
is true even if directors are enabled for the particular class in
question. When a class <i>derived</i> from a proxy class is created,
however, SWIG then creates an instance of the corresponding C++ director
class. The reason for this difference is that user-defined subclasses
may override or extend methods of the original class, so the director
class is needed to route calls to these methods correctly. For
unmodified proxy classes, all methods are ultimately implemented in C++
so there is no need for the extra overhead involved with routing the
calls through Python.
</p>
<H3><a name="Python_nn35">36.5.3 Ownership and object destruction</a></H3>
<p>
Memory management issues are slightly more complicated with directors
than for proxy classes alone. Python instances hold a pointer to the
associated C++ director object, and the director in turn holds a pointer
back to the Python object. By default, proxy classes own their C++
director object and take care of deleting it when they are garbage
collected.
</p>
<p>
This relationship can be reversed by calling the special
<tt>__disown__()</tt> method of the proxy class. After calling this
method, the <tt>.thisown</tt> flag is set to zero, and the director
class increments the reference count of the Python object. When the
director class is deleted it decrements the reference count. Assuming no
outstanding references to the Python object remain, the Python object
will be destroyed at the same time. This is a good thing, since
directors and proxies refer to each other and so must be created and
destroyed together. Destroying one without destroying the other will
likely cause your program to segfault.
</p>
<p>
To help ensure that no references to the Python object remain after
calling <tt>__disown__()</tt>, this method returns a weak reference to
the Python object. Weak references are only available in Python versions
2.1 and higher, so for older versions you must explicitly delete all
references. Here is an example:
</p>
<div class="code">
<pre>
class Foo {
public:
...
};
class FooContainer {
public:
void addFoo(Foo *);
...
};
</pre>
</div>
<br>
<div class="targetlang">
<pre>
>>> c = FooContainer()
>>> a = Foo().__disown__()
>>> c.addFoo(a)
>>> b = Foo()
>>> b = b.__disown__()
>>> c.addFoo(b)
>>> c.addFoo(Foo().__disown__())
</pre>
</div>
<p>
In this example, we are assuming that FooContainer will take care of
deleting all the Foo pointers it contains at some point. Note that no hard
references to the Foo objects remain in Python.
</p>
<H3><a name="Python_nn36">36.5.4 Exception unrolling</a></H3>
<p>
With directors routing method calls to Python, and proxies routing them
to C++, the handling of exceptions is an important concern. By default, the
directors ignore exceptions that occur during method calls that are
resolved in Python. To handle such exceptions correctly, it is necessary
to temporarily translate them into C++ exceptions. This can be done with
the %feature("director:except") directive. The following code should
suffice in most cases:
</p>
<div class="code">
<pre>
%feature("director:except") {
if ($error != NULL) {
throw Swig::DirectorMethodException();
}
}
</pre>
</div>
<p>
This code will check the Python error state after each method call from
a director into Python, and throw a C++ exception if an error occurred.
This exception can be caught in C++ to implement an error handler.
Currently no information about the Python error is stored in the
Swig::DirectorMethodException object, but this will likely change in
the future.
</p>
<p>
It may be the case that a method call originates in Python, travels up
to C++ through a proxy class, and then back into Python via a director
method. If an exception occurs in Python at this point, it would be nice
for that exception to find its way back to the original caller. This can
be done by combining a normal %exception directive with the
<tt>director:except</tt> handler shown above. Here is an example of a
suitable exception handler:
</p>
<div class="code">
<pre>
%exception {
try { $action }
catch (Swig::DirectorException &e) { SWIG_fail; }
}
</pre>
</div>
<p>
The class Swig::DirectorException used in this example is actually a
base class of Swig::DirectorMethodException, so it will trap this
exception. Because the Python error state is still set when
Swig::DirectorMethodException is thrown, Python will register the
exception as soon as the C wrapper function returns.
</p>
<H3><a name="Python_nn37">36.5.5 Overhead and code bloat</a></H3>
<p>
Enabling directors for a class will generate a new director method for
every virtual method in the class' inheritance chain. This alone can
generate a lot of code bloat for large hierarchies. Method arguments
that require complex conversions to and from target language types can
result in large director methods. For this reason it is recommended that
you selectively enable directors only for specific classes that are
likely to be extended in Python and used in C++.
</p>
<p>
Compared to classes that do not use directors, the call routing in the
director methods does add some overhead. In particular, at least one
dynamic cast and one extra function call occurs per method call from
Python. Relative to the speed of Python execution this is probably
completely negligible. For worst case routing, a method call that
ultimately resolves in C++ may take one extra detour through Python in
order to ensure that the method does not have an extended Python
implementation. This could result in a noticeable overhead in some cases.
</p>
<p>
Although directors make it natural to mix native C++ objects with Python
objects (as director objects) via a common base class pointer, one
should be aware of the obvious fact that method calls to Python objects
will be much slower than calls to C++ objects. This situation can be
optimized by selectively enabling director methods (using the %feature
directive) for only those methods that are likely to be extended in
Python.
</p>
<H3><a name="Python_nn38">36.5.6 Typemaps</a></H3>
<p>
Typemaps for input and output of most of the basic types from director
classes have been written. These are roughly the reverse of the usual
input and output typemaps used by the wrapper code. The typemap
operation names are 'directorin', 'directorout', and 'directorargout'.
The director code does not currently use any of the other kinds of typemaps.
It is not clear at this point which kinds are appropriate and
need to be supported.
</p>
<H3><a name="Python_nn39">36.5.7 Miscellaneous</a></H3>
<p>
Director typemaps for STL classes are in place, and hence you should
be able to use std::vector, std::string, etc., as you would any other type.
</p>
<p>
<b>Note:</b> The director typemaps for return types based in const
references, such as
<div class="code">
<pre>
class Foo {
…
virtual const int& bar();
…
};
</pre>
</div>
<p>
will work only for simple call scenarios. Usually the resulting code
is neither thread or reentrant safe. Hence, the user is advised to
avoid returning const references in director methods. For example,
the user could modify the method interface to use lvalue return
types, wherever possible, for example
</p>
<div class="code">
<pre>
class Foo {
…
virtual int bar();
…
};
</pre>
</div>
<p>
If that is not possible, the user should avoid enabling the
director feature for reentrant, recursive or threaded member
methods that return const references.
</p>
<H2><a name="Python_nn40">36.6 Common customization features</a></H2>
<p>
The last section presented the absolute basics of C/C++ wrapping. If
you do nothing but feed SWIG a header file, you will get an interface
that mimics the behavior described. However, sometimes this isn't
enough to produce a nice module. Certain types of functionality might
be missing or the interface to certain functions might be awkward.
This section describes some common SWIG features that are used to
improve your the interface to an extension module.
</p>
<H3><a name="Python_nn41">36.6.1 C/C++ helper functions</a></H3>
<p>
Sometimes when you create a module, it is missing certain bits of functionality. For
example, if you had a function like this
</p>
<div class="code">
<pre>
void set_transform(Image *im, double m[4][4]);
</pre>
</div>
<p>
it would be accessible from Python, but there may be no easy way to call it.
For example, you might get errors like this:
</p>
<div class="targetlang">
<pre>
>>> a = [
... [1, 0, 0, 0],
... [0, 1, 0, 0],
... [0, 0, 1, 0],
... [0, 0, 0, 1]]
>>> set_transform(im, a)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: Type error. Expected _p_a_4__double
</pre>
</div>
<p>
The problem here is that there is no easy way to construct and manipulate a suitable
<tt>double [4][4]</tt> value to use. To fix this, you can write some extra C helper
functions. Just use the <tt>%inline</tt> directive. For example:
</p>
<div class="code">
<pre>
%inline %{
/* Note: double[4][4] is equivalent to a pointer to an array double (*)[4] */
double (*new_mat44())[4] {
return (double (*)[4]) malloc(16*sizeof(double));
}
void free_mat44(double (*x)[4]) {
free(x);
}
void mat44_set(double x[4][4], int i, int j, double v) {
x[i][j] = v;
}
double mat44_get(double x[4][4], int i, int j) {
return x[i][j];
}
%}
</pre>
</div>
<p>
From Python, you could then write code like this:
</p>
<div class="targetlang">
<pre>
>>> a = new_mat44()
>>> mat44_set(a, 0, 0, 1.0)
>>> mat44_set(a, 1, 1, 1.0)
>>> mat44_set(a, 2, 2, 1.0)
...
>>> set_transform(im, a)
>>>
</pre>
</div>
<p>
Admittedly, this is not the most elegant looking approach. However, it works and it wasn't too
hard to implement. It is possible to clean this up using Python code, typemaps, and other
customization features as covered in later sections.
</p>
<H3><a name="Python_nn42">36.6.2 Adding additional Python code</a></H3>
<p>
If writing support code in C isn't enough, it is also possible to write code in
Python. This code gets inserted in to the <tt>.py</tt> file created by SWIG. One
use of Python code might be to supply a high-level interface to certain functions.
For example:
</p>
<div class="code">
<pre>
void set_transform(Image *im, double x[4][4]);
...
/* Rewrite the high level interface to set_transform */
%pythoncode %{
def set_transform(im, x):
a = new_mat44()
for i in range(4):
for j in range(4):
mat44_set(a, i, j, x[i][j])
_example.set_transform(im, a)
free_mat44(a)
%}
</pre>
</div>
<p>
In this example, <tt>set_transform()</tt> provides a high-level Python interface built on top of
low-level helper functions. For example, this code now seems to work:
</p>
<div class="targetlang">
<pre>
>>> a = [
... [1, 0, 0, 0],
... [0, 1, 0, 0],
... [0, 0, 1, 0],
... [0, 0, 0, 1]]
>>> set_transform(im, a)
>>>
</pre>
</div>
<p>
Admittedly, this whole scheme for wrapping the two-dimension array
argument is rather ad-hoc. Besides, shouldn't a Python list or a
Numeric Python array just work normally? We'll get to those examples
soon enough. For now, think of this example as an illustration of
what can be done without having to rely on any of the more advanced
customization features.
</p>
<p>
There is also <tt>%pythonbegin</tt> which is another directive very similar to <tt>%pythoncode</tt>,
but generates the given Python code at the beginning of the <tt>.py</tt> file.
This directive works in the same way as <tt>%pythoncode</tt>, except the code is copied
just after the SWIG banner (comment) at the top of the file, before any real code.
This provides an opportunity to add your own description in a comment near the top of the file as well
as Python imports that have to appear at the top of the file, such as "<tt>from __future__ import</tt>"
statements.
</p>
<p>
The following shows example usage for Python 2.6 to use <tt>print</tt> as it can in Python 3, that is, as a function instead of a statement:
</p>
<div class="code">
<pre>
%pythonbegin %{
# This module provides wrappers to the Whizz Bang library
%}
%pythonbegin %{
from __future__ import print_function
print("Loading", "Whizz", "Bang", sep=' ... ')
%}
</pre>
</div>
<p>
which can be seen when viewing the first few lines of the generated <tt>.py</tt> file:
</p>
<div class="code">
<pre>
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 2.0.11
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
# This module provides wrappers to the Whizz Bang library
from __future__ import print_function
print("Loading", "Whizz", "Bang", sep=' ... ')
</pre>
</div>
<p>When using <tt>%pythoncode</tt> and <tt>%pythonbegin</tt> you generally
want to make sure that the block is delimited by <tt>%{</tt> and <tt>%}</tt>.
If you delimit it with <tt>{</tt> and <tt>}</tt> then any lines with a
leading <tt>#</tt> will be handled by SWIG as preprocessor directives, when
you probably meant them as Python comments. Prior to SWIG 3.0.3, invalid
preprocessor directives were silently ignored, so generally using the wrong
delimiters resulted in such comments not appearing in the generated output
(though a comment starting with a valid preprocessor directive could cause
problems, for example: <tt># error handling</tt>). SWIG 3.0.3 and later report
an error for invalid preprocessor directives, so you may have to update
existing interface files to delimit blocks of Python code correctly.</p>
<p>As an alternative to providing a block containing Python code, you can
include python code from a file. The code is inserted exactly as in the
file, so this avoids any issues with the SWIG preprocessor. It's a good
approach if you have a non-trivial chunk of Python code to insert. To
use this feature you specify a filename in double quotes, for example:</p>
<div class="code">
<pre>
%pythoncode "somecode.py"
</pre>
</div>
<p>Sometimes you may want to replace or modify the wrapper function
that SWIG creates in the proxy <tt>.py</tt> file. The Python module
in SWIG provides some features that enable you to do this. First, to
entirely replace a proxy function you can use
<tt>%feature("shadow")</tt>. For example:</p>
<div class="code">
<pre>
%module example
// Rewrite bar() python code
%feature("shadow") Foo::bar(int) %{
def bar(*args):
#do something before
$action
#do something after
%}
class Foo {
public:
int bar(int x);
};
</pre>
</div>
<p> where <tt>$action</tt> will be replaced by the call to
the C/C++ proper method.
</p>
<p>
Often the proxy function created by SWIG is fine, but you simply want
to add code to it without touching the rest of the generated function
body. For these cases SWIG provides the <tt>pythonprepend</tt> and
<tt>pythonappend</tt> features which do exactly as their names suggest. The
<tt>pythonprepend</tt> feature will insert its value at the beginning of the
proxy function, and <tt>pythonappend</tt> will insert code at the end of the
proxy, just before the return statement.
</p>
<div class="code">
<pre>
%module example
// Add python code to bar()
%feature("pythonprepend") Foo::bar(int) %{
#do something before C++ call
%}
%feature("pythonappend") Foo::bar(int) %{
#do something after C++ call
%}
class Foo {
public:
int bar(int x);
};
</pre>
</div>
<p>
Notes: Usually the <tt>pythonappend</tt> and <tt>pythonprepend</tt>
features are safer to use than the <tt>shadow</tt> feature. Also, from
SWIG version 1.3.28 you can use the directive forms
<tt>%pythonappend</tt> and <tt>%pythonprepend</tt> as follows:</p>
<div class="code">
<pre>
%module example
// Add python code to bar()
%pythonprepend Foo::bar(int) %{
#do something before C++ call
%}
%pythonappend Foo::bar(int) %{
#do something after C++ call
%}
class Foo {
public:
int bar(int x);
};
</pre>
</div>
<p>
Note that when the underlying C++ method is overloaded, there is only one proxy Python method
for multiple C++ methods. In this case, only one of parsed methods is examined
for the feature. You are better off specifying the feature without the argument list to ensure it will get used,
as it will then get attached to all the overloaded C++ methods. For example:
</p>
<div class="code">
<pre>
%module example
// Add python code to bar()
%pythonprepend Foo::bar %{
#do something before C++ call
%}
%pythonappend Foo::bar %{
#do something after C++ call
%}
class Foo {
public:
int bar(int x);
int bar();
};
</pre>
</div>
<p>
The same applies for overloaded constructors.
</p>
<H3><a name="Python_nn43">36.6.3 Class extension with %extend</a></H3>
<p>
One of the more interesting features of SWIG is that it can extend
structures and classes with new methods--at least in the Python interface.
Here is a simple example:
</p>
<div class="code">
<pre>
%module example
%{
#include "someheader.h"
%}
struct Vector {
double x, y, z;
};
%extend Vector {
char *__str__() {
static char tmp[1024];
sprintf(tmp, "Vector(%g, %g, %g)", $self->x, $self->y, $self->z);
return tmp;
}
Vector(double x, double y, double z) {
Vector *v = (Vector *) malloc(sizeof(Vector));
v->x = x;
v->y = y;
v->z = z;
return v;
}
};
</pre>
</div>
<p>
Now, in Python
</p>
<div class="targetlang">
<pre>
>>> v = example.Vector(2, 3, 4)
>>> print v
Vector(2, 3, 4)
>>>
</pre>
</div>
<p>
<tt>%extend</tt> can be used for many more tasks than this.
For example, if you wanted to overload a Python operator, you might do this:
</p>
<div class="code">
<pre>
%extend Vector {
Vector __add__(Vector *other) {
Vector v;
v.x = $self->x + other->x;
v.y = $self->y + other->y;
v.z = $self->z + other->z;
return v;
}
};
</pre>
</div>
<p>
Use it like this:
</p>
<div class="targetlang">
<pre>
>>> import example
>>> v = example.Vector(2, 3, 4)
>>> w = example.Vector(10, 11, 12)
>>> print v+w
Vector(12, 14, 16)
>>>
</pre>
</div>
<p>
<tt>%extend</tt> works with both C and C++ code. It does not modify the underlying object
in any way---the extensions only show up in the Python interface.
</p>
<H3><a name="Python_nn44">36.6.4 Exception handling with %exception</a></H3>
<p>
If a C or C++ function throws an error, you may want to convert that error into a Python
exception. To do this, you can use the <tt>%exception</tt> directive. <tt>%exception</tt>
simply lets you rewrite part of the generated wrapper code to include an error check.
</p>
<p>
In C, a function often indicates an error by returning a status code (a negative number
or a NULL pointer perhaps). Here is a simple example of how you might handle that:
</p>
<div class="code">
<pre>
%exception malloc {
$action
if (!result) {
PyErr_SetString(PyExc_MemoryError, "Not enough memory");
SWIG_fail;
}
}
void *malloc(size_t nbytes);
</pre>
</div>
<p>
In Python,
</p>
<div class="targetlang">
<pre>
>>> a = example.malloc(2000000000)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
MemoryError: Not enough memory
>>>
</pre>
</div>
<p>
If a library provides some kind of general error handling framework, you can also use
that. For example:
</p>
<div class="code">
<pre>
%exception {
$action
if (err_occurred()) {
PyErr_SetString(PyExc_RuntimeError, err_message());
SWIG_fail;
}
}
</pre>
</div>
<p>
No declaration name is given to <tt>%exception</tt>, it is applied to all wrapper functions.
</p>
<p>
C++ exceptions are also easy to handle. For example, you can write code like this:
</p>
<div class="code">
<pre>
%exception getitem {
try {
$action
} catch (std::out_of_range &e) {
PyErr_SetString(PyExc_IndexError, const_cast<char*>(e.what()));
SWIG_fail;
}
}
class Base {
public:
Foo *getitem(int index); // Exception handled added
...
};
</pre>
</div>
<p>
When raising a Python exception from C, use the <tt>PyErr_SetString()</tt>
function as shown above followed by <tt>SWIG_fail</tt>.
The following exception types can be used as the first argument.
</p>
<div class="code">
<pre>
PyExc_ArithmeticError
PyExc_AssertionError
PyExc_AttributeError
PyExc_EnvironmentError
PyExc_EOFError
PyExc_Exception
PyExc_FloatingPointError
PyExc_ImportError
PyExc_IndexError
PyExc_IOError
PyExc_KeyError
PyExc_KeyboardInterrupt
PyExc_LookupError
PyExc_MemoryError
PyExc_NameError
PyExc_NotImplementedError
PyExc_OSError
PyExc_OverflowError
PyExc_RuntimeError
PyExc_StandardError
PyExc_SyntaxError
PyExc_SystemError
PyExc_TypeError
PyExc_UnicodeError
PyExc_ValueError
PyExc_ZeroDivisionError
</pre>
</div>
<p>
<tt>SWIG_fail</tt> is a C macro which when called within the context of SWIG wrapper function,
will jump to the error handler code. This will call any cleanup code (freeing any temp variables)
and then return from the wrapper function so that the Python interpreter can raise the Python exception.
This macro should always be called after setting a Python error in code snippets, such as typemaps and <tt>%exception</tt>, that are ultimately generated into the wrapper function.
</p>
<p>
The language-independent <tt>exception.i</tt> library file can also be used
to raise exceptions. See the <a href="Library.html#Library">SWIG Library</a> chapter.
</p>
<H2><a name="Python_nn45">36.7 Tips and techniques</a></H2>
<p>
Although SWIG is largely automatic, there are certain types of wrapping problems that
require additional user input. Examples include dealing with output parameters,
strings, binary data, and arrays. This chapter discusses the common techniques for
solving these problems.
</p>
<H3><a name="Python_nn46">36.7.1 Input and output parameters</a></H3>
<p>
A common problem in some C programs is handling parameters passed as simple pointers. For
example:
</p>
<div class="code">
<pre>
void add(int x, int y, int *result) {
*result = x + y;
}
</pre>
</div>
<p>
or perhaps
</p>
<div class="code">
<pre>
int sub(int *x, int *y) {
return *x-*y;
}
</pre>
</div>
<p>
The easiest way to handle these situations is to use the <tt>typemaps.i</tt> file. For example:
</p>
<div class="code">
<pre>
%module example
%include "typemaps.i"
void add(int, int, int *OUTPUT);
int sub(int *INPUT, int *INPUT);
</pre>
</div>
<p>
In Python, this allows you to pass simple values. For example:
</p>
<div class="targetlang">
<pre>
>>> a = add(3, 4)
>>> print a
7
>>> b = sub(7, 4)
>>> print b
3
>>>
</pre>
</div>
<p>
Notice how the <tt>INPUT</tt> parameters allow integer values to be passed instead of pointers
and how the <tt>OUTPUT</tt> parameter creates a return result.
</p>
<p>
If you don't want to use the names <tt>INPUT</tt> or <tt>OUTPUT</tt>, use the <tt>%apply</tt>
directive. For example:
</p>
<div class="code">
<pre>
%module example
%include "typemaps.i"
%apply int *OUTPUT { int *result };
%apply int *INPUT { int *x, int *y};
void add(int x, int y, int *result);
int sub(int *x, int *y);
</pre>
</div>
<p>
If a function mutates one of its parameters like this,
</p>
<div class="code">
<pre>
void negate(int *x) {
*x = -(*x);
}
</pre>
</div>
<p>
you can use <tt>INOUT</tt> like this:
</p>
<div class="code">
<pre>
%include "typemaps.i"
...
void negate(int *INOUT);
</pre>
</div>
<p>
In Python, a mutated parameter shows up as a return value. For example:
</p>
<div class="targetlang">
<pre>
>>> a = negate(3)
>>> print a
-3
>>>
</pre>
</div>
<p>
Note: Since most primitive Python objects are immutable, it is not possible to
perform in-place modification of a Python object passed as a parameter.
</p>
<p>
The most common use of these special typemap rules is to handle functions that
return more than one value. For example, sometimes a function returns a result
as well as a special error code:
</p>
<div class="code">
<pre>
/* send message, return number of bytes sent, along with success code */
int send_message(char *text, int len, int *success);
</pre>
</div>
<p>
To wrap such a function, simply use the <tt>OUTPUT</tt> rule above. For example:
</p>
<div class="code">
<pre>
%module example
%include "typemaps.i"
%apply int *OUTPUT { int *success };
...
int send_message(char *text, int *success);
</pre>
</div>
<p>
When used in Python, the function will return multiple values.
</p>
<div class="targetlang">
<pre>
bytes, success = send_message("Hello World")
if not success:
print "Whoa!"
else:
print "Sent", bytes
</pre>
</div>
<p>
Another common use of multiple return values are in query functions. For example:
</p>
<div class="code">
<pre>
void get_dimensions(Matrix *m, int *rows, int *columns);
</pre>
</div>
<p>
To wrap this, you might use the following:
</p>
<div class="code">
<pre>
%module example
%include "typemaps.i"
%apply int *OUTPUT { int *rows, int *columns };
...
void get_dimensions(Matrix *m, int *rows, *columns);
</pre>
</div>
<p>
Now, in Python:
</p>
<div class="targetlang">
<pre>
>>> r, c = get_dimensions(m)
</pre>
</div>
<p>
Be aware that the primary purpose of the <tt>typemaps.i</tt> file is to support primitive datatypes.
Writing a function like this
</p>
<div class="code">
<pre>
void foo(Bar *OUTPUT);
</pre>
</div>
<p>
may not have the intended effect since <tt>typemaps.i</tt> does not define an OUTPUT rule for <tt>Bar</tt>.
</p>
<H3><a name="Python_nn47">36.7.2 Simple pointers</a></H3>
<p>
If you must work with simple pointers such as <tt>int *</tt> or <tt>double *</tt> and you don't want to use
<tt>typemaps.i</tt>, consider using the <tt>cpointer.i</tt> library file. For example:
</p>
<div class="code">
<pre>
%module example
%include "cpointer.i"
%inline %{
extern void add(int x, int y, int *result);
%}
%pointer_functions(int, intp);
</pre>
</div>
<p>
The <tt>%pointer_functions(type, name)</tt> macro generates five helper functions that can be used to create,
destroy, copy, assign, and dereference a pointer. In this case, the functions are as follows:
</p>
<div class="code">
<pre>
int *new_intp();
int *copy_intp(int *x);
void delete_intp(int *x);
void intp_assign(int *x, int value);
int intp_value(int *x);
</pre>
</div>
<p>
In Python, you would use the functions like this:
</p>
<div class="targetlang">
<pre>
>>> result = new_intp()
>>> print result
_108fea8_p_int
>>> add(3, 4, result)
>>> print intp_value(result)
7
>>>
</pre>
</div>
<p>
If you replace <tt>%pointer_functions()</tt> by <tt>%pointer_class(type, name)</tt>, the interface is more class-like.
</p>
<div class="targetlang">
<pre>
>>> result = intp()
>>> add(3, 4, result)
>>> print result.value()
7
</pre>
</div>
<p>
See the <a href="Library.html#Library">SWIG Library</a> chapter for further details.
</p>
<H3><a name="Python_nn48">36.7.3 Unbounded C Arrays</a></H3>
<p>
Sometimes a C function expects an array to be passed as a pointer. For example,
</p>
<div class="code">
<pre>
int sumitems(int *first, int nitems) {
int i, sum = 0;
for (i = 0; i < nitems; i++) {
sum += first[i];
}
return sum;
}
</pre>
</div>
<p>
To wrap this into Python, you need to pass an array pointer as the first argument.
A simple way to do this is to use the <tt>carrays.i</tt> library file. For example:
</p>
<div class="code">
<pre>
%include "carrays.i"
%array_class(int, intArray);
</pre>
</div>
<p>
The <tt>%array_class(type, name)</tt> macro creates wrappers for an unbounded array object that
can be passed around as a simple pointer like <tt>int *</tt> or <tt>double *</tt>.
For instance, you will be able to do this in Python:
</p>
<div class="targetlang">
<pre>
>>> a = intArray(10000000) # Array of 10-million integers
>>> for i in xrange(10000): # Set some values
... a[i] = i
>>> sumitems(a, 10000)
49995000
>>>
</pre>
</div>
<p>
The array "object" created by <tt>%array_class()</tt> does not
encapsulate pointers inside a special array object. In fact, there is
no bounds checking or safety of any kind (just like in C). Because of
this, the arrays created by this library are extremely low-level
indeed. You can't iterate over them nor can you even query their
length. In fact, any valid memory address can be accessed if you want
(negative indices, indices beyond the end of the array, etc.).
Needless to say, this approach is not going to suit all applications.
On the other hand, this low-level approach is extremely efficient and
well suited for applications in which you need to create buffers,
package binary data, etc.
</p>
<H3><a name="Python_nn49">36.7.4 String handling</a></H3>
<p>
If a C function has an argument of <tt>char *</tt>, then a Python string
can be passed as input. For example:
</p>
<div class="code">
<pre>
// C
void foo(char *s);
</pre>
</div>
<div class="targetlang">
<pre>
# Python
>>> foo("Hello")
</pre>
</div>
<p>
When a Python string is passed as a parameter, the C function receives a pointer to the raw
data contained in the string. Since Python strings are immutable, it is illegal
for your program to change the value. In fact, doing so will probably crash the Python
interpreter.
</p>
<p>
If your program modifies the input parameter or uses it to return data, consider
using the <tt>cstring.i</tt> library file described in the <a href="Library.html#Library">SWIG Library</a> chapter.
</p>
<p>
When functions return a <tt>char *</tt>, it is assumed to be a NULL-terminated string.
Data is copied into a new Python string and returned.
</p>
<p>
If your program needs to work with binary data, you can use a typemap
to expand a Python string into a pointer/length argument pair. As luck would have it,
just such a typemap is already defined. Just do this:
</p>
<div class="code">
<pre>
%apply (char *STRING, int LENGTH) { (char *data, int size) };
...
int parity(char *data, int size, int initial);
</pre>
</div>
<p>
Now in Python:
</p>
<div class="targetlang">
<pre>
>>> parity("e\x09ffss\x00\x00\x01\nx", 0)
</pre>
</div>
<p>
If you need to return binary data, you might use the
<tt>cstring.i</tt> library file. The <tt>cdata.i</tt> library can
also be used to extra binary data from arbitrary pointers.
</p>
<H3><a name="Python_default_args">36.7.5 Default arguments</a></H3>
<p>
C++ default argument code generation is documented in the main
<a href="SWIGPlus.html#SWIGPlus_default_args">Default arguments</a> section.
There is also an optional Python specific feature that can be used called the <tt>python:cdefaultargs</tt>
<a href="Customization.html#Customization_feature_flags">feature flag</a>.
By default, SWIG attempts to convert C++ default argument values
into Python values and generates code into the Python layer containing these values.
For example:
</p>
<div class="code">
<pre>
struct CDA {
int fff(int a = 1, bool b = false);
};
</pre>
</div>
<p>
From Python this can be called as follows:
</p>
<div class="targetlang">
<pre>
>>> CDA().fff() # C++ layer receives a=1 and b=false
>>> CDA().fff(2) # C++ layer receives a=2 and b=false
>>> CDA().fff(3, True) # C++ layer receives a=3 and b=true
</pre>
</div>
<p>
The default code generation in the Python layer is:
</p>
<div class="targetlang">
<pre>
class CDA(object):
...
def fff(self, a=1, b=False):
return _default_args.CDA_fff(self, a, b)
</pre>
</div>
<p>
Adding the feature:
</p>
<div class="code">
<pre>
%feature("python:cdefaultargs") CDA::fff;
struct CDA {
int fff(int a = 1, bool b = false);
</pre>
</div>
<p>
results in identical behaviour when called from Python, however, it results in different code generation:
</p>
<div class="targetlang">
<pre>
class CDA(object):
...
def fff(self, *args):
return _default_args.CDA_fff(self, *args)
</pre>
</div>
<p>
The default arguments are obtained in the C++ wrapper layer instead of the Python layer.
Some code generation modes are quite different, eg <tt>-builtin</tt> and <tt>-fastproxy</tt>,
and are unaffected by <tt>python:cdefaultargs</tt> as the default values are always obtained from the C++ layer.
</p>
<p>
Note that not all default arguments can be converted into a Python equivalent.
When SWIG does not convert them, it will generate code to obtain them from the C++ layer as if
<tt>python:cdefaultargs</tt> was specified.
This will happen if just one argument cannot be converted into a Python equivalent.
This occurs typically when the argument is not fully numeric, such as <tt>int(1)</tt>:
</p>
<div class="code">
<pre>
struct CDA {
int fff(int a = int(1), bool b = false);
};
</pre>
</div>
<p>
<b>Compatibility Note:</b> SWIG-3.0.6 introduced the <tt>python:cdefaultargs</tt> feature.
Versions of SWIG prior to this varied in their ability to convert C++ default values into
equivalent Python default argument values.
</p>
<H2><a name="Python_nn53">36.8 Typemaps</a></H2>
<p>
This section describes how you can modify SWIG's default wrapping behavior
for various C/C++ datatypes using the <tt>%typemap</tt> directive. This
is an advanced topic that assumes familiarity with the Python C API as well
as the material in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
</p>
<p>
Before proceeding, it should be stressed that typemaps are not a required
part of using SWIG---the default wrapping behavior is enough in most cases.
Typemaps are only used if you want to change some aspect of the primitive
C-Python interface or if you want to elevate your guru status.
</p>
<H3><a name="Python_nn54">36.8.1 What is a typemap?</a></H3>
<p>
A typemap is nothing more than a code generation rule that is attached to
a specific C datatype. For example, to convert integers from Python to C,
you might define a typemap like this:
</p>
<div class="code"><pre>
%module example
%typemap(in) int {
$1 = (int) PyLong_AsLong($input);
printf("Received an integer : %d\n", $1);
}
%inline %{
extern int fact(int n);
%}
</pre></div>
<p>
Typemaps are always associated with some specific aspect of code generation.
In this case, the "in" method refers to the conversion of input arguments
to C/C++. The datatype <tt>int</tt> is the datatype to which the typemap
will be applied. The supplied C code is used to convert values. In this
code a number of special variable prefaced by a <tt>$</tt> are used. The
<tt>$1</tt> variable is placeholder for a local variable of type <tt>int</tt>.
The <tt>$input</tt> variable is the input object of type <tt>PyObject *</tt>.
</p>
<p>
When this example is compiled into a Python module, it operates as follows:
</p>
<div class="targetlang"><pre>
>>> from example import *
>>> fact(6)
Received an integer : 6
720
</pre></div>
<p>
In this example, the typemap is applied to all occurrences of the <tt>int</tt> datatype.
You can refine this by supplying an optional parameter name. For example:
</p>
<div class="code"><pre>
%module example
%typemap(in) int nonnegative {
$1 = (int) PyLong_AsLong($input);
if ($1 < 0) {
PyErr_SetString(PyExc_ValueError, "Expected a nonnegative value.");
SWIG_fail;
}
}
%inline %{
extern int fact(int nonnegative);
%}
</pre></div>
<p>
In this case, the typemap code is only attached to arguments that exactly match <tt>int nonnegative</tt>.
</p>
<p>
The application of a typemap to specific datatypes and argument names involves
more than simple text-matching--typemaps are fully integrated into the
SWIG C++ type-system. When you define a typemap for <tt>int</tt>, that typemap
applies to <tt>int</tt> and qualified variations such as <tt>const int</tt>. In addition,
the typemap system follows <tt>typedef</tt> declarations. For example:
</p>
<div class="code">
<pre>
%typemap(in) int n {
$1 = (int) PyLong_AsLong($input);
printf("n = %d\n", $1);
}
%inline %{
typedef int Integer;
extern int fact(Integer n); // Above typemap is applied
%}
</pre>
</div>
<p>
Typemaps can also be defined for groups of consecutive arguments. For example:
</p>
<div class="code">
<pre>
%typemap(in) (char *str, int len) {
$1 = PyString_AsString($input);
$2 = PyString_Size($input);
};
int count(char c, char *str, int len);
</pre>
</div>
<p>
When a multi-argument typemap is defined, the arguments are always handled as a single
Python object. This allows the function to be used like this (notice how the length
parameter is omitted):
</p>
<div class="targetlang">
<pre>
>>> example.count('e', 'Hello World')
1
>>>
</pre>
</div>
<H3><a name="Python_nn55">36.8.2 Python typemaps</a></H3>
<p>
The previous section illustrated an "in" typemap for converting Python objects to C.
A variety of different typemap methods are defined by the Python module. For example,
to convert a C integer back into a Python object, you might define an "out" typemap
like this:
</p>
<div class="code">
<pre>
%typemap(out) int {
$result = PyInt_FromLong((long) $1);
}
</pre>
</div>
<p>
A detailed list of available methods can be found in the "<a
href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
</p>
<p>
However, the best source of typemap information (and examples) is
probably the Python module itself. In fact, all of SWIG's default
type handling is defined by typemaps. You can view these typemaps by
looking at the files in the SWIG library. Just take into account that
in the latest versions of swig (1.3.22+), the library files are not
very pristine clear for the casual reader, as they used to be. The
extensive use of macros and other ugly techniques in the latest
version produce a very powerful and consistent python typemap library,
but at the cost of simplicity and pedagogic value.
</p>
<p>
To learn how to write a simple or your first typemap, you better take
a look at the SWIG library version 1.3.20 or so.
</p>
<H3><a name="Python_nn56">36.8.3 Typemap variables</a></H3>
<p>
Within typemap code, a number of special variables prefaced with a <tt>$</tt> may appear.
A full list of variables can be found in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
This is a list of the most common variables:
</p>
<p>
<tt>$1</tt>
</p>
<div class="indent">
A C local variable corresponding to the actual type specified in the
<tt>%typemap</tt> directive. For input values, this is a C local variable
that's supposed to hold an argument value. For output values, this is
the raw result that's supposed to be returned to Python.
</div>
<p>
<tt>$input</tt>
</p>
<div class="indent">
A <tt>PyObject *</tt> holding a raw Python object with an argument or variable value.
</div>
<p>
<tt>$result</tt>
</p>
<div class="indent">
A <tt>PyObject *</tt> that holds the result to be returned to Python.
</div>
<p>
<tt>$1_name</tt>
</p>
<div class="indent">
The parameter name that was matched.
</div>
<p>
<tt>$1_type</tt>
</p>
<div class="indent">
The actual C datatype matched by the typemap.
</div>
<p>
<tt>$1_ltype</tt>
</p>
<div class="indent">
An assignable version of the datatype matched by the typemap (a type that can appear on the left-hand-side of
a C assignment operation). This type is stripped of qualifiers and may be an altered version of <tt>$1_type</tt>.
All arguments and local variables in wrapper functions are declared using this type so that their values can be
properly assigned.
</div>
<p>
<tt>$symname</tt>
</p>
<div class="indent">
The Python name of the wrapper function being created.
</div>
<H3><a name="Python_nn57">36.8.4 Useful Python Functions</a></H3>
<p>
When you write a typemap, you usually have to work directly with Python objects.
The following functions may prove to be useful.
</p>
<p>
<b>Python Integer Functions</b>
</p>
<div class="code">
<pre>
PyObject *PyInt_FromLong(long l);
long PyInt_AsLong(PyObject *);
int PyInt_Check(PyObject *);
</pre>
</div>
<p>
<b>Python Floating Point Functions</b>
</p>
<div class="code">
<pre>
PyObject *PyFloat_FromDouble(double);
double PyFloat_AsDouble(PyObject *);
int PyFloat_Check(PyObject *);
</pre>
</div>
<p>
<b>Python String Functions</b>
</p>
<div class="code">
<pre>
PyObject *PyString_FromString(char *);
PyObject *PyString_FromStringAndSize(char *, lint len);
int PyString_Size(PyObject *);
char *PyString_AsString(PyObject *);
int PyString_Check(PyObject *);
</pre>
</div>
<p>
<b>Python List Functions</b>
</p>
<div class="code">
<pre>
PyObject *PyList_New(int size);
int PyList_Size(PyObject *list);
PyObject *PyList_GetItem(PyObject *list, int i);
int PyList_SetItem(PyObject *list, int i, PyObject *item);
int PyList_Insert(PyObject *list, int i, PyObject *item);
int PyList_Append(PyObject *list, PyObject *item);
PyObject *PyList_GetSlice(PyObject *list, int i, int j);
int PyList_SetSlice(PyObject *list, int i, int , PyObject *list2);
int PyList_Sort(PyObject *list);
int PyList_Reverse(PyObject *list);
PyObject *PyList_AsTuple(PyObject *list);
int PyList_Check(PyObject *);
</pre>
</div>
<p>
<b>Python Tuple Functions</b>
</p>
<div class="code">
<pre>
PyObject *PyTuple_New(int size);
int PyTuple_Size(PyObject *);
PyObject *PyTuple_GetItem(PyObject *, int i);
int PyTuple_SetItem(PyObject *, int i, PyObject *item);
PyObject *PyTuple_GetSlice(PyObject *t, int i, int j);
int PyTuple_Check(PyObject *);
</pre>
</div>
<p>
<b>Python Dictionary Functions</b>
</p>
<div class="code">
<pre>
PyObject *PyDict_New();
int PyDict_Check(PyObject *);
int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val);
int PyDict_SetItemString(PyObject *p, const char *key, PyObject *val);
int PyDict_DelItem(PyObject *p, PyObject *key);
int PyDict_DelItemString(PyObject *p, char *key);
PyObject* PyDict_Keys(PyObject *p);
PyObject* PyDict_Values(PyObject *p);
PyObject* PyDict_GetItem(PyObject *p, PyObject *key);
PyObject* PyDict_GetItemString(PyObject *p, const char *key);
int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue);
Py_ssize_t PyDict_Size(PyObject *p);
int PyDict_Update(PyObject *a, PyObject *b);
int PyDict_Merge(PyObject *a, PyObject *b, int override);
PyObject* PyDict_Items(PyObject *p);
</pre>
</div>
<p>
<b>Python File Conversion Functions</b>
</p>
<div class="code">
<pre>
PyObject *PyFile_FromFile(FILE *f);
FILE *PyFile_AsFile(PyObject *);
int PyFile_Check(PyObject *);
</pre>
</div>
<p>
<b>Abstract Object Interface</b>
</p>
<div class="code">
<pre>
write me
</pre>
</div>
<H2><a name="Python_nn58">36.9 Typemap Examples</a></H2>
<p>
This section includes a few examples of typemaps. For more examples, you
might look at the files "<tt>python.swg</tt>" and "<tt>typemaps.i</tt>" in
the SWIG library.
</p>
<H3><a name="Python_nn59">36.9.1 Converting Python list to a char ** </a></H3>
<p>
A common problem in many C programs is the processing of command line
arguments, which are usually passed in an array of NULL terminated
strings. The following SWIG interface file allows a Python list
object to be used as a <tt>char **</tt> object.
</p>
<div class="code"><pre>
%module argv
// This tells SWIG to treat char ** as a special case
%typemap(in) char ** {
/* Check if is a list */
if (PyList_Check($input)) {
int size = PyList_Size($input);
int i = 0;
$1 = (char **) malloc((size+1)*sizeof(char *));
for (i = 0; i < size; i++) {
PyObject *o = PyList_GetItem($input, i);
if (PyString_Check(o)) {
$1[i] = PyString_AsString(PyList_GetItem($input, i));
} else {
free($1);
PyErr_SetString(PyExc_TypeError, "list must contain strings");
SWIG_fail;
}
}
$1[i] = 0;
} else {
PyErr_SetString(PyExc_TypeError, "not a list");
SWIG_fail;
}
}
// This cleans up the char ** array we malloc'd before the function call
%typemap(freearg) char ** {
free((char *) $1);
}
// Now a test function
%inline %{
int print_args(char **argv) {
int i = 0;
while (argv[i]) {
printf("argv[%d] = %s\n", i, argv[i]);
i++;
}
return i;
}
%}
</pre></div>
<p>
When this module is compiled, the wrapped C function now operates as
follows :
</p>
<div class="targetlang"><pre>
>>> from argv import *
>>> print_args(["Dave", "Mike", "Mary", "Jane", "John"])
argv[0] = Dave
argv[1] = Mike
argv[2] = Mary
argv[3] = Jane
argv[4] = John
5
</pre></div>
<p>
In the example, two different typemaps are used. The "in" typemap is
used to receive an input argument and convert it to a C array. Since dynamic
memory allocation is used to allocate memory for the array, the
"freearg" typemap is used to later release this memory after the execution of
the C function.
</p>
<H3><a name="Python_nn60">36.9.2 Expanding a Python object into multiple arguments</a></H3>
<p>
Suppose that you had a collection of C functions with arguments
such as the following:
</p>
<div class="code">
<pre>
int foo(int argc, char **argv);
</pre>
</div>
<p>
In the previous example, a typemap was written to pass a Python list as the <tt>char **argv</tt>. This
allows the function to be used from Python as follows:
</p>
<div class="targetlang">
<pre>
>>> foo(4, ["foo", "bar", "spam", "1"])
</pre>
</div>
<p>
Although this works, it's a little awkward to specify the argument count. To fix this, a multi-argument
typemap can be defined. This is not very difficult--you only have to make slight modifications to the
previous example:
</p>
<div class="code">
<pre>
%typemap(in) (int argc, char **argv) {
/* Check if is a list */
if (PyList_Check($input)) {
int i;
$1 = PyList_Size($input);
$2 = (char **) malloc(($1+1)*sizeof(char *));
for (i = 0; i < $1; i++) {
PyObject *o = PyList_GetItem($input, i);
if (PyString_Check(o)) {
$2[i] = PyString_AsString(PyList_GetItem($input, i));
} else {
free($2);
PyErr_SetString(PyExc_TypeError, "list must contain strings");
SWIG_fail;
}
}
$2[i] = 0;
} else {
PyErr_SetString(PyExc_TypeError, "not a list");
SWIG_fail;
}
}
%typemap(freearg) (int argc, char **argv) {
free((char *) $2);
}
</pre>
</div>
<p>
When writing a multiple-argument typemap, each of the types is referenced by a variable such
as <tt>$1</tt> or <tt>$2</tt>. The typemap code simply fills in the appropriate values from
the supplied Python object.
</p>
<p>
With the above typemap in place, you will find it no longer necessary
to supply the argument count. This is automatically set by the typemap code. For example:
</p>
<div class="targetlang">
<pre>
>>> foo(["foo", "bar", "spam", "1"])
</pre>
</div>
<p>
If your function is overloaded in C++, for example:
</p>
<div class="code">
<pre>
int foo(int argc, char **argv);
int foo();
</pre>
</div>
<p>
don't forget to also provide a suitable <a href="Typemaps.html#Typemaps_overloading">typecheck typemap for overloading</a>
such as:
</p>
<div class="code">
<pre>
%typecheck(SWIG_TYPECHECK_STRING_ARRAY) (int argc, char **argv) {
$1 = PyList_Check($input) ? 1 : 0;
}
</pre>
</div>
<p>
If you don't you'll get an error message along the lines of:
</p>
<div class="shell">
<pre>
Traceback (most recent call last):
File "runme.py", line 3, in >module<
example.foo(["foo", "bar", "spam", "1"])
NotImplementedError: Wrong number or type of arguments for overloaded function 'foo'.
Possible C/C++ prototypes are:
foo(int, char **)
foo()
</pre>
</div>
<H3><a name="Python_nn61">36.9.3 Using typemaps to return arguments</a></H3>
<p>
A common problem in some C programs is that values may be returned in
arguments rather than in the return value of a function. For example:
</p>
<div class="code"><pre>
/* Returns a status value and two values in out1 and out2 */
int spam(double a, double b, double *out1, double *out2) {
... Do a bunch of stuff ...
*out1 = result1;
*out2 = result2;
return status;
}
</pre></div>
<p>
A typemap can be used to handle this case as follows :
</p>
<div class="code"><pre>
%module outarg
// This tells SWIG to treat an double * argument with name 'OutValue' as
// an output value. We'll append the value to the current result which
// is guaranteed to be a List object by SWIG.
%typemap(argout) double *OutValue {
PyObject *o, *o2, *o3;
o = PyFloat_FromDouble(*$1);
if ((!$result) || ($result == Py_None)) {
$result = o;
} else {
if (!PyTuple_Check($result)) {
PyObject *o2 = $result;
$result = PyTuple_New(1);
PyTuple_SetItem($result, 0, o2);
}
o3 = PyTuple_New(1);
PyTuple_SetItem(o3, 0, o);
o2 = $result;
$result = PySequence_Concat(o2, o3);
Py_DECREF(o2);
Py_DECREF(o3);
}
}
int spam(double a, double b, double *OutValue, double *OutValue);
</pre></div>
<p>
The typemap works as follows. First, a check is made to see if any previous result
exists. If so, it is turned into a tuple and the new output value is concatenated to it.
Otherwise, the result is returned normally. For the sample function <tt>spam()</tt>, there
are three output values--meaning that the function will return a 3-tuple of the results.
</p>
<p>
As written, the function must accept 4 arguments as input values,
last two being pointers to doubles. If these arguments are only used to hold output values (and have
no meaningful input value), an additional typemap can be written. For example:
</p>
<div class="code"><pre>
%typemap(in, numinputs=0) double *OutValue(double temp) {
$1 = &temp;
}
</pre></div>
<p>
By specifying numinputs=0, the input value is ignored. However, since the argument still has to be set to
some meaningful value before calling C, it is set to point to a local variable <tt>temp</tt>. When the function
stores its output value, it will simply be placed in this local variable. As a result, the
function can now be used as follows:
</p>
<div class="targetlang"><pre>
>>> a = spam(4, 5)
>>> print a
(0, 2.45, 5.0)
>>> x, y, z = spam(4, 5)
>>>
</pre></div>
<H3><a name="Python_nn62">36.9.4 Mapping Python tuples into small arrays</a></H3>
<p>
In some applications, it is sometimes desirable to pass small arrays
of numbers as arguments. For example :
</p>
<div class="code"><pre>
extern void set_direction(double a[4]); // Set direction vector
</pre></div>
<p>
This too, can be handled used typemaps as follows :
</p>
<div class="code"><pre>
// Grab a 4 element array as a Python 4-tuple
%typemap(in) double[4](double temp[4]) { // temp[4] becomes a local variable
int i;
if (PyTuple_Check($input)) {
if (!PyArg_ParseTuple($input, "dddd", temp, temp+1, temp+2, temp+3)) {
PyErr_SetString(PyExc_TypeError, "tuple must have 4 elements");
SWIG_fail;
}
$1 = &temp[0];
} else {
PyErr_SetString(PyExc_TypeError, "expected a tuple.");
SWIG_fail;
}
}
</pre></div>
<p>
This allows our <tt>set_direction</tt> function to be called from
Python as follows :
</p>
<div class="targetlang"><pre>
>>> set_direction((0.5, 0.0, 1.0, -0.25))
</pre></div>
<p>
Since our mapping copies the contents of a Python tuple into a C
array, such an approach would not be recommended for huge arrays, but
for small structures, this approach works fine.
</p>
<H3><a name="Python_nn63">36.9.5 Mapping sequences to C arrays</a></H3>
<p>
Suppose that you wanted to generalize the previous example to handle C
arrays of different sizes. To do this, you might write a typemap as follows:
</p>
<div class="code"><pre>
// Map a Python sequence into any sized C double array
%typemap(in) double[ANY](double temp[$1_dim0]) {
int i;
if (!PySequence_Check($input)) {
PyErr_SetString(PyExc_TypeError, "Expecting a sequence");
SWIG_fail;
}
if (PyObject_Length($input) != $1_dim0) {
PyErr_SetString(PyExc_ValueError, "Expecting a sequence with $1_dim0 elements");
SWIG_fail;
}
for (i =0; i < $1_dim0; i++) {
PyObject *o = PySequence_GetItem($input, i);
if (!PyFloat_Check(o)) {
Py_XDECREF(o);
PyErr_SetString(PyExc_ValueError, "Expecting a sequence of floats");
SWIG_fail;
}
temp[i] = PyFloat_AsDouble(o);
Py_DECREF(o);
}
$1 = &temp[0];
}
</pre>
</div>
<p>
In this case, the variable <tt>$1_dim0</tt> is expanded to match the
array dimensions actually used in the C code. This allows the typemap
to be applied to types such as:
</p>
<div class="code">
<pre>
void foo(double x[10]);
void bar(double a[4], double b[8]);
</pre>
</div>
<p>
Since the above typemap code gets inserted into every wrapper function where used, it might make sense
to use a helper function instead. This will greatly reduce the amount of wrapper code. For example:
</p>
<div class="code">
<pre>
%{
static int convert_darray(PyObject *input, double *ptr, int size) {
int i;
if (!PySequence_Check(input)) {
PyErr_SetString(PyExc_TypeError, "Expecting a sequence");
return 0;
}
if (PyObject_Length(input) != size) {
PyErr_SetString(PyExc_ValueError, "Sequence size mismatch");
return 0;
}
for (i =0; i < size; i++) {
PyObject *o = PySequence_GetItem(input, i);
if (!PyFloat_Check(o)) {
Py_XDECREF(o);
PyErr_SetString(PyExc_ValueError, "Expecting a sequence of floats");
return 0;
}
ptr[i] = PyFloat_AsDouble(o);
Py_DECREF(o);
}
return 1;
}
%}
%typemap(in) double [ANY](double temp[$1_dim0]) {
if (!convert_darray($input, temp, $1_dim0)) {
SWIG_fail;
}
$1 = &temp[0];
}
</pre>
</div>
<H3><a name="Python_nn64">36.9.6 Pointer handling</a></H3>
<p>
Occasionally, it might be necessary to convert pointer values that have
been stored using the SWIG typed-pointer representation. Since there are
several ways in which pointers can be represented, the following two
functions are used to safely perform this conversion:
</p>
<p>
<tt>
int SWIG_ConvertPtr(PyObject *obj, void **ptr, swig_type_info *ty, int flags)</tt>
</p>
<div class="indent">
Converts a Python object <tt>obj</tt> to a C pointer. The result of the conversion is placed
into the pointer located at <tt>ptr</tt>. <tt>ty</tt> is a SWIG type descriptor structure.
<tt>flags</tt> is used to handle error checking and other aspects of conversion. It is the
bitwise-or of several flag values including <tt>SWIG_POINTER_EXCEPTION</tt> and
<tt>SWIG_POINTER_DISOWN</tt>. The first flag makes the function raise an exception on type
error. The second flag additionally
steals ownership of an object. Returns 0 on success and -1 on error.
</div>
<p>
<tt>
PyObject *SWIG_NewPointerObj(void *ptr, swig_type_info *ty, int own)</tt>
</p>
<div class="indent">
Creates a new Python pointer object. <tt>ptr</tt> is the pointer to convert, <tt>ty</tt> is the SWIG type descriptor structure that
describes the type, and <tt>own</tt> is a flag that indicates whether or not Python should take ownership of the
pointer.
</div>
<p>
Both of these functions require the use of a special SWIG
type-descriptor structure. This structure contains information about
the mangled name of the datatype, type-equivalence information, as
well as information about converting pointer values under C++
inheritance. For a type of <tt>Foo *</tt>, the type descriptor structure
is usually accessed as follows:
</p>
<div class="code">
<pre>
Foo *f;
if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &f, SWIGTYPE_p_Foo, 0))) {
SWIG_exception_fail(SWIG_TypeError, "in method '$symname', expecting type Foo");
}
PyObject *obj;
obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
</pre>
</div>
<p>
In a typemap, the type descriptor should always be accessed using the special typemap
variable <tt>$1_descriptor</tt>. For example:
</p>
<div class="code">
<pre>
%typemap(in) Foo * {
if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor, 0))) {
SWIG_exception_fail(SWIG_TypeError, "in method '$symname', expecting type Foo");
}
}
</pre>
</div>
<p>
If necessary, the descriptor for any type can be obtained using the <tt>$descriptor()</tt> macro in a typemap.
For example:
</p>
<div class="code">
<pre>
%typemap(in) Foo * {
if (!SWIG_IsOK(SWIG_ConvertPtr($input, (void **) &$1, $descriptor(Foo *), 0))) {
SWIG_exception_fail(SWIG_TypeError, "in method '$symname', expecting type Foo");
}
}
</pre>
</div>
<p>
Although the pointer handling functions are primarily intended for
manipulating low-level pointers, both functions are fully aware of
Python proxy classes. Specifically,
<tt>SWIG_ConvertPtr()</tt> will retrieve a pointer from any object
that has a <tt>this</tt> attribute. In addition,
<tt>SWIG_NewPointerObj()</tt> can automatically generate a proxy
class object (if applicable).
</p>
<H2><a name="Python_nn65">36.10 Docstring Features</a></H2>
<p>
Using docstrings in Python code is becoming more and more important
and more tools are coming on the scene that take advantage of them,
everything from full-blown documentation generators to class browsers
and popup call-tips in Python-aware IDEs. Given the way that SWIG
generates the proxy code by default, your users will normally get
something like <tt>"function_name(*args)"</tt> in the popup calltip of
their IDE which is next to useless when the real function prototype
might be something like this:
</p>
<div class="code">
<pre>
bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
</pre>
</div>
<p>
The features described in this section make it easy for you to add
docstrings to your modules, functions and methods that can then be
used by the various tools out there to make the programming experience
of your users much simpler.
</p>
<H3><a name="Python_nn66">36.10.1 Module docstring</a></H3>
<p>
Python allows a docstring at the beginning of the <tt>.py</tt> file
before any other statements, and it is typically used to give a
general description of the entire module. SWIG supports this by
setting an option of the <tt>%module</tt> directive. For example:
</p>
<div class="code">
<pre>
%module(docstring="This is the example module's docstring") example
</pre>
</div>
<p>
When you have more than just a line or so then you can retain the easy
readability of the <tt>%module</tt> directive by using a macro. For
example:
</p>
<div class="code">
<pre>
%define DOCSTRING
"The `XmlResource` class allows program resources defining menus,
layout of controls on a panel, etc. to be loaded from an XML file."
%enddef
%module(docstring=DOCSTRING) xrc
</pre>
</div>
<H3><a name="Python_nn67">36.10.2 %feature("autodoc")</a></H3>
<p>
As alluded to above SWIG will generate all the function and method
proxy wrappers with just "*args" (or "*args, **kwargs" if the -keyword
option is used) for a parameter list and will then sort out the
individual parameters in the C wrapper code. This is nice and simple
for the wrapper code, but makes it difficult to be programmer and tool
friendly as anyone looking at the <tt>.py</tt> file will not be able
to find out anything about the parameters that the functions accept.
</p>
<p>But since SWIG does know everything about the function it is
possible to generate a docstring containing the parameter types, names
and default values. Since many of the docstring tools are adopting a
standard of recognizing if the first thing in the docstring is a
function prototype then using that instead of what they found from
introspection, then life is good once more.
<p>SWIG's Python module provides support for the "autodoc" feature,
which when attached to a node in the parse tree will cause a docstring
to be generated that includes the name of the function, parameter
names, default values if any, and return type if any. There are also
four levels for autodoc controlled by the value given to the
feature, <tt>%feature("autodoc", "<i>level</i>")</tt>.
The four values for <i>level</i> are covered in the following sub-sections.
<H4><a name="Python_nn68">36.10.2.1 %feature("autodoc", "0")</a></H4>
<p>
When level "0" is used then the types of the parameters will
<em>not</em> be included in the autodoc string. For example, given
this function prototype:
</p>
<div class="code">
<pre>
%feature("autodoc", "0");
bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
</pre>
</div>
<p>
Then Python code like this will be generated:
</p>
<div class="targetlang">
<pre>
def function_name(*args, **kwargs):
"""function_name(x, y, foo=None, bar=None) -> bool"""
...
</pre>
</div>
<H4><a name="Python_nn69">36.10.2.2 %feature("autodoc", "1")</a></H4>
<p>
When level "1" is used then the parameter types <em>will</em> be
used in the autodoc string. In addition, an attempt is made to
simplify the type name such that it makes more sense to the Python
user. Pointer, reference and const info is removed if the associated type
is has an associated Python type (<tt>%rename</tt>'s are thus shown correctly).
This works most of the time, otherwise a C/C++ type will be used.
See the next section for the "docstring" feature for tweaking the docstrings to your liking.
Given the example above, then turning on the
parameter types with level "1" will result in Python code like
this:
</p>
<div class="targetlang">
<pre>
def function_name(*args, **kwargs):
"""function_name(int x, int y, Foo foo=None, Bar bar=None) -> bool"""
...
</pre>
</div>
<H4><a name="Python_autodoc2">36.10.2.3 %feature("autodoc", "2")</a></H4>
<p>
Level "2" results in the function prototype as per level "0". In addition, a line of
documentation is generated for each parameter using <a href="https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt">numpydoc</a> style.
Using the previous example, the generated code will be:
</p>
<div class="targetlang">
<pre>
def function_name(*args, **kwargs):
"""
function_name(x, y, foo=None, bar=None) -> bool
Parameters
----------
x: int
y: int
foo: Foo *
bar: Bar *
"""
...
</pre>
</div>
<p>
Note that the documentation for each parameter is sourced from the "doc" typemap which by default shows the
C/C++ type rather than the simplified Python type name described earlier for level "1".
Typemaps can of course change the output for any particular type, for example the <tt>int x</tt> parameter:
</p>
<div class="code">
<pre>
%feature("autodoc", "2");
%typemap("doc") int x "$1_name (C++ type: $1_type) -- Input $1_name dimension"
bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
</pre>
</div>
<p>
resulting in
</p>
<div class="targetlang">
<pre>
def function_name(*args, **kwargs):
"""
function_name(x, y, foo=None, bar=None) -> bool
Parameters
----------
x (C++ type: int) -- Input x dimension
y: int
foo: Foo *
bar: Bar *
"""
</pre>
</div>
<H4><a name="Python_autodoc3">36.10.2.4 %feature("autodoc", "3")</a></H4>
<p>
Level "3" results in the function prototype as per level "1" but also contains the same additional line of documentation for each parameter as per level "2". Using our earlier example again, the generated code will be:
</p>
<div class="targetlang">
<pre>
def function_name(*args, **kwargs):
"""
function_name(int x, int y, Foo foo=None, Bar bar=None) -> bool
Parameters
----------
x: int
y: int
foo: Foo *
bar: Bar *
"""
...
</pre>
</div>
<H4><a name="Python_nn70">36.10.2.5 %feature("autodoc", "docstring")</a></H4>
<p>
Finally, there are times when the automatically generated autodoc
string will make no sense for a Python programmer, particularly when a
typemap is involved. So if you give an explicit value for the autodoc
feature then that string will be used in place of the automatically
generated string. For example:
</p>
<div class="code">
<pre>
%feature("autodoc", "GetPosition() -> (x, y)") GetPosition;
void GetPosition(int* OUTPUT, int* OUTPUT);
</pre>
</div>
<H3><a name="Python_nn71">36.10.3 %feature("docstring")</a></H3>
<p>
In addition to the autodoc strings described above, you can also
attach any arbitrary descriptive text to a node in the parse tree with
the "docstring" feature. When the proxy module is generated then any
docstring associated with classes, function or methods are output.
If an item already has an autodoc string then it is combined with the
docstring and they are output together. If the docstring is all on a
single line then it is output like this::
</p>
<div class="targetlang">
<pre>
"""This is the docstring"""
</pre>
</div>
<p>
Otherwise, to aid readability it is output like this:
</p>
<div class="targetlang">
<pre>
"""
This is a multi-line docstring
with more than one line.
"""
</pre>
</div>
<H2><a name="Python_nn72">36.11 Python Packages</a></H2>
<p>Python has concepts of modules and packages. Modules are separate units of
code and may be grouped together to form a package. Packages may be nested,
that is they may contain subpackages. This leads to tree-like hierarchy, with
packages as intermediate nodes and modules as leaf nodes.</p>
<p>The hierarchy of Python packages/modules follows the hierarchy of
<tt>*.py</tt> files found in a source tree (or, more generally, in the Python path).
Normally, the developer creates new module by placing a <tt>*.py</tt> file
somewhere under Python path; the module is then named after that <tt>*.py</tt>
file. A package is created by placing an <tt>__init__.py</tt> file within a
directory; the package is then named after that directory. For example, the
following source tree:</p>
<div class="diagram">
<pre>
mod1.py
pkg1/__init__.py
pkg1/mod2.py
pkg1/pkg2/__init__.py
pkg1/pkg2/mod3.py
</pre>
</div>
<p>
defines the following Python packages and modules:
</p>
<div class="diagram">
<pre>
pkg1 # package
pkg1.pkg2 # package
mod1 # module
pkg1.mod2 # module
pkg1.pkg2.mod3 # module
</pre>
</div>
<p>
The purpose of an <tt>__init__.py</tt> file is two-fold. First, the existence of
<tt>__init__.py</tt> in a directory informs the Python interpreter that this
directory contains a Python package. Second, the code in <tt>__init__.py</tt> is
loaded/executed automatically when the package is initialized (when it or its
submodule/subpackage gets <tt>import</tt>'ed). By default, SWIG generates
proxy Python code – one <tt>*.py</tt> file for each <tt>*.i</tt>
interface. The <tt>__init__.py</tt> files, however, are not generated by SWIG.
They should be created by other means. Both files (module <tt>*.py</tt> and
<tt>__init__.py</tt>) should be installed in appropriate destination
directories in order to obtain a desirable package/module hierarchy.
</p>
<p>
Python3 adds another option for packages with
<a href="https://www.python.org/dev/peps/pep-0420/">PEP 0420</a> (implicit
namespace packages). Implicit namespace packages no longer use
__init__.py files. SWIG generated Python modules support implicit
namespace packages. See
<a href="#Python_implicit_namespace_packages">36.11.5 Implicit Namespace
Packages</a> for more information.
</p>
<p>
If you place a SWIG generated module into a Python package then there
are details concerning the way SWIG
<a href="#Python_package_search">searches for the wrapper module</a>
that you may want to familiarize yourself with.
</p>
<p>The way Python defines its modules and packages impacts SWIG users. Some
users may need to use special features such as the <tt>package</tt> option in the
<tt>%module</tt> directive or import related command line options. These are
explained in the following sections.</p>
<H3><a name="Python_modulepackage">36.11.1 Setting the Python package</a></H3>
<p>
Using the <tt>package</tt> option in the <tt>%module</tt> directive allows you
to specify a Python package that the module will be in when installed.
</p>
<div class="code">
<pre>
%module(package="wx") xrc
</pre>
</div>
<p>
This is useful when the <tt>.i</tt> file is <tt>%import</tt>ed by
another <tt>.i</tt> file. By default SWIG will assume that the
importer is able to find the importee with just the module name, but
if they live in separate Python packages then this won't work.
However if the importee specifies what its package is with the
<tt>%module</tt> option then the Python code generated for the
importer will use that package name when importing the other module
and in base class declarations, etc..
</p>
<p>SWIG assumes that the <tt>package</tt> option provided to <tt>%module</tt>
together with the <tt>module</tt> name (that is, <tt>wx.xrc</tt> in the above
example) forms a fully qualified (absolute) name of a module (in Python terms).
This is important especially for Python 3, where absolute imports are used by
default. It's up to you to place the generated module files (<tt>.py</tt>,
<tt>.so</tt>) in appropriate subdirectories. For example, if you have an
interface file <tt>foo.i</tt> with:
</p>
<div class="code">
<pre>
%module(package="pkg1.pkg2") foo
</pre>
</div>
<p>
then the resulting directory layout should be
</p>
<div class="diagram">
<pre>
pkg1/
pkg1/__init__.py
pkg1/pkg2/__init__.py
pkg1/pkg2/foo.py # (generated by SWIG)
pkg1/pkg2/_foo.so # (shared library built from C/C++ code generated by SWIG)
</pre>
</div>
<H3><a name="Python_absrelimports">36.11.2 Absolute and relative imports</a></H3>
<p>Suppose, we have the following hierarchy of files:</p>
<div class="diagram">
<pre>
pkg1/
pkg1/__init__.py
pkg1/mod2.py
pkg1/pkg2/__init__.py
pkg1/pkg2/mod3.py
</pre>
</div>
<p>Let the contents of <tt>pkg1/pkg2/mod3.py</tt> be</p>
<div class="targetlang">
<pre>
class M3: pass
</pre>
</div>
<p>
We edit <tt>pkg1/mod2.py</tt> and want to import module
<tt>pkg1/pkg2/mod3.py</tt> in order to derive from class <tt>M3</tt>. We can
write appropriate Python code in several ways, for example:
</p>
<ol>
<li><p>Using "<tt>import <></tt>" syntax with absolute package name:</p>
<div class="targetlang">
<pre>
# pkg1/mod2.py
import pkg1.pkg2.mod3
class M2(pkg1.pkg2.mod3.M3): pass
</pre>
</div>
</li>
<li><p>Using "<tt>import <></tt>" syntax with package name relative to
<tt>pkg1</tt> (only in Python 2.7 and earlier):</p>
<div class="targetlang">
<pre>
# pkg1/mod2.py
import pkg2.mod3
class M2(pkg2.mod3.M3): pass
</pre>
</div>
</li>
<li><p>Using "<tt>from <> import <></tt>" syntax (relative import
syntax, only in Python 2.5 and later):</p>
<div class="targetlang">
<pre>
# pkg1/mod2.py
from .pkg2 import mod3
class M2(mod3.M3): pass
</pre>
</div>
</li>
<li><p>Other variants, for example the following construction in order to
have the <tt>pkg2.mod3.M3</tt> symbol available in <tt>mod2</tt> as
in point 2 above (but now under Python 3):</p>
<div class="targetlang">
<pre>
# pkg1/mod2.py
from . import pkg2
from .pkg2 import mod3
class M2(pkg2.mod3.M3): pass
</pre>
</div>
</li>
</ol>
<p>Now suppose we have <tt>mod2.i</tt> with</p>
<div class="code">
<pre>
// mod2.i
%module (package="pkg1") mod2
%import "mod3.i"
// ...
</pre>
</div>
<p>and <tt>mod3.i</tt> with</p>
<div class="code">
<pre>
// mod3.i
%module (package="pkg1.pkg2") mod3
// ...
</pre>
</div>
<p>By default, SWIG would generate <tt>mod2.py</tt> proxy file with
<tt>import</tt> directive as in point 1. This can be changed with the
<tt>-relativeimport</tt> command line option. The <tt>-relativeimport</tt> instructs
SWIG to organize imports as in point 2 (for Python < 2.7.0) or as in point 4
for Python 2.7.0 and newer. This is a check done at the time the module is
imported. In short, if you have
<tt>mod2.i</tt> and <tt>mod3.i</tt> as above, then without
<tt>-relativeimport</tt> SWIG will write</p>
<div class="targetlang">
<pre>
import pkg1.pkg2.mod3
</pre>
</div>
<p>to <tt>mod2.py</tt> proxy file, and with <tt>-relativeimport</tt> it will
write</p>
<div class="targetlang">
<pre>
from sys import version_info
if version_info >= (2, 7, 0):
from . import pkg2
import pkg1.pkg2.mod3
else:
import pkg2.mod3
del version_info
</pre>
</div>
<p>You should avoid using relative imports and use absolute ones whenever
possible. There are some cases, however, when relative imports may be
necessary. The first example is, when some (legacy) Python code refers entities
imported by proxy files generated by SWIG, and it assumes that the proxy file
uses relative imports. Second case is, when one puts import directives in
<tt>__init__.py</tt> to import symbols from submodules or subpackages and the
submodule depends on other submodules (discussed later).</p>
<H3><a name="Python_absimport">36.11.3 Enforcing absolute import semantics</a></H3>
<p>As you may know, there is an incompatibility in import semantics (for the
<tt>import <></tt> syntax) between Python 2 and 3. In Python 2.4 and
earlier it is not clear whether</p>
<div class="targetlang">
<pre>
import foo
</pre>
</div>
<p>refers to a top-level module or to another module inside the current
package. In Python 3 it always refers to a top-level module
(see <a href="https://www.python.org/dev/peps/pep-0328/">PEP 328</a>).
To instruct Python 2.5 through 2.7 to use new semantics (that is <tt>import
foo</tt> is interpreted as absolute import), one has to put the following
line
</p>
<div class="targetlang">
<pre>
from __future__ import absolute_import
</pre>
</div>
<p>at the very beginning of his proxy <tt>*.py</tt> file. In SWIG, it may be
accomplished with <tt>%pythonbegin</tt> directive as follows:</p>
<div class="code">
<pre>
%pythonbegin %{
from __future__ import absolute_import
%}
</pre>
</div>
<H3><a name="Python_importfrominit">36.11.4 Importing from __init__.py</a></H3>
<p>Imports in <tt>__init__.py</tt> are handy when you want to populate a
package's namespace with names imported from other modules. In SWIG based
projects this approach may also be used to split large pieces of code into
smaller modules, compile them in parallel and then re-assemble everything at
runtime by importing submodules' contents in <tt>__init__.py</tt>, for
example.</p>
<p>Unfortunately import directives in <tt>__init__.py</tt> may cause problems,
especially if they refer to a package's submodules. This is caused by the way
Python initializes packages. If you spot problems with imports from
<tt>__init__.py</tt> try using <tt>-relativeimport</tt> option. Below we
explain in detail one issue, for which the <tt>-relativeimport</tt> workaround
may be helpful.</p>
<p>Consider the following example (Python 3):</p>
<div class="diagram">
<pre>
pkg1/__init__.py # (empty)
pkg1/pkg2/__init__.py # (imports something from bar.py)
pkg1/pkg2/foo.py
pkg1/pkg2/bar.py # (imports foo.py)
</pre>
</div>
<p>If the file contents are:</p>
<ul>
<li> <p><tt>pkg1/pkg2/__init__.py:</tt></p>
<div class="targetlang">
<pre>
# pkg1/pkg2/__init__.py
from .bar import Bar
</pre>
</div>
</li>
<li> <p><tt>pkg1/pkg2/foo.py:</tt></p>
<div class="targetlang">
<pre>
# pkg1/pkg2/foo.py
class Foo: pass
</pre>
</div>
</li>
<li> <p><tt>pkg1/pkg2/bar.py:</tt></p>
<div class="targetlang">
<pre>
# pkg1/pkg2/bar.py
import pkg1.pkg2.foo
class Bar(pkg1.pkg2.foo.Foo): pass
</pre>
</div>
</li>
</ul>
<p>Now if one simply used <tt>import pkg1.pkg2</tt>, it will usually fail:</p>
<div class="diagram">
<pre>
>>> import pkg1.pkg2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "./pkg1/pkg2/__init__.py", line 2, in <module>
from .bar import Bar
File "./pkg1/pkg2/bar.py", line 3, in <module>
class Bar(pkg1.pkg2.foo.Foo): pass
AttributeError: 'module' object has no attribute 'pkg2'
</pre>
</div>
<p>Surprisingly, if we execute the <tt>import pkg1.pkg2</tt> directive for the
second time, it succeeds. The reason seems to be following: when Python spots
the <tt>from .bar import Bar</tt> directive in <tt>pkg1/pkg2/__init__.py</tt>
it starts loading <tt>pkg1/pkg2/bar.py</tt>. This module imports
<tt>pkg1.pkg2.foo</tt> in turn and tries to use <tt>pkg1.pkg2.foo.Foo</tt>, but
the package <tt>pkg1</tt> is not fully initialized yet (the initialization
procedure is actually in progress) and it seems like the effect of the already seen
<tt>import pkg1.pkg2.pkg3.foo</tt> is "delayed" or ignored. Exactly the
same may happen to a proxy module generated by SWIG.</p>
<p>One workaround for this case is to use a relative
import in <tt>pkg1/pkg2/bar.py</tt>. If we change <tt>bar.py</tt> to be:</p>
<div class="targetlang">
<pre>
from .pkg3 import foo
class Bar(foo.Foo): pass
</pre>
</div>
<p>or</p>
<div class="targetlang">
<pre>
from . import pkg3
from .pkg3 import foo
class Bar(pkg3.foo.Foo): pass
</pre>
</div>
<p>then the example works again. With SWIG, you need to enable the
<tt>-relativeimport</tt> option in order to have the above workaround in
effect (note, that the Python 2 case also needs the <tt>-relativeimport</tt>
workaround).</p>
<H3><a name="Python_implicit_namespace_packages">36.11.5 Implicit Namespace Packages</a></H3>
<p> Python 3.3 introduced
<a href="https://www.python.org/dev/peps/pep-0420/">PEP 0420</a> which
implements implicit namespace packages. In a nutshell, implicit namespace
packages remove the requirement of an __init__.py file and allow packages
to be split across multiple PATH elements. For example:
</p>
<div class="diagram">
<pre>
/fragment1/pkg1/mod1.py
/fragment2/pkg1/mod2.py
/fragment3/pkg1/mod3.py
</pre>
</div>
<p>If PYTHONPATH is set to "/fragment1:/fragment2:/fragment3", then mod1, mod2
and mod3 will be part of pkg1. This allows for splitting of packages into
separate pieces. This can be useful for SWIG generated wrappers in the
following way.
</p>
<p> Suppose you create a SWIG wrapper for a module called robin. The SWIG
generated code consists of two files robin.py and _robin.so. You wish to
make these modules part of a subpackage (brave.sir). With implicit namespace
packages you can place these files in the following configurations:
</p>
<p>Using PYTHONPATH="/some/path"</p>
<div class="diagram">
<pre>
/some/path/brave/sir/robin.py
/some/path/brave/sir/_robin.so
</pre>
</div>
<p>Using PYTHONPATH="/some/path:/some/other/path"
<div class="diagram">
<pre>
/some/path/brave/sir/robin.py
/some/other/path/brave/sir/_robin.so
</pre>
</div>
<p> Finally suppose that your pure python code is stored in a .zip file or
some other way (database, web service connection, etc). Python can load the
robin.py module using a custom importer. But the _robin.so module will need
to be located on a file system. Implicit namespace packages make this
possible. For example, using PYTHONPATH="/some/path/foo.zip:/some/other/path"
<p> Contents of foo.zip</p>
<div class="diagram">
<pre>
brave/
brave/sir/
brave/sir/robin.py
</pre>
</div>
<p> File system contents</p>
<div class="diagram">
<pre>
/some/other/path/brave/sir/_robin.so
</pre>
</div>
<p>Support for implicit namespace packages was added to python-3.3. The
zipimporter requires python-3.5.1 or newer to work with subpackages.
</p>
<p>
<b>Compatibility Note:</b> Support for implicit namespace packages was added in SWIG-3.0.9.
</p>
<H3><a name="Python_package_search">36.11.6 Searching for the wrapper module</a></H3>
<p>
When SWIG creates wrappers from an interface file, say foo.i, two Python modules are
created. There is a pure Python module module (foo.py) and C/C++ code which is
built and linked into a dynamically (or statically) loaded low-level module _foo
(see the <a href="Python.html#Python_nn3">Preliminaries section</a> for details). So, the interface
file really defines two Python modules. How these two modules are loaded is
covered next.
</p>
<p>
The pure Python module needs to load the C/C++ module in order to link
to the wrapped C/C++ methods. To do this it must make some assumptions
about what package the C/C++ module may be located in. The approach the
pure Python module uses to find the C/C++ module is as follows:
</p>
<ol>
<li><p>The pure Python module, foo.py, tries to load the C/C++ module, _foo, from the same package foo.py is
located in. The package name is determined from the <tt>__name__</tt>
attribute given to foo.py by the Python loader that imported
foo.py. If foo.py is not in a package then _foo is loaded
as a global module.</p>
</li>
<li><p>If the above import of _foo results in an ImportError
being thrown, then foo.py makes a final attempt to load _foo
as a global module.</p>
</li>
</ol>
<p>
The Python code implementing the loading logic described above is quite complex to handle multiple
versions of Python, but it can be replaced with custom code.
This is not recommended unless you understand the full intricacies of importing Python modules.
The custom code can be specified by setting the <tt>moduleimport</tt> option of the <tt>%module</tt> directive with the appropriate import code. For example:
</p>
<div class="code">
<pre>
%module(moduleimport="import _foo") foo
</pre>
</div>
<p>
The special variable <tt>$module</tt> will also be expanded into the low-level C/C++ module name, <tt>_foo</tt> in the case above.
When you have more than just a line or so then you can retain the easy
readability of the <tt>%module</tt> directive by using a macro. For
example:
</p>
<div class="code">
<pre>
%define MODULEIMPORT
"
print 'Loading low-level module $module'
import $module
print 'Module has loaded'
"
%enddef
%module(moduleimport=MODULEIMPORT) foo
</pre>
</div>
<p>
Now let's consider an example using the SWIG default loading logic.
Suppose foo.i is compiled into foo.py and _foo.so. Assuming
/dir is on PYTHONPATH, then the two modules can be installed and used in the
following ways:
</p>
<H4><a name="Python_package_search_both_package_modules">36.11.6.1 Both modules in the same package</a></H4>
<p>Both modules are in one package:</p>
<div class="diagram">
<pre>
/dir/package/foo.py
/dir/package/__init__.py
/dir/package/_foo.so
</pre>
</div>
<p>And imported with</p>
<div class="diagram">
<pre>
from package import foo
</pre>
</div>
<H4><a name="Python_package_search_wrapper_split">36.11.6.2 Split modules</a></H4>
<p>The pure python module is in a package and the C/C++ module is global:</p>
<div class="diagram">
<pre>
/dir/package/foo.py
/dir/package/__init__.py
/dir/_foo.so
</pre>
</div>
<p>And imported with</p>
<div class="diagram">
<pre>
from package import foo
</pre>
</div>
<H4><a name="Python_package_search_both_global_modules">36.11.6.3 Both modules are global</a></H4>
<p>Both modules are global:</p>
<div class="diagram">
<pre>
/dir/foo.py
/dir/_foo.so
</pre>
</div>
<p>And imported with</p>
<div class="diagram">
<pre>
import foo
</pre>
</div>
<p>
If _foo is statically linked into an embedded Python interpreter, then it may or
may not be in a Python package. This depends in the exact way the module was
loaded statically. The above search order will still be used for statically
loaded modules. So, one may place the module either globally or in a package
as desired.
</p>
<H4><a name="Python_package_search_static">36.11.6.4 Statically linked C modules</a></H4>
<p>It is strongly recommended to use dynamically linked modules for the C
portion of your pair of Python modules.
If for some reason you still need
to link the C module of the pair of Python modules generated by SWIG into
your interpreter, then this section provides some details on how this impacts
the pure Python modules ability to locate the other part of the pair.
Please also see the <a href="Python.html#Python_nn8">Static Linking</a> section.
</p>
<p>When Python is extended with C code the Python interpreter needs to be
informed about details of the new C functions that have been linked into
the executable. The code to do this is created by SWIG and is automatically
called in the correct way when the module is dynamically loaded. However
when the code is not dynamically loaded (because it is statically linked)
Then the initialization method for the module created by SWIG is not
called automatically and the Python interpreter has no idea that the
new SWIG C module exists.
</p>
<p>Before Python 3, one could simply call the init method created by SWIG
which would have normally been called when the shared object was dynamically
loaded. The specific name of this method is not given here because statically
linked modules are not encouraged with SWIG
(<a href="Python.html#Python_nn8">Static Linking</a>). However one can find this
init function in the C file generated by SWIG.
</p>
<p>If you are really keen on static linking there are two ways
to initialize the SWIG generated C module with the init method. Which way
you use depends on what version of Python your module is being linked with.
Python 2 and Python 3 treat this init function differently. And the way
they treat it affects how the pure Python module will be able to
locate the C module.
</p>
<p>The details concerning this are covered completly in the documentation
for Python itself. Links to the relavent sections follow:
</p>
<ul>
<li><a href="https://docs.python.org/2/extending/extending.html#methodtable">Extending in python2</a></li>
<li><a href="https://docs.python.org/3.6/extending/extending.html#the-module-s-method-table-and-initialization-function">Extending in python3</a></li>
</ul>
<p>There are two keys things to understand. The first is that in
Python 2 the init() function returns void. In Python 3 the init() function
returns a PyObject * which points to the new module. Secondly, when
you call the init() method manually, you are the Python importer. So, you
determine which package the C module will be located in.
</p>
<p>So, if you are using Python 3 it is important that you follow what is
described in the Python documentation linked above. In particular, you can't
simply call the init() function generated by SWIG and cast the PyObject
pointer it returns over the side. If you do then Python 3 will have no
idea that your C module exists and the pure Python half of your wrapper will
not be able to find it. You need to register your module with the Python
interpreter as described in the Python docs.
</p>
<p>With Python 2 things are somewhat more simple. In this case the init function
returns void. Calling it will register your new C module as a <b>global</b>
module. The pure Python part of the SWIG wrapper will be able to find it
because it tries both the pure Python module it is part of and the global
module. If you wish not to have the statically linked module be a global
module then you will either need to refer to the Python documentation on how
to do this (remember you are now the Python importer) or use dynamic linking.
</p>
<H2><a name="Python_python3support">36.12 Python 3 Support</a></H2>
<p>
SWIG is able to support Python 3.0. The wrapper code generated by
SWIG can be compiled with both Python 2.x or 3.0. Further more, by
passing the <tt>-py3</tt> command line option to SWIG, wrapper code
with some Python 3 specific features can be generated (see below
subsections for details of these features). The <tt>-py3</tt> option also
disables some incompatible features for Python 3, such as
<tt>-classic</tt>.
<p>
There is a list of known-to-be-broken features in Python 3:
</p>
<ul>
<li>No more support for FILE* typemaps, because PyFile_AsFile has been dropped
in Python 3.</li>
<li>The <tt>-apply</tt> command line option is removed and generating
code using apply() is no longer supported.</li>
</ul>
<p>
The following are Python 3.0 new features that are currently supported by
SWIG.
</p>
<H3><a name="Python_nn74">36.12.1 Function annotation</a></H3>
<p>
The <tt>-py3</tt> option will enable function annotation support. When used
SWIG is able to generate proxy method definitions like this:
</p>
<div class="code"><pre>
def foo(self, bar : "int"=0) -> "void" : ...
</pre></div>
<p>
Also, even if without passing SWIG the <tt>-py3</tt> option, the parameter list
still could be generated:
</p>
<div class="code"><pre>
def foo(self, bar=0): ...
</pre></div>
<p>
But for overloaded function or method, the parameter list would fallback to
<tt>*args</tt> or <tt>self, *args</tt>, and <tt>**kwargs</tt> may be append
depend on whether you enabled the keyword argument. This fallback is due to
all overloaded functions share the same function in SWIG generated proxy class.
</p>
<p>
For detailed usage of function annotation, see
<a href="https://www.python.org/dev/peps/pep-3107/">PEP 3107</a>.
</p>
<H3><a name="Python_nn75">36.12.2 Buffer interface</a></H3>
<p>
Buffer protocols were revised in Python 3. SWIG also gains a series of
new typemaps to support buffer interfaces. These typemap macros are
defined in <tt>pybuffer.i</tt>, which must be included in order to use them.
By using these typemaps, your wrapped function will be able to
accept any Python object that exposes a suitable buffer interface.
</p>
<p>
For example, the <tt>get_path()</tt> function puts the path string
into the memory pointed to by its argument:
</p>
<div class="code"><pre>
void get_path(char *s);
</pre></div>
<p>
Then you can write a typemap like this: (the following example is
applied to both Python 3.0 and 2.6, since the <tt>bytearray</tt> type
is backported to 2.6.
</p>
<div class="code"><pre>
%include <pybuffer.i>
%pybuffer_mutable_string(char *str);
void get_path(char *s);
</pre></div>
<p>
And then on the Python side the wrapped <tt>get_path</tt> could be used in this
way:
</p>
<div class="targetlang"><pre>
>>> p = bytearray(10)
>>> get_path(p)
>>> print(p)
bytearray(b'/Foo/Bar/\x00')
</pre></div>
<p>
The macros defined in <tt>pybuffer.i</tt> are similar to those in
<tt>cstring.i</tt>:
</p>
<p>
<b>%pybuffer_mutable_binary(parm, size_parm)</b>
</p>
<div class="indent">
<p>
The macro can be used to generate a typemap which maps a buffer of an
object to a pointer provided by <tt>parm</tt> and a size argument
provided by <tt>size_parm</tt>. For example:
</p>
<div class="code"><pre>
%pybuffer_mutable_binary(char *str, size_t size);
...
int snprintf(char *str, size_t size, const char *format, ...);
</pre></div>
<p>
In Python:
</p>
<div class="targetlang"><pre>
>>> buf = bytearray(6)
>>> snprintf(buf, "Hello world!")
>>> print(buf)
bytearray(b'Hello\x00')
>>>
</pre></div>
</div>
<p>
<b>%pybuffer_mutable_string(parm)</b>
</p>
<div class="indent">
<p>
This typemap macro requires the buffer to be a zero terminated string,
and maps the pointer of the buffer to <tt>parm</tt>. For example:
</p>
<div class="code"><pre>
%pybuffer_mutable_string(char *str);
...
size_t make_upper(char *str);
</pre></div>
<p>
In Python:
</p>
<div class="targetlang"><pre>
>>> buf = bytearray(b'foo\x00')
>>> make_upper(buf)
>>> print(buf)
bytearray(b'FOO\x00')
>>>
</pre></div>
<p>
Both <tt>%pybuffer_mutable_binary</tt> and <tt>%pybuffer_mutable_string</tt>
require the provided buffer to be mutable, eg. they can accept a
<tt>bytearray</tt> type but can't accept an immutable <tt>byte</tt>
type.
</p>
</div>
<p>
<b>%pybuffer_binary(parm, size_parm)</b>
</p>
<div class="indent">
<p>
This macro maps an object's buffer to a pointer <tt>parm</tt> and a
size <tt>size_parm</tt>. It is similar to
<tt>%pybuffer_mutable_binary</tt>, except the
<tt>%pybuffer_binary</tt> an accept both mutable and immutable
buffers. As a result, the wrapped function should not modify the buffer.
</p>
</div>
<p>
<b>%pybuffer_string(parm)</b>
</p>
<div class="indent">
<p>
This macro maps an object's buffer as a string pointer <tt>parm</tt>.
It is similar to <tt>%pybuffer_mutable_string</tt> but the buffer
could be both mutable and immutable. And your function should not
modify the buffer.
</p>
</div>
<H3><a name="Python_nn76">36.12.3 Abstract base classes</a></H3>
<p>
By including <tt>pyabc.i</tt> and using the <tt>-py3</tt> command
line option when calling SWIG, the proxy classes of the STL containers
will automatically gain an appropriate abstract base class. For
example, the following SWIG interface:
</p>
<div class="code"><pre>
%include <pyabc.i>
%include <std_map.i>
%include <std_list.i>
namespace std {
%template(Mapii) map<int, int>;
%template(IntList) list<int>;
}
</pre></div>
<p>
will generate a Python proxy class <tt>Mapii</tt> inheriting from
<tt>collections.MutableMap</tt> and a proxy class <tt>IntList</tt>
inheriting from <tt>collections.MutableSequence</tt>.
</p>
<p>
<tt>pyabc.i</tt> also provides a macro <tt>%pythonabc</tt> that could be
used to define an abstract base class for your own C++ class:
</p>
<div class="code"><pre>
%pythonabc(MySet, collections.MutableSet);
</pre></div>
<p>
For details of abstract base class, please see
<a href="https://www.python.org/dev/peps/pep-3119/">PEP 3119</a>.
</p>
<H3><a name="Python_nn77">36.12.4 Byte string output conversion</a></H3>
<p>
By default, any byte string (<tt>char*</tt> or <tt>std::string</tt>) returned
from C or C++ code is decoded to text as UTF-8. This decoding uses the
<tt>surrogateescape</tt> error handler under Python 3.1 or higher -- this
error handler decodes invalid byte sequences to high surrogate characters
in the range U+DC80 to U+DCFF.
As an example, consider the following SWIG interface, which exposes a byte
string that cannot be completely decoded as UTF-8:
</p>
<div class="code"><pre>
%module example
%include <std_string.i>
%inline %{
const char* non_utf8_c_str(void) {
return "h\xe9llo w\xc3\xb6rld";
}
%}
</pre></div>
<p>
When this method is called from Python 3, the return value is the following
text string:
</p>
<div class="targetlang"><pre>
>>> s = example.non_utf8_c_str()
>>> s
'h\udce9llo wörld'
</pre></div>
<p>
Since the C string contains bytes that cannot be decoded as UTF-8, those raw
bytes are represented as high surrogate characters that can be used to obtain
the original byte sequence:
</p>
<div class="targetlang"><pre>
>>> b = s.encode('utf-8', errors='surrogateescape')
>>> b
b'h\xe9llo w\xc3\xb6rld'
</pre></div>
<p>
One can then attempt a different encoding, if desired (or simply leave the
byte string as a raw sequence of bytes for use in binary protocols):
</p>
<div class="targetlang"><pre>
>>> b.decode('latin-1')
'héllo wörld'
</pre></div>
<p>
Note, however, that text strings containing surrogate characters are rejected
with the default <tt>strict</tt> codec error handler. For example:
</p>
<div class="targetlang"><pre>
>>> with open('test', 'w') as f:
... print(s, file=f)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
UnicodeEncodeError: 'utf-8' codec can't encode character '\udce9' in position 1: surrogates not allowed
</pre></div>
<p>
This requires the user to check most strings returned by SWIG bindings, but
the alternative is for a non-UTF8 byte string to be completely inaccessible
in Python 3 code.
</p>
<p>
For more details about the <tt>surrogateescape</tt> error handler, please see
<a href="https://www.python.org/dev/peps/pep-0383/">PEP 383</a>.
</p>
<p>
In some cases, users may wish to instead handle all byte strings as bytes
objects in Python 3. This can be accomplished by adding
<tt>SWIG_PYTHON_STRICT_BYTE_CHAR</tt> to the generated code:
</p>
<div class="code"><pre>
%module char_to_bytes
%begin %{
#define SWIG_PYTHON_STRICT_BYTE_CHAR
%}
char *charstring(char *s) {
return s;
}
</pre></div>
<p>
This will modify the behavior so that only Python 3 bytes objects will be
accepted and converted to a C/C++ string, and any string returned from C/C++
will be converted to a bytes object in Python 3:
</p>
<div class="targetlang"><pre>
>>> from char_to_bytes import *
>>> charstring(b"hi") # Byte string
b'hi'
>>> charstring("hi") # Unicode string
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: in method 'charstring', argument 1 of type 'char *'
</pre></div>
<p>
Note that in Python 2, defining <tt>SWIG_PYTHON_STRICT_BYTE_CHAR</tt> has no
effect, since strings in Python 2 are equivalent to Python 3 bytes objects.
However, there is a similar capability to force unicode-only handling for
wide characters C/C++ strings (<tt>wchar_t *</tt> or <tt>std::wstring</tt>
types) in Python 2. By default, in Python 2 both strings and unicode strings
are converted to C/C++ wide strings, and returned wide strings are converted
to a Python unicode string. To instead only convert unicode strings to wide
strings, users can add <tt>SWIG_PYTHON_STRICT_UNICODE_WCHAR</tt> to the
generated code:
</p>
<div class="code"><pre>
%module wchar_to_unicode
%begin %{
#define SWIG_PYTHON_STRICT_UNICODE_WCHAR
%}
wchar_t *wcharstring(wchar_t *s) {
return s;
}
</pre></div>
<p>
This ensures that only unicode strings are accepted by wcharstring in both
Python 2 and Python 3:
</p>
<div class="targetlang"><pre>
>>> from wchar_to_unicode import *
>>> wcharstring(u"hi") # Unicode string
u'hi'
>>> wcharstring(b"hi") # Byte string
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: in method 'charstring', argument 1 of type 'wchar_t *'
</pre></div>
<p>
By defining both <tt>SWIG_PYTHON_STRICT_BYTE_CHAR</tt> and
<tt>SWIG_PYTHON_STRICT_UNICODE_WCHAR</tt>, Python wrapper code can support
overloads taking both std::string (as Python bytes) and std::wstring
(as Python unicode).
</p>
<H3><a name="Python_2_unicode">36.12.5 Python 2 Unicode</a></H3>
<p>
A Python 3 string is a Unicode string so by default a Python 3 string that contains Unicode
characters passed to C/C++ will be accepted and converted to a C/C++ string
(<tt>char *</tt> or <tt>std::string</tt> types).
A Python 2 string is not a unicode string by default and should a Unicode string be
passed to C/C++ it will fail to convert to a C/C++ string
(<tt>char *</tt> or <tt>std::string</tt> types).
The Python 2 behavior can be made more like Python 3 by defining
<tt>SWIG_PYTHON_2_UNICODE</tt> when compiling the generated C/C++ code.
By default when the following is wrapped:
</p>
<div class="code"><pre>
%module unicode_strings
char *charstring(char *s) {
return s;
}
</pre></div>
<p>
An error will occur when using Unicode strings in Python 2:
</p>
<div class="targetlang"><pre>
>>> from unicode_strings import *
>>> charstring("hi")
'hi'
>>> charstring(u"hi")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: in method 'charstring', argument 1 of type 'char *'
</pre></div>
<p>
When the <tt>SWIG_PYTHON_2_UNICODE</tt> macro is added to the generated code:
</p>
<div class="code"><pre>
%module unicode_strings
%begin %{
#define SWIG_PYTHON_2_UNICODE
%}
char *charstring(char *s) {
return s;
}
</pre></div>
<p>
Unicode strings will be successfully accepted and converted from UTF-8,
but note that they are returned as a normal Python 2 string:
</p>
<div class="targetlang"><pre>
>>> from unicode_strings import *
>>> charstring("hi")
'hi'
>>> charstring(u"hi")
'hi'
>>>
</pre></div>
<p>
Note that defining both <tt>SWIG_PYTHON_2_UNICODE</tt> and
<tt>SWIG_PYTHON_STRICT_BYTE_CHAR</tt> at the same time is not allowed, since
the first is allowing unicode conversion and the second is explicitly
prohibiting it.
</p>
</body>
</html>
<!-- LocalWords: polymorphism Typemaps STL typemap typemaps Docstring autodoc
-->
<!-- LocalWords: docstring SWIG's cxx py GCC linux DLL gcc fPIC Wiki Xlinker
-->
<!-- LocalWords: examplemodule DHAVE CONFIG lpython lm ldl mypython lsocket
-->
<!-- LocalWords: lnsl lpthread distutils enums namespaces
-->
|