Source

pyobjc / pyobjc / Modules / objc / class-builder.m

Full commit
   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
/*
 * This file contains the code that is used to create proxy-classes for Python
 * classes in the objective-C runtime.
 */
#include "pyobjc.h"
#include "objc_support.h"
#include <Foundation/NSInvocation.h>


/* List of instance variables, methods and class-methods that should not
 * be overridden from python
 */
static char* dont_override_methods[] = {
	"alloc",
	"dealloc",
	"retain",
	"release",
	"autorelease",
	"retainCount",
	NULL
};

/* Special methods for Python subclasses of Objective-C objects */
static void object_method_dealloc(id self, SEL sel);
static BOOL object_method_respondsToSelector(id self, SEL selector, 
	SEL aSelector);
static NSMethodSignature*  object_method_methodSignatureForSelector(id self, 
	SEL selector, SEL aSelector);
static void object_method_forwardInvocation(id self, SEL selector, 
	NSInvocation* invocation);
static id object_method_storedValueForKey_(id self, SEL _meth, NSString* key);
static id object_method_valueForKey_(id self, SEL _meth, NSString* key);
static void object_method_takeStoredValue_forKey_(id self, SEL _meth, 
	id value, NSString* key);
static void object_method_takeValue_forKey_(id self, SEL _meth, 
	id vlaue, NSString* key);


/*
 * When we create a 'Class' we actually create the struct below. This allows
 * us to add some extra information to the class defintion.
 *
 * NOTE1: the meta_class field is first because poseAs: copies the class but
 *        not the meta class (on MacOS X <= 10.2)
 * NOTE2: That doesn't help, test_posing still crashes.
 */
#define MAGIC 0xDEADBEEF
#define CLASS_WRAPPER(cls) ((struct class_wrapper*)(cls))
#define CHECK_MAGIC(o) do { if (CLASS_WRAPPER(o)->magic != MAGIC) abort(); } while(0)
struct class_wrapper {
	struct objc_class class;
	struct objc_class meta_class;
	PyObject* python_class;
	unsigned int magic; 
};

#define IDENT_CHARS "ABCDEFGHIJKLMNOPQSRTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789"

/*
 * This function finds the superclass of the class where 'selector' is
 * overridden using 'currentImp'.
 *
 * This is needed to call the correct superclass implementation in case 
 * of multiple layers of subclassing in Python. If we don't find the 'real'
 * superclass, a call to 
 *   'objc_msgSendSuper({ self->isa->super_class, self }, ...)' will just 
 * transfer back to 'currentImp' if the method was called from a subclass (e.g.
 * if 'currentImp' is the IMP for the superclass of 'self->isa' instead of the
 * one from 'self'.
 *
 * The 'right' way to do this is by building closures (if done correctly it
 * would at least be faster) using libffi.
 */
static Class find_real_superclass(Class startAt, SEL selector, 
		METHOD (*find_method)(Class, SEL), IMP currentImp)
{
	METHOD m;
	Class  cur;

	cur = startAt;
	m = find_method(cur, selector);

	/* Skip to class containing this function */
	while (m == NULL || m->method_imp != currentImp) {
		cur = cur->super_class;
		if (!cur) {
			Py_FatalError("PyObjC: find_real_superclass "
				"cannot find SEL in class hierarchy");
		}
		m = find_method(cur, selector);
	}

	/* Skip all classes containing this function */
	while (m != NULL && m->method_imp == currentImp) {
		cur = cur->super_class;
		if (!cur) {
			Py_FatalError("PyObjC: find_real_superclass "
				"reached top of class hierarchy");
		}
		m = find_method(cur, selector);
	}

	/* We found the 'real' superclass */
	return cur;
}


/*
 * Last step of the construction a python subclass of an objective-C class.
 *
 * Set reference to the python half in the objective-C half of the class.
 *
 * Return 0 on success, -1 on failure.
 */
int PyObjCClass_SetClass(Class objc_class, PyObject* py_class)
{
	if (objc_class == nil) {
		ObjCErr_Set(ObjCExc_internal_error, 
			"Trying to set class of <nil>\n", objc_class->name);
		return -1;
	}
	if (py_class == NULL || !PyObjCClass_Check(py_class)) {
		ObjCErr_Set(ObjCExc_internal_error,
			"Trying to set class to of %s to invalid value "
			"(type %s instead of %s)",
			objc_class->name, py_class->ob_type->tp_name,
			PyObjCClass_Type.tp_name);
		return -1;
	}

	CHECK_MAGIC(objc_class);

	if (CLASS_WRAPPER(objc_class)->python_class != NULL) {
		ObjCErr_Set(ObjCExc_internal_error,
			"Trying to set update PythonClass of %s",
			objc_class->name);
		return -1;
	}


	CLASS_WRAPPER(objc_class)->python_class = py_class;
	Py_INCREF(py_class);

	objc_addClass(objc_class);
	return 0;
}

/*
 * Call this when the python half of the class could not be created. 
 *
 * Due to technical restrictions it is not allowed to unbuild a class that
 * is already registered with the Objective-C runtime.
 */
void PyObjCClass_UnbuildClass(Class objc_class)
{
	struct class_wrapper* wrapper = CLASS_WRAPPER(objc_class); 

	if (objc_class == nil) {
		ObjCErr_Set(ObjCExc_internal_error, 
		"Trying to unregister class <nil>");
		return;
	}

	CHECK_MAGIC(objc_class);

	if (wrapper->python_class != NULL) {
		ObjCErr_Set(ObjCExc_internal_error,
			"Trying to unregister objective-C class %s, but it "
			"is already registered with the runtime",
			objc_class->name);
		return;
	}


	objc_freeMethodList(wrapper->class.METHODLISTS);
	objc_freeMethodList(wrapper->meta_class.METHODLISTS);
	free((char*)(wrapper->class.name));
	free(objc_class);
}

/*
 * Find the signature of 'selector' in the list of protocols.
 */
static char*
find_protocol_signature(PyObject* protocols, SEL selector)
{
	int len;
	int i;
	PyObject* proto;
	PyObject* info;

	if (!PyList_Check(protocols)) {
		ObjCErr_Set(ObjCExc_internal_error,
			"Protocol-list is not a list");
		return NULL;
	}

	/* First try the explicit protocol definitions */
	len = PyList_GET_SIZE(protocols);
	for (i = 0; i < len; i++) {
		proto = PyList_GET_ITEM(protocols, i);
		if (proto == NULL) {
			PyErr_Clear();
			continue;
		}
		if (!PyObjCInformalProtocol_Check(proto)) continue;

		info = PyObjCInformalProtocol_FindSelector(proto, selector);
		if (info != NULL) {
			return PyObjCSelector_Signature(info);
		}
	}

	/* Then check if another protocol users this selector */
	proto = PyObjCInformalProtocol_FindProtocol(selector);
	if (proto == NULL) {
		PyErr_Clear();
		return NULL;
	}

	info = PyObjCInformalProtocol_FindSelector(proto, selector);
	if (info != NULL) {
		if (PyList_Append(protocols, proto) < 0) {
			return NULL;
		}
		Py_INCREF(proto);
		return PyObjCSelector_Signature(info);
	}
	
	return NULL;
}

/*
 * Be smart about slots: Push them into Objective-C and leave an empty
 * __slots__ attribute, that way we don't store object-state in the python
 * proxy.
 */
static int 
do_slots(PyObject* super_class, PyObject* clsdict)
{
	PyObject* slot_value;
	PyObject* slots;
	int       len, i;

	slot_value = PyDict_GetItemString(clsdict, "__slots__");
	if (slot_value == NULL) {
		PyObject* v;

		/* Add an __dict__ unless it is already there */
		PyErr_Clear();

		if (PyObjCClass_DictOffset(super_class) != 0) {
			/* We already have an __dict__ */
			return 0;
		}

		v = PyObjCInstanceVariable_New("__dict__");
		if (v == NULL) {
			return -1;
		}
		((PyObjCInstanceVariable*)v)->type[0] = '\0';
		((PyObjCInstanceVariable*)v)->isSlot = 1;
		if (PyDict_SetItemString(clsdict, "__dict__", v) < 0) {
			Py_DECREF(v);
			return -1;
		}
		Py_DECREF(v);

		slot_value = PyTuple_New(0);
		if (slot_value == NULL) {
			return NULL;
		}

		if (PyDict_SetItemString(clsdict, "__slots__", slot_value) < 0){
			Py_DECREF(slot_value);
			return -1;
		}
		Py_DECREF(slot_value);
		return 0;
	}

	slots = PySequence_Fast(slot_value, "__slots__ must be a sequence");
	if (slots == NULL) {
		return -1;
	}
	
	len = PySequence_Fast_GET_SIZE(slots);
	for (i = 0; i < len; i++) {
		PyObjCInstanceVariable* var;
		slot_value = PySequence_Fast_GET_ITEM(slots, i);

		if (!PyString_Check(slot_value)) {
			ObjCErr_Set(PyExc_TypeError, 
				"__slots__ entry %d is not a string", i);
			Py_DECREF(slots);
			return -1;
		}

		var = (PyObjCInstanceVariable*)PyObjCInstanceVariable_New(
				PyString_AS_STRING(slot_value));
		if (var == NULL) {
			Py_DECREF(slots);
			return -1;
		}
		var->type[0] = '\0';
		((PyObjCInstanceVariable*)var)->isSlot = 1;
	
		if (PyDict_SetItem(clsdict, slot_value, (PyObject*)var) < 0) {
			Py_DECREF(slots);
			Py_DECREF(var);
			return -1;
		}
		Py_DECREF(var);
	}
	Py_DECREF(slots);

	slot_value = PyTuple_New(0);
	if (slot_value == NULL) {
		return NULL;
	}
	if (PyDict_SetItemString(clsdict, "__slots__", slot_value) < 0) {
		Py_DECREF(slot_value);
		return -1;
	}
	Py_DECREF(slot_value);
	return 0;
}

/*
 * First step of creating a python subclass of an objective-C class
 *
 * Returns NULL or the newly created objective-C klass. 'class_dict' may
 * be modified by this function.
 *
 * TODO:
 * - Set 'sel_class' of ObjCPythonSelector instances
 * - This function complete ignores other base-classes, even though they
 *   might override methods. Need to check the MRO documentation to check
 *   if this is a problem. 
 * - It is a problem when the user tries to use mixins to define common
 *   methods (like a NSTableViewDataSource mixin), this works but slowly
 *   because this calls will always be resolved through forwardInvocation:
 * - Add an 'override' flag that makes it possible to replace an existing
 *   PyObjC class, feature request for the Python-IDE  (write class, run,
 *   oops this doesn't work, rewrite class, reload and continue testing in
 *   the running app)
 */
Class PyObjCClass_BuildClass(Class super_class,  PyObject* protocols,
				char* name, PyObject* class_dict)
{
	PyObject*                key_list = NULL;
	PyObject*                key = NULL;
	PyObject*                value = NULL;
	int                      i, key_count;
	int	                 ivar_count = 0;
	int                      ivar_size  = 0;
	int                      meta_method_count = 0;
	int                      method_count = 0;
	int                      first_python_gen = 0;
	struct objc_ivar_list*   ivar_list = NULL;
	struct objc_method_list* method_list = NULL;
	struct objc_method_list* meta_method_list = NULL;
	struct class_wrapper*    new_class = NULL;
	Class                    root_class;
	char**                   curname;
	PyObject*		 py_superclass;
	int			 item_size;


	/* XXX: May as well directly pass this in... */
	py_superclass = PyObjCClass_New(super_class);
	if (py_superclass == NULL) return NULL;

	if (do_slots(py_superclass, class_dict) < 0) {
		goto error_cleanup;
	}

	if (!PyList_Check(protocols)) {
		ObjCErr_Set(ObjCExc_internal_error, "%s", 
			"protocol list not a python 'list'");
		goto error_cleanup;
	}
	if (!PyDict_Check(class_dict)) {
		ObjCErr_Set(ObjCExc_internal_error, "%s", 
			"class dict not a python 'dict'");
		goto error_cleanup;
	}
	if (super_class == NULL) {
		ObjCErr_Set(ObjCExc_internal_error, "%s", 
			"must have super_class");
		goto error_cleanup;
	}

	if (objc_lookUpClass(name) != NULL) {
		ObjCErr_Set(ObjCExc_error, "class already '%s' exists", name);
		goto error_cleanup;
	}
	if (strspn(name, IDENT_CHARS) != strlen(name)) {
		ObjCErr_Set(ObjCExc_error, "'%s' not a valid name", name);
		goto error_cleanup;
	}

	/* 
	 * Check for methods/variables that must not be overridden in python.
	 */
	for (curname = dont_override_methods; *curname != NULL; curname++) {
		key = PyDict_GetItemString(class_dict, *curname);
		if (key != NULL) {
			ObjCErr_Set(ObjCExc_error,
				"Cannot override %s from python", *curname);
			goto error_cleanup;
		}
	}

	key_list = PyDict_Keys(class_dict);
	if (key_list == NULL) {
		goto error_cleanup;
	}

	key_count = PyList_Size(key_list);
	if (PyErr_Occurred()) {
		Py_DECREF(key_list);
		goto error_cleanup;
	}


	if (!PyObjCClass_HasPythonImplementation(py_superclass)) {
		/* 
		 * This class has a super_class that is pure objective-C
		 * We'll add some instance variables and methods that are
		 * needed for the correct functioning of the class. 
		 *
		 * See the code below the next loop.
		 */
		first_python_gen = 1;

		ivar_count        += 0;
		meta_method_count += 0; 
		method_count      += 8;
	}

	/* Allocate the class as soon as possible, for new selector objects */
	new_class = calloc(1, sizeof(struct class_wrapper));
	if (new_class == NULL) {
		goto error_cleanup;
	}

	/* First round, count new instance-vars and check for overridden 
	 * methods.
	 */
	for (i = 0; i < key_count; i++) {
		key = PyList_GetItem(key_list, i);
		if (PyErr_Occurred()) {
			PyErr_Clear();
			ObjCErr_Set(ObjCExc_internal_error,
				"PyObjCClass_BuildClass: "
				"Cannot fetch key in keylist");
			goto error_cleanup;
		}

		value = PyDict_GetItem(class_dict, key);
		if (value == NULL) {
			PyErr_Clear();
			ObjCErr_Set(ObjCExc_internal_error,
				"PyObjCClass_BuildClass: "
				"Cannot fetch item in keylist");
			goto error_cleanup;
		}

		if (PyObjCInstanceVariable_Check(value)) {
			if (class_getInstanceVariable(super_class, 
			    ((PyObjCInstanceVariable*)value)->name) != NULL) {
				ObjCErr_Set(ObjCExc_error,
					"a superclass already has an instance "
					"variable with this name: %s",
					((PyObjCInstanceVariable*)value)->name);
				goto error_cleanup;
			}

			ivar_count ++;

			if (((PyObjCInstanceVariable*)value)->isSlot) {
				item_size = sizeof(PyObject**);
			} else {
				item_size = objc_sizeof_type(
					((PyObjCInstanceVariable*)value)->type);
			}
			if (item_size == -1) goto error_cleanup;
			ivar_size += item_size;

		} else if (PyObjCSelector_Check(value)) {
			PyObjCSelector* sel = (PyObjCSelector*)value;
			METHOD        meth;

			if (sel->sel_flags & PyObjCSelector_kCLASS_METHOD) {
				meth = class_getClassMethod(super_class,
					sel->sel_selector);
				meta_method_count ++;


			} else {
				meth = class_getInstanceMethod(super_class,
					sel->sel_selector);
				method_count ++;
			}

			/* TODO: If it already has a sel_class, create a copy */
			((PyObjCSelector*)value)->sel_class =
				&new_class->class;

		} else if (PyMethod_Check(value) || PyFunction_Check(value)) {
			PyObject* pyname;
			char*     ocname;
			SEL	  selector;
			METHOD    meth;
			int       is_class_method = 0;

			pyname = key;
			if (pyname == NULL) continue;

			ocname = PyString_AS_STRING(pyname);
			if (ocname[0] == '_' && ocname[1] == '_') {
				/* Skip special methods */
				continue;
			}

			selector = PyObjCSelector_DefaultSelector(ocname);

			meth = class_getInstanceMethod(super_class, selector);
			if (!meth) {
				meth = class_getClassMethod(
						super_class, selector);
				if (meth) {
					is_class_method = 1;
				}
			}

			if (meth) {
				/* The function overrides a method in the 
				 * objective-C class, replace by a selector 
				 * object.
				 *
				 * Get the signature through the python wrapper,
				 * the user may have specified a more exact
				 * signature!
				 */
				PyObject* super_sel = PyObjCClass_FindSelector(
					py_superclass, selector);
				if (!super_sel) goto error_cleanup;

				value = PyObjCSelector_New(
					value, 
					selector, 
					PyObjCSelector_Signature(super_sel),
					is_class_method,
					&new_class->class);
				new_class->class.name = "TempValue";
				Py_DECREF(super_sel);
			} else {
				char* signature;

				signature = find_protocol_signature(
					protocols, selector);
				value = PyObjCSelector_New(
					value, 
					selector, 
					signature,
					0,
					&new_class->class);
			}
			if (value == NULL) goto error_cleanup;
				
			if (PyDict_SetItem(class_dict, key, value) < 0) {
				Py_DECREF(value); value = NULL;
				goto error_cleanup;
			}
			Py_DECREF(value); value = NULL;
			if (is_class_method) {
				meta_method_count++;
			} else {
				method_count++;
			}
#if 0
		} else if ((value)->ob_type == PyClassMethod_Type) {
			/* Make a new selector object */
#endif
		}
	}

	/* Allocate space for the new instance variables and methods */

	if (ivar_count == 0)  {
		ivar_list = NULL;
	} else {
		ivar_list = malloc(sizeof(struct objc_ivar_list) +
			(ivar_count)*sizeof(struct objc_ivar));
		if (ivar_list == NULL) {
			PyErr_NoMemory();
			goto error_cleanup;
		}
		ivar_list->ivar_count = 0;
	}

	if (method_count == 0) {
		method_list = NULL;
	} else {
		method_list = objc_allocMethodList(method_count);

		if (method_list == NULL) {
			PyErr_NoMemory();
			goto error_cleanup;
		}
	}

	if (meta_method_count == 0) {
		meta_method_list = NULL;
		
	} else {
		meta_method_list = objc_allocMethodList(meta_method_count);

		if (meta_method_list == NULL) {
			PyErr_NoMemory();
			goto error_cleanup;
		}
	}


	/* And fill the method_lists and ivar_list */

#if 0
	/* Create new_class here, just in case we are the first python
	 * generation, in which case we need to use new_class (it must just
	 * be there, it doesn't have to be initialized)
	 */
	new_class = calloc(1, sizeof(struct class_wrapper));
	if (new_class == NULL) {
		goto error_cleanup;
	}
#endif


	ivar_size = super_class->instance_size;

	if (first_python_gen) {
		/* Our parent is a pure Objective-C class, add our magic
		 * methods and variables 
		 */
		 
		METHOD meth;
		PyObject* sel;

#		define METH(pyname, selector, types, imp) 		\
			meth = method_list->method_list + 		\
				method_list->method_count++;		\
			meth->method_name = selector;			\
			meth->method_types = types;			\
			meth->method_imp = (IMP)imp;			\
			sel = PyObjCSelector_NewNative(&new_class->class, \
				selector,  types, 0);			\
			if (sel == NULL) goto error_cleanup;		\
			PyDict_SetItemString(class_dict, pyname, sel);	\
			Py_DECREF(sel)


		METH(
			"dealloc", 
			@selector(dealloc), 
			"v@:", 
			object_method_dealloc);
		METH(
			"respondsToSelector_", 
			@selector(respondsToSelector:), 
			"c@::", 
			object_method_respondsToSelector);
		METH(
			"methodSignatureForSelector_", 
			@selector(methodSignatureForSelector:), 
			"@@::", 
			object_method_methodSignatureForSelector);
		METH(
			"forwardInvocation_", 
			@selector(forwardInvocation:), 
			"v@:@", 
			object_method_forwardInvocation);
		METH(
			"storedValueForKey_",
			@selector(storedValueForKey:),
			"@@:@",
			object_method_storedValueForKey_);
		METH(
			"valueForKey_",
			@selector(valueForKey:),
			"@@:@",
			object_method_valueForKey_);
		METH(
			"takeStoredValue_forKey_",
			@selector(takeStoredValue:forKey:),
			"@@:@@",
			object_method_takeStoredValue_forKey_);
		METH(
			"takeValue_forKey_",
			@selector(takeValue:forKey:),
			"@@:@@",
			object_method_takeValue_forKey_);
#undef		METH
	}

	for (i = 0; i < key_count; i++) {
		key = PyList_GetItem(key_list, i);
		if (key == NULL) {
			ObjCErr_Set(ObjCExc_internal_error,
				"PyObjCClass_BuildClass: "
				"Cannot fetch key in keylist");
			goto error_cleanup;
		}

		value = PyDict_GetItem(class_dict, key);
		if (value == NULL)  {
			ObjCErr_Set(ObjCExc_internal_error,
				"PyObjCClass_BuildClass: "
				"Cannot fetch item in keylist");
			goto error_cleanup;
		}

		if (PyObjCInstanceVariable_Check(value)) {
			IVAR var;

			var = ivar_list->ivar_list + ivar_list->ivar_count;
			ivar_list->ivar_count++;

			var->ivar_name = strdup(
				((PyObjCInstanceVariable*)value)->name);
			var->ivar_offset = ivar_size;

			/* XXX: Add alignment! */

			if (((PyObjCInstanceVariable*)value)->isSlot) {
				var->ivar_type = "^v";
				item_size = sizeof(PyObject**);
			} else {
				var->ivar_type = strdup(((PyObjCInstanceVariable*)value)->type);
				item_size = objc_sizeof_type(var->ivar_type);
			}

			if (item_size == -1) goto error_cleanup;
			ivar_size += item_size;

		} else if (PyObjCSelector_Check(value)) {
			PyObjCSelector* sel = (PyObjCSelector*)value;
			METHOD        meth;
			int           is_override = 0;
			struct objc_method_list* lst;

			if (sel->sel_flags & PyObjCSelector_kCLASS_METHOD) {
				meth = class_getClassMethod(super_class,
					sel->sel_selector);
				is_override = 1;
				lst = meta_method_list;
			} else {
				meth = class_getInstanceMethod(super_class,
					sel->sel_selector);
				if (meth) is_override = 1;
				lst = method_list;
			}

			meth = lst->method_list + lst->method_count;
			meth->method_name = sel->sel_selector;
			meth->method_types = sel->sel_signature;
		
			if (is_override) {
				meth->method_imp = 
					ObjC_FindIMP(super_class, 
						sel->sel_selector);
			} else {
				meth->method_imp = 
					ObjC_FindIMPForSignature(
						sel->sel_signature);

			}

			if (sel->sel_class == NULL) {
				sel->sel_class = &new_class->class;
			}

			if (meth->method_imp == NULL) {
				goto error_cleanup;
			}
			lst->method_count++;
		}
	}
	Py_DECREF(key_list);
	key_list = NULL;

	/* And now initialize the actual class... */

	root_class = super_class;
	while (root_class->super_class != NULL) {
		root_class = root_class->super_class;
	}

	new_class->magic = MAGIC;
	new_class->python_class = NULL;
	new_class->class.METHODLISTS = NULL;
	new_class->meta_class.METHODLISTS = NULL;
	GETISA(&new_class->class) = &new_class->meta_class;
	new_class->class.info = CLS_CLASS|CLS_METHOD_ARRAY;
	new_class->meta_class.info = CLS_META|CLS_METHOD_ARRAY;

	new_class->class.name = strdup(name);
	new_class->meta_class.name = new_class->class.name;

#ifndef GNU_RUNTIME
	new_class->class.METHODLISTS = 
		calloc(1, sizeof(struct objc_method_list*));
	if (new_class->class.METHODLISTS == NULL) goto error_cleanup;

	new_class->meta_class.METHODLISTS = 
		calloc(1, sizeof(struct objc_method_list*));
	if (new_class->meta_class.METHODLISTS == NULL) goto error_cleanup;

	/* 
	 * This is MacOS X specific, and an undocumented feature (long live
	 * Open Source!). 
	 *
	 * The code in the objc runtime assumes that the method lists are 
	 * terminated by '-1', and will happily overwite existing data if
	 * they aren't.
	 *
	 * Ronald filed a bugreport for this: Radar #3317376
	 */
	new_class->class.METHODLISTS[0] = (struct objc_method_list*)-1;
	new_class->meta_class.METHODLISTS[0] = (struct objc_method_list*)-1;

#endif

	new_class->class.super_class = super_class;
	new_class->meta_class.super_class = GETISA(super_class);
	GETISA(&new_class->meta_class) = GETISA(root_class);

	new_class->class.instance_size = ivar_size;
	new_class->class.ivars = ivar_list;

	new_class->class.protocols = NULL;
	new_class->meta_class.protocols = NULL;

	if (method_list) {
		class_addMethods(&(new_class->class), method_list);
	}
	if (meta_method_list) {
		class_addMethods(&(new_class->meta_class), meta_method_list);
	}

	Py_XDECREF(py_superclass);

	if (PyDict_DelItemString(class_dict, "__dict__") < 0) {
		PyErr_Clear();
	}

	/* 
	 * NOTE: Class is not registered yet, we do that as lately as possible
	 * because it is impossible to remove the registration from the
	 * objective-C runtime (at least on MacOS X).
	 */
	return &new_class->class;

error_cleanup:
	Py_XDECREF(py_superclass);

	if (key_list != NULL) {
		Py_DECREF(key_list);
		key_list = NULL;
	}

	if (ivar_list) {
		free(ivar_list);
	}
	if (method_list) {
		free(method_list);
	}
	if (meta_method_list) {
		free(meta_method_list);
	}

	if (new_class != NULL) {
		if(new_class->class.METHODLISTS) {
			objc_freeMethodList(new_class->class.METHODLISTS);
		}
		if (new_class->meta_class.METHODLISTS) {
			objc_freeMethodList(new_class->meta_class.METHODLISTS);
		}

		if (new_class->class.name) {
			free((char*)(new_class->class.name));
		}
		free(new_class);
	}

	return NULL;
}

/*
 * Below here are implementations of various methods needed to correctly
 * subclass Objective-C classes from Python. 
 *
 * These are added to the new Objective-C class by  PyObjCClass_BuildClass (but
 * only if the super_class is a 'pure' objective-C klass)
 *
 * NOTE:
 * - These functions will be used as methods, but as far as the compiler
 *   knows these are normal functions. You cannot use [super call]s here.
 */


static void
free_ivars(id self, PyObject* cls)
{
	/* Free all instance variables introduced through python */
	IVAR var;

	var = class_getInstanceVariable(PyObjCClass_GetClass(cls), "__dict__");
	if (var != NULL) {
		Py_XDECREF(*(PyObject**)(((char*)self) + var->ivar_offset));
		*(PyObject**)(((char*)self) + var->ivar_offset) = NULL;
	}

	while (cls != NULL) {
		Class     objcClass = PyObjCClass_GetClass(cls);
		PyObject* clsDict; 
		PyObject* clsValues;
		PyObject* o;
		int       len, i;

		if (objcClass == nil) break;


		clsDict = PyObject_GetAttrString(cls, "__dict__");
		if (clsDict == NULL) {
			PyErr_Clear();
			break;
		}
		
		/* Class.__dict__ is a dictproxy, which is not a dict and
		 * therefore PyDict_Values doesn't work.
		 */
		clsValues = PyObject_CallMethod(clsDict, "values", NULL);
		Py_DECREF(clsDict);
		if (clsValues == NULL) {
			PyErr_Clear();
			break;
		}

		len = PyList_Size(clsValues);
		/* Check type */
		for (i = 0; i < len; i++) {
			PyObjCInstanceVariable* iv;

			o = PyList_GET_ITEM(clsValues, i);

			if (o == NULL) continue;
			if (!PyObjCInstanceVariable_Check(o)) continue;
		
			iv = ((PyObjCInstanceVariable*)o);

			if (iv->type[0] != '@') continue;
			if (iv->isOutlet) continue;

			var = class_getInstanceVariable(objcClass, iv->name);
			if (var == NULL) continue;

			if (iv->isSlot) {
				Py_XDECREF(*(PyObject**)(((char*)self) + 
					var->ivar_offset));
			} else {
				[*(id*)(((char*)self) + var->ivar_offset) release];
				*(id*)(((char*)self) + var->ivar_offset) = NULL;
			}
		}

		Py_DECREF(clsValues);

		o = PyObject_GetAttrString(cls, "__bases__");
		if (o == NULL) {
			PyErr_Clear();
			cls = NULL;
		}  else if (PyTuple_Size(o) == 0) {
			PyErr_Clear();
			cls = NULL;
			Py_DECREF(o);
		} else {
			cls = PyTuple_GET_ITEM(o, 0);
			if (cls == (PyObject*)&PyObjCClass_Type) {
				cls = NULL;
			}
			Py_DECREF(o);
		}
	}

}

/* -dealloc */
static void object_method_dealloc(id self, SEL sel __attribute__((__unused__)))
{
	struct objc_super super;
	PyObject* obj;
	PyObject* delmethod;
	PyObject* cls;

	PyObject* ptype, *pvalue, *ptraceback;

	PyErr_Fetch(&ptype, &pvalue, &ptraceback);

	CHECK_MAGIC(self->isa);
	cls = PyObjCClass_New(self->isa);
	if (!PyObjCClass_HasPythonImplementation(cls)) {
		printf("-dealloc substitute called for pure ObjC class\n");
		abort();
	}

	delmethod = PyObjCClass_GetDelMethod(cls);
	if (delmethod != NULL) {
		PyObject* s = _PyObjCObject_NewDeallocHelper(self);
		obj = PyObject_CallFunction(delmethod, "O", s);
		_PyObjCObject_FreeDeallocHelper(s);
		if (obj == NULL) {
			PyErr_WriteUnraisable(delmethod);
		} else {
			Py_DECREF(obj);
		}
		Py_DECREF(delmethod);
	}

	free_ivars(self, cls);

	PyErr_Restore(ptype, pvalue, ptraceback);

	super.class = find_real_superclass(GETISA(self),
		@selector(dealloc), class_getInstanceMethod, 
		(IMP)object_method_dealloc);
	RECEIVER(super) = self;
	
	objc_msgSendSuper(&super, @selector(dealloc)); 
}

/* -respondsToSelector: */
static BOOL 
object_method_respondsToSelector(id self, SEL selector, SEL aSelector)
{
	struct objc_super super;
	BOOL              res;
        PyObject*         pyself;
	PyObject*         pymeth;

	/* First check if we respond */
	pyself = PyObjCObject_New(self);
	if (pyself == NULL) {
		return NO;
	}
	pymeth = PyObjCObject_FindSelector(pyself, aSelector);
	Py_DECREF(pyself);
	if (pymeth) {
		Py_DECREF(pymeth);
		return YES;
	}
	PyErr_Clear();

	/* Check superclass */
	super.class = find_real_superclass(GETISA(self),
			selector, class_getInstanceMethod, 
			(IMP)object_method_respondsToSelector);
	RECEIVER(super) = self;

	res = (int)objc_msgSendSuper(&super, selector, aSelector);
	return res;
}

/* -methodSignatureForSelector */
static NSMethodSignature*  
object_method_methodSignatureForSelector(id self, SEL selector, SEL aSelector)
{
	NSMethodSignature* result = nil;
	struct objc_super  super;
        PyObject*          pyself;
	PyObject*          pymeth;

	super.class = find_real_superclass(
			GETISA(self), 
			selector, class_getInstanceMethod, 
			(IMP)object_method_methodSignatureForSelector);
	RECEIVER(super) = self;

	NS_DURING
		result = objc_msgSendSuper(&super, selector, aSelector);
	NS_HANDLER
		result = nil;
	NS_ENDHANDLER

	if (result != nil) {
		return result;
	}

	pyself = PyObjCObject_New(self);
	if (pyself == NULL) {
		PyErr_Clear();
		return nil;
	}

	pymeth = PyObjCObject_FindSelector(pyself, aSelector);
	if (!pymeth) {
		Py_DECREF(pyself);
		PyErr_Clear();
		return nil;
	}

	result =  [NSMethodSignature signatureWithObjCTypes:(
		  	(PyObjCSelector*)pymeth)->sel_signature];
	Py_DECREF(pymeth);
	Py_DECREF(pyself);
	return result;
}

/* -forwardInvocation: */
static void
object_method_forwardInvocation(id self, SEL selector, NSInvocation* invocation)
{
	PyObject*	args;
	PyObject* 	result;
	PyObject*       v;
	int		isAlloc;
	int             i;
	int 		len;
	NSMethodSignature* signature;
	char		   argbuf[1024];
	const char* 		type;
	void* arg = NULL;
	int  err;
	int   arglen;
	PyObject* pymeth;
	PyObject* pyself;
	int have_output = 0;

	pyself = PyObjCObject_New(self);
	if (pyself == NULL) {
		PyObjCErr_ToObjC();
		return;
	}
	pymeth = PyObjCObject_FindSelector(pyself, [invocation selector]);
	if ((pymeth == NULL) || ObjCNativeSelector_Check(pymeth)) {
		struct objc_super super;

		if (pymeth == NULL) PyErr_Clear();

		Py_XDECREF(pymeth);
		Py_XDECREF(pyself);

		super.class = find_real_superclass(
				GETISA(self), 
				selector, class_getInstanceMethod, 
				(IMP)object_method_forwardInvocation);
		super.receiver = self;
		objc_msgSendSuper(&super, selector, invocation);
		return;
	}

	Py_XDECREF(pymeth);
	Py_XDECREF(pyself);

	signature = [invocation methodSignature];
	len = [signature numberOfArguments];

	args = PyList_New(1);
	if (args == NULL) {
		PyObjCErr_ToObjC();
	}

	i = PyList_SetItem(args, 0, pythonify_c_value(
					[signature getArgumentTypeAtIndex:0],
					(void*)&self));
	if (i < 0) {
		Py_DECREF(args);
		PyObjCErr_ToObjC();
		return;
	}

	for (i = 2; i < len; i++) {
		type = [signature getArgumentTypeAtIndex:i];
		arglen = objc_sizeof_type(type);

		if (arglen == -1) {
			Py_DECREF(args);
			PyObjCErr_ToObjC();
			return;
		}

		arg = alloca(arglen);
		
		[invocation getArgument:argbuf atIndex:i];

		switch (*type) {
		case _C_PTR:
			have_output ++;
			v = pythonify_c_value(type+1, *(void**)argbuf);
			break;
		case _C_INOUT:
			if (type[1] == _C_PTR) {
				have_output ++;
			}
			/* FALL THROUGH */
		case _C_IN: case _C_CONST:
			if (type[1] == _C_PTR) {
				v = pythonify_c_value(type+2, *(void**)argbuf);
			} else {
				v = pythonify_c_value(type+1, argbuf);
			}
			break;
		case _C_OUT:
			if (type[1] == _C_PTR) {
				have_output ++;
			}
			continue;
		default:
			v = pythonify_c_value(type, argbuf);
		}

		if (v == NULL) {
			Py_DECREF(args);
			PyObjCErr_ToObjC();
			return;
		}

		if (PyList_Append(args, v) < 0) {
			Py_DECREF(args);
			PyObjCErr_ToObjC();
			return;
		}
	}

	v = PyList_AsTuple(args);
	if (v == NULL) {
		Py_DECREF(args);
		PyObjCErr_ToObjC();
		return;
	}
	Py_DECREF(args);
	args = v;

	result = PyObjC_CallPython(self, [invocation selector], args, &isAlloc);
	Py_DECREF(args);
	if (result == NULL) {
		PyObjCErr_ToObjC();
		return;
	}

	type = [signature methodReturnType];
	arglen = objc_sizeof_type(type);

	if (arglen == -1) {
		PyObjCErr_ToObjC();
		return;
	}

	if (!have_output) {
		if (*type  != _C_VOID && *type != _C_ONEWAY) {
			arg = alloca(arglen+1);

			err = depythonify_c_value(type, result, arg);
			if (err == -1) {
				PyObjCErr_ToObjC();
				return;
			}
			if (isAlloc && *type == _C_ID) {
				[(*(id*)arg) retain];
			}
			[invocation setReturnValue:arg];
		}
		Py_DECREF(result);
	} else {
		int idx;
		PyObject* real_res;

		if (*type == _C_VOID && have_output == 1) {
			/* One output argument, and a 'void' return value,
			 * the python method returned just the output
			 * argument
			 */
			/* This should be cleaned up, unnecessary code
			 * duplication
			 */

			for (i = 2; i < len;i++) {
				void* ptr;
				type = [signature getArgumentTypeAtIndex:i];

				if (arglen == -1) {
					PyObjCErr_ToObjC();
					return;
				}

				switch (*type) {
				case _C_PTR:
					type ++;
					break;
				case _C_INOUT: case _C_OUT:
					if (type[1] != _C_PTR) {
						continue;
					}
					type += 2;
					break;
				default:
					continue;
				}

				[invocation getArgument:&ptr atIndex:i];
				err = depythonify_c_value(type, result, ptr);
				if (err == -1) {
					PyObjCErr_ToObjC();
				}
				if (v->ob_refcnt == 1 && type[0] == _C_ID) {
					/* make sure return value doesn't die before
					 * the caller can get its hands on it.
					 */
					[[*(id*)ptr retain] autorelease];
				}

				/* We have exactly 1 output argument */
				break;

			}

			Py_DECREF(result);
			return;
		}

		if (*type != _C_VOID) {
			if (!PyTuple_Check(result) 
			     || PyTuple_Size(result) != have_output+1) {
				ObjCErr_Set(PyExc_TypeError,
					"%s: Need tuple of %d arguments as result",
					SELNAME([invocation selector]),
					have_output+1);
				Py_DECREF(result);
				PyObjCErr_ToObjC();
				return;
			}
			idx = 1;
			real_res = PyTuple_GET_ITEM(result, 0);

			arg = alloca(arglen+1);

			err = depythonify_c_value(type, real_res, arg);
			if (err == -1) {
				PyObjCErr_ToObjC();
				return;
			}
			if (isAlloc && *type == _C_ID) {
				[(*(id*)arg) retain];
			}
			[invocation setReturnValue:arg];

		} else {
			if (!PyTuple_Check(result) 
			     || PyTuple_Size(result) != have_output) {
				ObjCErr_Set(PyExc_TypeError,
					"%s: Need tuple of %d arguments as result",
					SELNAME([invocation selector]),
					have_output);
				Py_DECREF(result);
				PyObjCErr_ToObjC();
				return;
			}
			idx = 0;
		}


		for (i = 2; i < len;i++) {
			void* ptr;
			type = [signature getArgumentTypeAtIndex:i];

			if (arglen == -1) {
				PyObjCErr_ToObjC();
				return;
			}

			switch (*type) {
			case _C_PTR:
				type ++;
				break;
			case _C_INOUT: case _C_OUT:
				if (type[1] != _C_PTR) {
					continue;
				}
				type += 2;
				break;
			default:
				continue;
			}

			[invocation getArgument:&ptr atIndex:i];
			v = PyTuple_GET_ITEM(result, idx++);
			err = depythonify_c_value(type, v, ptr);
			if (err == -1) {
				PyObjCErr_ToObjC();
			}
			if (v->ob_refcnt == 1 && type[0] == _C_ID) {
				/* make sure return value doesn't die before
				 * the caller can get its hands on it.
			   	 */
				[[*(id*)ptr retain] autorelease];
			}

		}
		Py_DECREF(result);
	}
}

/*
 * XXX: Function PyObjC_CallPython should be moved
 */

PyObject*
PyObjC_CallPython(id self, SEL selector, PyObject* arglist, int* isAlloc)
{
	PyObject* pyself = NULL;
	PyObject* pymeth = NULL;
	PyObject* result;


	pyself = pythonify_c_value("@", &self);
	if (pyself == NULL) {
		PyObjCErr_ToObjC();
		return NULL;
	}
	
	if (PyObjCClass_Check(pyself)) {
		pymeth = PyObjCClass_FindSelector(pyself, selector);
	} else {
		pymeth = PyObjCObject_FindSelector(pyself, selector);
	}
	if (pymeth == NULL) {
		Py_DECREF(pyself);
		PyObjCErr_ToObjC();
		return NULL;
	}

	if (isAlloc != NULL) {
		*isAlloc = ((PyObjCSelector*)pymeth)->sel_flags;
		*isAlloc = (*isAlloc & PyObjCSelector_kDONATE_REF) != 0;
	}

	result = PyObject_Call(pymeth, arglist, NULL);
	Py_DECREF(pymeth);
	Py_DECREF(pyself);

	if (result == NULL) {
		PyObjCErr_ToObjC();
		return NULL;
	}

	return result;
}

/*
 * Suppport for key-value encoding for Python/ObjC hybrids.
 * 
 * NOTE: This implementation is likely to change, which probably will have
 * user-visible effects.
 *
 * We check python-specific ways to read/write attributes, and then defer
 * to the super-class implementation. This seems to be the best way to 
 * play nice with when subclassing arbitrary Objective-C classes.
 */

static int
getAttribute(id self, NSString* key, id* result)
{
	PyObject* cls = PyObjCClass_New(self->isa);
	PyObject* val;
	PyObject* att;
	PyObject* dict;
	int dictoffset;
	int r;
	id  tmpVal;

	dictoffset = PyObjCClass_DictOffset(cls);
	if (dictoffset != 0) {
		PyObject** dictptr = (PyObject**)(((char*)self) + dictoffset);
		if (*dictptr != NULL) {
			val = PyDict_GetItemString(*dictptr, 
				(char*)[key cString]);
			if (val == NULL) {
				PyErr_Clear();
			} else {
				tmpVal = nil;
				r = depythonify_c_value(
					@encode(id), val, (void*)&tmpVal);
				if (r == -1) {
					PyErr_Clear();
				}
				*result = tmpVal;
				return r;
			}
		}
	}

	/* 
	 * Maybe this is a descriptor object, check if there is a
	 * non-method attribute in the class
	 */
	att = PyObject_GetAttrString(cls, (char*)[key cString]);
	if (att == NULL) {
		PyErr_Clear();
	} else {
		if (!PyObjCSelector_Check(att)) {
			Py_DECREF(att);
			val = PyObject_GetAttrString(
				PyObjCObject_New(self),
				(char*)[key cString]);
			if (val == NULL) {
				PyErr_Clear();
				return -1;
			} else {
				r = depythonify_c_value(@encode(id),
					val, result);
				Py_DECREF(val);
				if (r == -1) {
					PyErr_Clear();
				}
				return r;
			}
		} 
		Py_DECREF(att);
	}

	/* Check for properties, data properties won't be found using
	 * getattr(cls, propname).
	 */
	dict = PyObject_GetAttrString(cls, "__dict__");
	if (dict == NULL) {
		PyErr_Clear();
	} else {
		/* Class __dict__ need not be an actual dict! */
		att = PyMapping_GetItemString(dict, (char*)[key cString]);
		if (att == NULL) {
			PyErr_Clear();
		} else if (!PyObjCSelector_Check(att)) {
			val = PyObject_GetAttrString(
				PyObjCObject_New(self),
				(char*)[key cString]);
			if (val == NULL) {
				PyErr_Clear();
				return -1;
			} else {
				r = depythonify_c_value(@encode(id),
					val, result);
				Py_DECREF(val);
				if (r == -1) {
					PyErr_Clear();
				}
				return r;
			}
		} 
	}
	return -1;
}

static int
getAccessor(id self, NSString* key, id* result)
{
	PyObject* cls = PyObjCClass_New(self->isa);
	PyObject* val;
	PyObject* att;
	int r;

	att = PyObject_GetAttrString(cls, (char*)[key cString]);
	if (att == NULL) {
		PyErr_Clear();
	} else {
		if (PyObjCSelector_Check(att) 
				|| PyFunction_Check(att) 
				|| PyMethod_Check(att)) {
			Py_DECREF(att);
			val = PyObject_CallMethod(
				PyObjCObject_New(self),
				(char*)[key cString],
				NULL);
			if (val == NULL) {
				PyErr_Clear();
				return -1;
			} else {
				r = depythonify_c_value(@encode(id),
					val, result);
				if (r == -1) {
					PyErr_Clear();
				}
				return r;
			}
		} 
		Py_DECREF(att);
	}

	return -1;
}

static int
setAttribute(id self, NSString* key, id value)
{
	PyObject* cls = PyObjCClass_New(self->isa);
	PyObject* val;
	PyObject* att;
	int dictoffset;
	int r;

	dictoffset = PyObjCClass_DictOffset(cls);
	if (dictoffset != 0) {
		PyObject** dictptr = (PyObject**)(((char*)self) + dictoffset);
		if (*dictptr != NULL && PyDict_GetItemString(
				*dictptr, (char*)[key cString]) != NULL) {

			val = pythonify_c_value(@encode(id), &value);
			if (val == NULL) {
				PyErr_Clear();
				return -1;
			}

			r = PyDict_SetItemString(*dictptr, 
				(char*)[key cString], val);
			if (r == -1) {
				PyErr_Clear();
			}
			Py_DECREF(val);
			return r;
		}
	}

	/* 
	 * Maybe this is a descriptor object, check if there is a
	 * non-method attribute in the class
	 */
	att = PyObject_GetAttrString(cls, (char*)[key cString]);
	if (att == NULL) {
		PyErr_Clear();
	} else {
		if (!PyObjCSelector_Check(att)) {
			Py_DECREF(att);

			val = pythonify_c_value(@encode(id), &value);
			if (val == NULL) {
				PyErr_Clear();
				return -1;
			}

			r = PyObject_SetAttrString(
				PyObjCObject_New(self),
				(char*)[key cString], val);
			if (r == -1) {
				PyErr_Clear();
			}
			Py_DECREF(val);
			return r;
		}
		Py_DECREF(att);
	}

	return -1;
}

static int
setAccessor(id self, NSString* key, id value)
{
	PyObject* cls = PyObjCClass_New(self->isa);
	PyObject* val;
	PyObject* att;

	att = PyObject_GetAttrString(cls, (char*)[key cString]);
	if (att == NULL) {
		PyErr_Clear();
	} else {
		if (PyObjCSelector_Check(att) 
				|| PyFunction_Check(att) 
				|| PyMethod_Check(att)) {

			Py_DECREF(att);

			val = pythonify_c_value(@encode(id), &value);
			if (val == NULL) {
				PyErr_Clear();
				return -1;
			}

			att = PyObject_CallMethod(
				PyObjCObject_New(self),
				(char*)[key cString], "O", val);
			if (att == NULL) {
				PyErr_Print();
				PyErr_Clear();
			}
			Py_XDECREF(att);
			Py_DECREF(val);
			return (att == NULL) ? -1 : 0;
		}
		Py_DECREF(att);
	}

	return -1;
}

static id
object_method_storedValueForKey_(id self, SEL _meth, NSString* key)
{
	id result;
	int r;
	struct objc_super super;

	r = getAccessor(self, [NSString stringWithFormat: @"get_%@", key], 
		&result);
	if (r == 0) {
		return result;
	}

	r = getAttribute(self, key, &result);
	if (r == 0) {
		return result;
	}


	r = getAccessor(self, [NSString stringWithFormat: @"_get_%@", key], 
		&result);
	if (r == 0) {
		return result;
	}

	r = getAttribute(self, [NSString stringWithFormat: @"_%@", key], 
		&result);
	if (r == 0) {
		return result;
	}

	/* Call super */
	super.class = find_real_superclass(
		GETISA(self),
		_meth,
		class_getInstanceMethod,
		(IMP)object_method_storedValueForKey_);
	super.receiver = self;
	return objc_msgSendSuper(&super, _meth, key);
}

static id
object_method_valueForKey_(id self, SEL _meth, NSString* key)
{
	id result;
	int r;
	struct objc_super super;

	r = getAccessor(self, [NSString stringWithFormat: @"get_%@", key], 
		&result);
	if (r == 0) {
		return result;
	}

	r = getAttribute(self, key, &result);
	if (r == 0) {
		return result;
	}


	r = getAccessor(self, [NSString stringWithFormat: @"_get_%@", key], 
		&result);
	if (r == 0) {
		return result;
	}

	r = getAccessor(self, [NSString stringWithFormat: @"%@", key], 
		&result);
	if (r == 0) {
		return result;
	}

	r = getAccessor(self, [NSString stringWithFormat: @"_%@", key], 
		&result);
	if (r == 0) {
		return result;
	}

	r = getAttribute(self, [NSString stringWithFormat: @"_%@", key], 
		&result);
	if (r == 0) {
		return result;
	}


	/* Call super */
	super.class = find_real_superclass(
		GETISA(self),
		_meth,
		class_getInstanceMethod,
		(IMP)object_method_valueForKey_);
	super.receiver = self;
	result = objc_msgSendSuper(&super, _meth, key);
	return result;
}

static void
object_method_takeStoredValue_forKey_(id self, SEL _meth, id value, NSString* key)
{
	struct objc_super super;
	int r;

	r = setAccessor(self, 
		[NSString stringWithFormat:@"set_%@", key], value);
	if (r == 0) {
		return;
	}

	r = setAccessor(self, 
		[NSString stringWithFormat:@"set%@", [key capitalizedString]], 
		value);
	if (r == 0) {
		return;
	}

	r = setAttribute(self, key, value);
	if (r == 0) {
		return;
	}

	r = setAccessor(self, 
		[NSString stringWithFormat:@"_set_%@", key], value);
	if (r == 0) {
		return;
	}

	r = setAccessor(self, 
		[NSString stringWithFormat:@"_set%@", [key capitalizedString]], 
		value);
	if (r == 0) {
		return;
	}

	r = setAttribute(self, [NSString stringWithFormat:@"_%@", key], value);
	if (r == 0) {
		return;
	}

	/* Call super */
	NS_DURING
		super.class = find_real_superclass(
			GETISA(self),
			_meth,
			class_getInstanceMethod,
			(IMP)object_method_takeStoredValue_forKey_);
		super.receiver = self;
		(void)objc_msgSendSuper(&super, _meth, value, key);
	NS_HANDLER
		/* Parent doesn't know the key, try to create in the 
		 * python side, just like for plain python objects.
		 */
		if ([[localException name] isEqual:@"NSUnknownKeyException"]) {
			PyObject* selfObj = PyObjCObject_New(self);
			PyObject* val;

			val = pythonify_c_value(@encode(id), &value);
			if (val == NULL) {
				PyErr_Clear();
				[localException raise];
			}

			r = PyObject_SetAttrString(selfObj, 
				(char*)[key cString],
				val);
			Py_DECREF(val);
			if (r == -1) {
				PyErr_Clear();
				[localException raise];
			}
				
		} else {
			[localException raise];
		}
	NS_ENDHANDLER
}

static void
object_method_takeValue_forKey_(id self, SEL _meth, id value, NSString* key)
{
	struct objc_super super;
	int r;

	r = setAccessor(self, 
		[NSString stringWithFormat:@"set_%@", key], value);
	if (r == 0) {
		return;
	}

	r = setAccessor(self, 
		[NSString stringWithFormat:@"set%@", [key capitalizedString]], 
		value);
	if (r == 0) {
		return;
	}

	r = setAttribute(self, key, value);
	if (r == 0) {
		return;
	}

	r = setAccessor(self, 
		[NSString stringWithFormat:@"_set_%@", key], value);
	if (r == 0) {
		return;
	}

	r = setAccessor(self, 
		[NSString stringWithFormat:@"_set%@", [key capitalizedString]], 
		value);
	if (r == 0) {
		return;
	}

	r = setAttribute(self, [NSString stringWithFormat:@"_%@", key], value);
	if (r == 0) {
		return;
	}


	/* Call super */
	NS_DURING
		super.class = find_real_superclass(
			GETISA(self),
			_meth,
			class_getInstanceMethod,
			(IMP)object_method_takeValue_forKey_);
		super.receiver = self;
		(void)objc_msgSendSuper(&super, _meth, value, key);
	NS_HANDLER
		/* Parent doesn't know the key, try to create in the 
		 * python side, just like for plain python objects.
		 */
		if ([[localException name] isEqual:@"NSUnknownKeyException"]) {
			PyObject* selfObj = PyObjCObject_New(self);
			PyObject* val;

			val = pythonify_c_value(@encode(id), &value);
			if (val == NULL) {
				PyErr_Clear();
				[localException raise];
			}

			r = PyObject_SetAttrString(selfObj, 
				(char*)[key cString],
				val);
			Py_DECREF(val);
			if (r == -1) {
				PyErr_Clear();
				[localException raise];
			}
				
		} else {
			[localException raise];
		}
	NS_ENDHANDLER
}