Source

delPython / delPython.pas

   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
{ delPython v1.0 - A library for interfacing existing Delphi functionality to Python.
  http://bitbucket.org/utku/delpython/

  (c) 2009-2010 M.Utku Karataş. <m.utku.k@gmail.com>
  This library is freely distributable under the terms of the MIT license.

  Requirements:
    - Delphi 2010 or later. Older versions are not supported (LitePython uses the latest RTTI
      tricks from Delphi 2010).
    - Python 2.6 - 2.7. Older versions and 3.x are not supported. Though Python 3.x shall be supported soon.

  * Some portions of code from PythonForDelphi package (xxx attribution to all P4D contributors).
}

//TODO: A LOT OF MEM LEAKS IN HERE FOR SURE!

unit delPython;

interface

uses
  Classes, SysUtils, Generics.Collections, Rtti;

{ -------------------------------------------------------------------------------------------------------------------- }
{ C API wrappers }

const
  single_input = 256;
  file_input = 257;
  eval_input = 258;
  PYTHON_API_VERSION = 1013;

  METH_VARARGS = $1;

  { for tp_flags }
  Py_TPFLAGS_HAVE_GETCHARBUFFER = (1 shl 0);
  Py_TPFLAGS_HAVE_SEQUENCE_IN = (1 shl 1);
  Py_TPFLAGS_GC = (1 shl 2);
  Py_TPFLAGS_HAVE_INPLACEOPS = (1 shl 3);
  Py_TPFLAGS_CHECKTYPES = (1 shl 4);
  Py_TPFLAGS_HAVE_RICHCOMPARE = (1 shl 5);
  Py_TPFLAGS_HAVE_WEAKREFS = (1 shl 6);
  Py_TPFLAGS_HAVE_ITER = (1 shl 7);
  Py_TPFLAGS_HAVE_CLASS = (1 shl 8);
  Py_TPFLAGS_HEAPTYPE = (1 shl 9);
  Py_TPFLAGS_BASETYPE = (1 shl 10);
  Py_TPFLAGS_READY = (1 shl 12);
  Py_TPFLAGS_READYING = (1 shl 13);
  Py_TPFLAGS_HAVE_GC = (1 shl 14);
  Py_TPFLAGS_DEFAULT = Py_TPFLAGS_HAVE_GETCHARBUFFER or
                       Py_TPFLAGS_HAVE_SEQUENCE_IN or
                       Py_TPFLAGS_HAVE_INPLACEOPS or
                       Py_TPFLAGS_HAVE_RICHCOMPARE or
                       Py_TPFLAGS_HAVE_WEAKREFS or
                       Py_TPFLAGS_HAVE_ITER or
                       Py_TPFLAGS_HAVE_CLASS;

type
  unused_python_pointer_type = pointer; // some types are just not needed to be even declared.
  PPyObject = ^PyObject;
  PPyTypeObject = ^PyTypeObject;
  PPyIntObject = ^PyIntObject;
  PPPyObject = ^PPyObject;

  pydestructor = procedure(ob: PPyObject); cdecl;
  printfunc = function(ob: PPyObject; var f: file; i: integer): integer; cdecl;
  getattrfunc = function(ob1: PPyObject; name: PAnsiChar): PPyObject; cdecl;
  setattrfunc = function(ob1: PPyObject; name: PAnsiChar; ob2: PPyObject): integer; cdecl;
  cmpfunc = function(ob1, ob2: PPyObject): integer; cdecl;
  reprfunc = function(ob: PPyObject): PPyObject; cdecl;
  PyCFunction = function(self, args: PPyObject): PPyObject; cdecl;
  newfunc = function(subtype: PPyTypeObject; args, kwds: PPyObject): PPyObject; cdecl;
  allocfunc = function(self: PPyTypeObject; nitems: integer): PPyObject; cdecl;
  binaryfunc = function(ob1, ob2: PPyObject): PPyObject; cdecl;
  ternaryfunc = function(self, args, kwds : PPyObject): PPyObject; cdecl;
  objobjargproc = function(ob1, ob2, ob3 : PPyObject): integer; cdecl;
  inquiry = function(ob1: PPyObject): integer; cdecl;

  PPyMethodDef = ^PyMethodDef;
  PyMethodDef = packed record
    ml_name: PAnsiChar;
    ml_meth: PyCFunction;
    ml_flags: integer;
    ml_doc: PAnsiChar;
  end;

  PPyMappingMethods = ^PyMappingMethods;
  PyMappingMethods = packed record
     mp_length: inquiry;
     mp_subscript: binaryfunc;        // --> PyObject* PyObject_GetItem(PyObject *o, PyObject *key)
     mp_ass_subscript: objobjargproc; // --> int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v)¶
  end;

  TGenericGetterFunc = reference to function(obj: TObject; i: integer): TValue;
  TGenericSetterFunc = reference to procedure(obj: TObject; i: integer; value: TValue);

  TExtraPropEntry = class
  public
    GetterFunc: TGenericGetterFunc;
    SetterFunc: TGenericSetterFunc;
  end;
  
  PyTypeObject = packed record
    ob_refcnt: integer;
    ob_type: PPyTypeObject;
    ob_size: integer; // Number of items in variable part
    tp_name: PAnsiChar; // For printing
    tp_basicsize, tp_itemsize: integer; // For allocation

    // Methods to implement standard operations
    tp_dealloc: pydestructor;
    tp_print: printfunc;
    tp_getattr: getattrfunc;
    tp_setattr: setattrfunc;
    tp_compare: cmpfunc;
    tp_repr: reprfunc;

    // Method suites for standard classes
    tp_as_number: unused_python_pointer_type; // PPyNumberMethods;
    tp_as_sequence: unused_python_pointer_type; // PPySequenceMethods;
    tp_as_mapping: unused_python_pointer_type; // PPyMappingMethods;

    // More standard operations (here for binary compatibility)
    tp_hash: unused_python_pointer_type; // hashfunc;
    tp_call: ternaryfunc;
    tp_str: unused_python_pointer_type; // reprfunc;
    tp_getattro: unused_python_pointer_type; // getattrofunc;
    tp_setattro: unused_python_pointer_type; // setattrofunc;

    // Functions to access object as input/output buffer
    tp_as_buffer: unused_python_pointer_type; // PPyBufferProcs;

    // Flags to define presence of optional/expanded features
    tp_flags: LongInt;

    tp_doc: PAnsiChar; // Documentation AnsiString
    tp_traverse: unused_python_pointer_type; // traverseproc;
    tp_clear: unused_python_pointer_type; // inquiry;
    tp_richcompare: unused_python_pointer_type; // richcmpfunc;
    tp_weaklistoffset: Longint;
    tp_iter: unused_python_pointer_type; // getiterfunc;
    tp_iternext: unused_python_pointer_type; // iternextfunc;

    // Attribute descriptor and subclassing stuff
    tp_methods          : unused_python_pointer_type; //PPyMethodDef;
    tp_members          : unused_python_pointer_type; // PPyMemberDef;
    tp_getset           : unused_python_pointer_type; // PPyGetSetDef;
    
    tp_base             : unused_python_pointer_type; // PPyTypeObject;
    tp_dict             : unused_python_pointer_type; // PPyObject;
    tp_descr_get        : unused_python_pointer_type; // descrgetfunc;
    tp_descr_set        : unused_python_pointer_type; // descrsetfunc;
    tp_dictoffset       : longint;
    tp_init             : unused_python_pointer_type; // initproc;
    tp_alloc            : allocfunc;
    tp_new              : newfunc;
    tp_free             : pydestructor; // Low-level free-memory routine
    tp_is_gc            : unused_python_pointer_type; // inquiry; // For PyObject_IS_GC
    tp_bases            : unused_python_pointer_type; // PPyObject;
    tp_mro              : unused_python_pointer_type; // PPyObject; // method resolution order
    tp_cache            : unused_python_pointer_type; // PPyObject;
    tp_subclasses       : unused_python_pointer_type; // PPyObject;
    tp_weaklist         : unused_python_pointer_type; // PPyObject;
    tp_del              : unused_python_pointer_type; // pydestructor;

    // xxx rest ripped... object.h

    // extra field for ExtraProps
    tp_extra_props: TStringList;
  end;

  PyObject = packed record
    ob_refcnt: integer;
    ob_type: PPyTypeObject;
  end;

  PyIntObject = packed record
    ob_refcnt : Integer;
    ob_type   : PPyTypeObject;
    ob_ival   : LongInt;
  end;

{ -------------------------------------------------------------------------------------------------------------------- }

type
  EPythonError = class(Exception);
  EPythonDllImportError = class(EPythonError);

  TValueArray = TArray<TValue>;

  TPythonDLL = class
  public
    { Wrapping actual Python API functions }
    Py_Initialize: procedure; cdecl;
    PyEval_InitThreads: procedure; cdecl;
    Py_InitModule4: function(name: PAnsiChar; methods: PPyMethodDef; doc: PAnsiChar;
      self_: PPyObject; apiver: integer): PPyObject; cdecl;
    PyRun_String: function(str: PAnsiChar; start: integer; globals: PPyObject; locals: PPyObject): PPyObject; cdecl;
    PyErr_Print: procedure; cdecl;
    PySys_GetObject: function(s: PAnsiChar): PPyObject; cdecl;
    PyObject_Str: function(v: PPyObject): PPyObject; cdecl;
    PyObject_Repr: function(ob: PPyObject): PPyObject; cdecl;
    PyString_AsString: function(ob: PPyObject): PAnsiChar; cdecl;
    PyType_IsSubtype: function(a, b: PPyTypeObject): integer; cdecl;
    PyImport_AddModule: function(name: PAnsiChar): PPyObject; cdecl;
    PyModule_GetDict: function(module: PPyObject): PPyObject; cdecl;
    PyType_GenericNew: function(atype: PPyTypeObject; args, kwds: PPyObject): PPyObject; cdecl;
    PyType_Ready: function(atype: PPyTypeObject): integer; cdecl;
    PyModule_AddObject: function(amodule: PPyObject; aname: PAnsiChar; value: PPyObject): PPyObject; cdecl;
    _PyObject_New: function(typ: PPyTypeObject): PPyObject; cdecl;
    PyString_FromString: function(str: PAnsiChar): PPyObject; cdecl;
    PyInt_AsLong: function(ob: PPyObject): LONGINT; cdecl;
    PyTuple_Size: function(ob: PPyObject): integer; cdecl;
    PyTuple_GetItem: function(ob: PPyObject; i: integer): PPyObject; cdecl;
    PyUnicode_AsWideChar: function(unicode: PPyObject; w: PWideChar; size: integer): integer; cdecl;
    PySequence_Length: function(ob: PPyObject): integer; cdecl;
    PyInt_FromLong: function(x: LongInt): PPyObject; cdecl;
    PyObject_GetAttrString: function(ob: PPyObject; key: PAnsiChar): PPyObject; cdecl;
    PyObject_SetAttrString: function(ob: PPyObject; key: PAnsiChar; value: PPyObject): integer; cdecl;
    PyCallable_Check: function(ob: PPyObject): integer; cdecl;
    PyObject_CallObject: function(ob, args: PPyObject): PPyObject; cdecl;
    PyDict_New: function: PPyObject; cdecl;
    PyDict_GetItemString: function(dp: PPyObject; key: PAnsiChar): PPyObject; cdecl;
    PyDict_SetItemString: function(dp: PPyObject; key: PAnsiChar; item: PPyObject): Integer; cdecl;
    PyTuple_New: function(size: integer): PPyObject; cdecl;
    PyTuple_SetItem: function(ob: PPyObject; key: integer; value: PPyObject): integer; cdecl;
    PyErr_SetString: procedure(ErrorObject: PPyObject; text: PAnsiChar); cdecl;

    PyString_Type: PPyTypeObject;
    PyUnicode_Type: PPyTypeObject;
    PyInt_Type: PPyTypeObject;
    PyTuple_Type: PPyTypeObject;
    PyDict_Type: PPyTypeObject;
    Py_None: PPyObject;
    Py_False: PPyIntObject;
    Py_True: PPyIntObject;
    PyExc_RuntimeError: PPPyObject;
  private
    { Helper methods }
    fDLLHandle: THandle;
    procedure Py_INCREF(op: PPyObject);
    procedure Py_XDECREF(op: PPyObject);
    procedure Py_DECREF(op: PPyObject);
    function Py_InitModule(const name: PAnsiChar; methods: PPyMethodDef): PPyObject;
    function PyString_Check(obj: PPyObject): Boolean;
    function PyUnicode_Check(obj: PPyObject): Boolean;
    function PyObject_TypeCheck(obj: PPyObject; t: PPyTypeObject): Boolean;
    function PyInt_Check(obj: PPyObject): Boolean;
    function PyTuple_Check(obj: PPyObject): boolean;
    function ReturnNone: PPyObject;
    function ReturnBool(b: Boolean): PPyObject;
    function GetMainModule: PPyObject;
    function PyObjectAsString(obj: PPyObject): AnsiString;
    function PyTupleToTValueArray(tuple: PPyObject): TValueArray;
    function PyObjectToTValue(obj: PPyObject): TValue;
    function PyString_AsDelphiString(obj: PPyObject): string;
    function PyUnicode_AsWideString(obj: PPyObject): widestring;
  public
    function Import(const funcname: AnsiString; canFail: Boolean = True): Pointer;
    procedure LoadDll(const DllPath: string); // raise exc. on errors
  end;

  TPythonWriteNotification = procedure(const Data: string) of object;

  TdpObject = class;

  TPythonEngine = class(TPythonDLL)
  private
    fOnOutput: TPythonWriteNotification;
    class function ConvertToPAnsiChar(const S: string): PAnsiChar;
    procedure generic_event;
  public
    constructor Create;
    destructor Destroy; override;

    { High level execution.
      These do never raise Delphi exceptions. }
    function Exec(const Code: string): boolean;   // Returns false if Code raises any exceptions.
    function Eval(const Code: string): PPyObject; // Returns nil if Code raises any exceptions.
    function EvalStr(const Code: string): string;
  public
    { interfacing Delphi to Python }
    fPythonType_DelphiType_Map: TDictionary<PPyTypeObject, TClass>;
    fModule: PPyObject;
    procedure CreateModule(aModuleName: AnsiString);

    procedure DeclareClass(aClass: TClass);
    procedure DeclareGlobal(const VarNameInPython: string; DelphiEntity: TObject);
    function WrapMethodCall(anActualObj: TObject; LMethod: string): PPyObject;
    function WrapProperty(anActualObj: TObject; LProp: string): PPyObject;
    function WrapValue(aValue: TValue): PPyObject;
    procedure FixProp(aClass: TClass; aPropName: string; aGetter: TGenericGetterFunc; aSetter: TGenericSetterFunc);

    class function DPO(aPythonObject: PPyObject): TdpObject;

    procedure RedirectOutput;
    property OnOutput: TPythonWriteNotification read fOnOutput write fOnOutput;
  end;

  TdpObject = class
  private
    function GetAsString: string;
  protected
    fPyObj: PPyObject;
    function GetI(const k: ansistring): integer; virtual;
    function GetO(const k: ansistring): TdpObject; virtual;
    function GetS(const k: ansistring): ansistring; virtual;
    procedure PutI(const k: ansistring; const Value: integer); virtual;
    procedure PutO(const k: ansistring; const Value: TdpObject); virtual;
    procedure PutS(const k, Value: ansistring); virtual;
  public
    constructor Create(aPythonObj: PPyObject);
    destructor Destroy; override;

    { If the object is a Python method }
    function Call(const Args: array of const): TdpObject;

    { If the object is a Python object use these Field accessors }
    property O[const k: ansistring]: TdpObject read GetO write PutO; default;
    property S[const k: ansistring]: ansistring read GetS write PutS;
    property I[const k: ansistring]: integer read GetI write PutI;

    { If the object is a Python string }
    property AsString: string read GetAsString;
  end;

  TdpDict = class(TdpObject)
  protected
    { override the field access methods to turn them into Key/Value accesses }
    function GetI(const k: ansistring): integer; override;
    function GetO(const k: ansistring): TdpObject; override;
    function GetS(const k: ansistring): ansistring; override;
    procedure PutI(const k: ansistring; const Value: integer); override;
    procedure PutO(const k: ansistring; const Value: TdpObject); override;
    procedure PutS(const k, Value: ansistring); override;
  end;

var
  python: TPythonEngine;

implementation

uses
  Windows, Dialogs, TypInfo, ObjAuto;

{ -------------------------------------------------------------------------------------------------------------------- }
{ TPythonDLL }

function TPythonDLL.Import(const funcname: AnsiString; canFail: Boolean): Pointer;
begin
  Result := GetProcAddress(fDLLHandle, PAnsiChar(funcname));
  if (Result = nil) and canFail then
    raise EPythonDllImportError.CreateFmt('Error %d: could not map symbol "%s"', [GetLastError, funcname]);
end;

procedure TPythonDLL.LoadDll(const DllPath: string);
begin
  fDLLHandle := SafeLoadLibrary(DllPath);
  if fDLLHandle = 0 then
    raise EPythonDllImportError.Create('Couldn''t load DLL ' + DllPath);

  @PyRun_String           := Import('PyRun_String');
  @Py_Initialize          := Import('Py_Initialize');
  @PyEval_InitThreads     := Import('PyEval_InitThreads');
  @Py_InitModule4         := Import('Py_InitModule4');
  @PyErr_Print            := Import('PyErr_Print');
  @PySys_GetObject        := Import('PySys_GetObject');
  @PyObject_Str           := Import('PyObject_Str');
  @PyObject_Repr          := Import('PyObject_Repr');
  @PyString_AsString      := Import('PyString_AsString');
  @PyType_IsSubtype       := Import('PyType_IsSubtype');
  @PyImport_AddModule     := Import('PyImport_AddModule');
  @PyModule_GetDict       := Import('PyModule_GetDict');
  @PyType_GenericNew      :=Import('PyType_GenericNew');
  @PyType_Ready           := Import('PyType_Ready');
  @PyModule_AddObject     := Import('PyModule_AddObject');
  @_PyObject_New          := Import('_PyObject_New');
  @PyString_FromString    := Import('PyString_FromString');
  @PyInt_AsLong           := Import('PyInt_AsLong');
  @PyTuple_Size           := Import('PyTuple_Size');
  @PyTuple_GetItem        := Import('PyTuple_GetItem');
  @PySequence_Length      := Import('PySequence_Length');
  @PyUnicode_AsWideChar   := Import('PyUnicodeUCS2_AsWideChar');
  @PyInt_FromLong         := Import('PyInt_FromLong');
  @PyObject_GetAttrString := Import('PyObject_GetAttrString');
  @PyObject_SetAttrString := Import('PyObject_SetAttrString');
  @PyCallable_Check       := Import('PyCallable_Check');
  @PyObject_CallObject    := Import('PyObject_CallObject');
  @PyDict_New             := Import('PyDict_New');
  @PyDict_GetItemString   := Import('PyDict_GetItemString');
  @PyDict_SetItemString   := Import('PyDict_SetItemString');
  @PyTuple_New            := Import('PyTuple_New');
  @PyTuple_SetItem        := Import('PyTuple_SetItem');
  @PyErr_SetString        := Import('PyErr_SetString');

  Py_None                 := Import('_Py_NoneStruct');
  Py_False                := Import('_Py_ZeroStruct');
  Py_True                 := Import('_Py_TrueStruct');
  PyString_Type           := Import('PyString_Type');
  PyUnicode_Type          := Import('PyUnicode_Type');
  PyInt_Type              := Import('PyInt_Type');
  PyTuple_Type            := Import('PyTuple_Type');
  PyDict_Type             := Import('PyDict_Type');
  PyExc_RuntimeError      := Import('PyExc_RuntimeError');

  Py_Initialize;
  PyEval_InitThreads;
end;

function TPythonDLL.PyObject_TypeCheck(obj: PPyObject; t: PPyTypeObject): Boolean;
begin
  Result := Assigned(obj) and (obj^.ob_type = t);
  if not Result and Assigned(obj) and Assigned(t) then
    Result := PyType_IsSubtype(obj^.ob_type, t) = 1;
end;

function TPythonDLL.PyString_Check(obj: PPyObject): Boolean;
begin
  Result := PyObject_TypeCheck(obj, PyString_Type);
  if not Result then
    Result := PyObject_TypeCheck(obj, PyUnicode_Type);
end;

function TPythonDLL.PyTupleToTValueArray(tuple: PPyObject): TValueArray;
var
  i: integer;
begin
  if not PyTuple_Check(tuple) then
    raise EPythonError.Create('The python object is not a tuple');
  SetLength(Result, PyTuple_Size(tuple));
  for i := 0 to Length(Result) - 1 do
    Result[i] := PyObjectToTValue(PyTuple_GetItem(tuple, i));
end;

function TPythonDLL.PyObjectToTValue(obj: PPyObject): TValue;
begin
  if PyInt_Check(obj) then
    Result := PyInt_AsLong(obj)
  else if PyUnicode_Check(obj) then
    Result := PyUnicode_AsWideString(obj)
  else if PyString_Check(obj) then
    Result := PyObjectAsString(obj)
  else
    raise EPythonError.CreateFmt('xxx PyObjectToTValue: unsupported type "%s"', [obj.ob_type.tp_name]);
end;

function TPythonDLL.PyTuple_Check(obj: PPyObject): boolean;
begin
  Result := PyObject_TypeCheck(obj, PyTuple_Type);
end;

function TPythonDLL.PyUnicode_Check(obj: PPyObject): Boolean;
begin
  Result := PyObject_TypeCheck(obj, PyUnicode_Type);
end;

function TPythonDLL.PyUnicode_AsWideString(obj: PPyObject): widestring;
var
  _size: integer;
begin
  _size := PySequence_Length(obj);
  if _size > 0 then
  begin
    SetLength(Result, _size);
    if PyUnicode_AsWideChar(obj, @Result[1], _size) <> _size then
      raise EPythonError.Create('Could not copy the whole Unicode AnsiString into its buffer');
  end
  else
    Result := '';
end;

function TPythonDLL.PyString_AsDelphiString(obj: PPyObject): string;
begin
  if PyUnicode_Check(obj) then
    Result := PyUnicode_AsWideString(obj)
  else
    Result := PyString_AsString(obj);
end;

procedure TPythonDLL.Py_DECREF(op: PPyObject);
begin
  with op^ do
  begin
    Dec(ob_refcnt);
    if ob_refcnt = 0 then
    begin
      ob_type^.tp_dealloc(op);
    end;
  end;
end;

procedure TPythonDLL.Py_INCREF(op: PPyObject);
begin
  Inc(op^.ob_refcnt);
end;

function TPythonDLL.Py_InitModule(const name: PAnsiChar; methods: PPyMethodDef): PPyObject;
begin
  Result := Py_InitModule4(name, methods, nil, nil, PYTHON_API_VERSION);
end;

procedure TPythonDLL.Py_XDECREF(op: PPyObject);
begin
  if op <> nil then
    Py_DECREF(op);
end;

function TPythonDLL.ReturnBool(b: Boolean): PPyObject;
begin
  if b then Result := PPyObject(Py_True)
       else Result := PPyObject(Py_False);
  Py_INCREF(Result);
end;

function TPythonDLL.ReturnNone: PPyObject;
begin
  Result := Py_None;
  Py_INCREF(Result);
end;

function TPythonDLL.PyInt_Check(obj: PPyObject): Boolean;
begin
  Result := PyObject_TypeCheck(obj, PyInt_Type);
end;

// todo: horrible implementation
function TPythonDLL.PyObjectAsString(obj: PPyObject): AnsiString;
var
  s: PPyObject;
  u: string;
  _size: integer;
begin
  Result := '';
  if not Assigned(obj) then
    Exit;

  if PyUnicode_Check(obj) then
  begin
    _size := PySequence_Length(obj);
    SetLength(Result, _size);
    if PyUnicode_AsWideChar(obj, @Result[1], _size) <> _size then
      raise EPythonError.Create('Could not copy the whole Unicode AnsiString into its buffer');
    u := Result;
    Exit(u);
  end;

  //xxx gereksiz asagisi?
  s := PyObject_Str(obj);
  if Assigned(s) and PyString_Check(s) then
  begin
    Result := PyString_AsString(s);
  end;
  Py_XDECREF(s);
end;

function TPythonDLL.GetMainModule: PPyObject;
begin
  Result := PyImport_AddModule(PAnsiChar('__main__'));
end;

{ -------------------------------------------------------------------------------------------------------------------- }
{ TLitePython }

constructor TPythonEngine.Create;
begin
  inherited;
  fPythonType_DelphiType_Map := TDictionary<PPyTypeObject, TClass>.Create;
end;

destructor TPythonEngine.Destroy;
begin
  FreeAndNil(fPythonType_DelphiType_Map);
  inherited;
end;

class function TPythonEngine.DPO(aPythonObject: PPyObject): TdpObject;
begin
  with python do
    if PyObject_TypeCheck(aPythonObject, PyDict_Type) then
      Result := TdpDict.Create(aPythonObject)
    else
      Result := TdpObject.Create(aPythonObject);
end;

var
  gKeepStrings: array of AnsiString; // will leak

{ Convert the given Unicode value S to ANSI and increase the ref. count so that returned pointer stays valid }
class function TPythonEngine.ConvertToPAnsiChar(const S: string): PAnsiChar;
var temp: AnsiString;
begin
  SetLength(gKeepStrings, Length(gKeepStrings) + 1);
  temp := Utf8ToAnsi(UTF8Encode(S));
  gKeepStrings[High(gKeepStrings)] := temp; // keeps the resulting pointer valid by incresing the ref. count of temp.
  Result := PAnsiChar(temp);
end;

  //xxx
  function CleanString(const s : AnsiString) : AnsiString;
  var
    i : Integer;
  begin
    result := s;
    if s = '' then
      Exit;
    i := Pos(#13,s);
    while i > 0 do
      begin
        Delete( result, i, 1 );
        i := Pos(#13,result);
      end;
    if result[length(result)] <> #10 then
      Insert(#10, result, length(result)+1 );
  end;

function TPythonEngine.Exec(const Code: string): boolean;
var
  ansiCode: AnsiString;
  pyobj: PPyObject;
  m, _locals, _globals: PPyObject;
begin
  Result := False;
  m := GetMainModule;
  if m = nil then
    raise EPythonError.Create('Exec: can''t create __main__');
  _locals := PyModule_GetDict(m);
  _globals := PyModule_GetDict(m);

  ansiCode := Utf8ToAnsi(UTF8Encode(Code));
  ansiCode := CleanString(ansiCode);

  try
    pyobj := PyRun_String(PAnsiChar(ansiCode), file_input, _globals, _locals);
    if pyobj = nil then // the Python code passed raised an exception
      PyErr_Print;
    Result := True;
  except
    // Delphi code raised an exception.. wrap this exception into a Python exception..
    PyErr_SetString(PyExc_RuntimeError^,
      PAnsiChar(AnsiString('delPython internal FAIL: ' + Exception(ExceptObject).Message)));
    PyErr_Print;
  end;
  Py_XDECREF(pyobj);
end;

function TPythonEngine.Eval(const Code: string): PPyObject;
var
  ansiCode: AnsiString;
  m, _locals, _globals: PPyObject;
begin
  m := GetMainModule;
  if m = nil then
    raise EPythonError.Create('Exec: can''t create __main__');
  _locals := PyModule_GetDict(m);
  _globals := PyModule_GetDict(m);

  ansiCode := Utf8ToAnsi(UTF8Encode(Code));
  ansiCode := CleanString(ansiCode);

  Result := nil;
  try
    Result := PyRun_String(PAnsiChar(ansiCode), eval_input, _globals, _locals);
    if Result = nil then // the Python code passed raised an exception
      PyErr_Print;
  except
    // Delphi code raised an exception.. wrap this exception into a Python exception..
    PyErr_SetString(PyExc_RuntimeError^,
      PAnsiChar(AnsiString('delPython internal FAIL: ' + Exception(ExceptObject).Message)));
    PyErr_Print;
  end;
end;

function TPythonEngine.EvalStr(const Code: string): string;
begin
  Result := PyObjectAsString(Eval(Code));
end;

{ -------------------------------------------------------------------------------------------------------------------- }
{ Introducing a new type from native code.
  See http://docs.python.org/extending/newtypes.html }

type
  { Don't use Delphi managed types like string in this struct. Because the allocation is done by Python.}
  PPyObjectPuppet = ^TPyObjectPuppet;
  TPyObjectPuppet = packed record // this is the actual structure that gets created by python
    ob_refcnt: integer;
    ob_type: PPyTypeObject;

    actual_obj: TObject; // and this is a link to the Delphi object under covers.
    method_name: PAnsiChar; // for callable types, link to the Delphi method to call..
  end;

  procedure puppet_dealloc(self: PPyObject); cdecl;
  begin
    self.ob_type.tp_free(self);
  end;

  function puppet_new(subtype: PPyTypeObject; args, kwds: PPyObject): PPyObject; cdecl;
  var
    LContext: TRttiContext;
    LCons: TRTTIMethod;
    aClass: TClass;
  begin
    Result := subtype.tp_alloc(subtype, 0);
    if Result <> nil then
    begin
      // right place to call the delphi constructor
      LContext := TRttiContext.Create;
      aClass := python.fPythonType_DelphiType_Map[subtype];
      LCons := LContext.GetType(aClass).AsInstance.GetMethod('Create'); // todo: only Create method supported for now
      PPyObjectPuppet(Result).actual_obj := LCons.Invoke(aClass, []).AsObject;
    end;
  end;

  function puppet_get(ob1: PPyObject; name: PAnsiChar): PPyObject; cdecl;
  var 
    LMethod: TRttiMethod;
    LProp: TRttiProperty;
    LField: TRttiField;
    actual_obj: TObject;
    idx: integer;
  begin
    actual_obj := PPyObjectPuppet(ob1).actual_obj;

    { first, lookup the methods }
    LMethod := TRttiContext.Create.GetType(actual_obj.ClassInfo).GetMethod(name);
    if LMethod <> nil then
      EXIT(python.WrapMethodCall(actual_obj, LMethod.Name));

    { then lookup the properties }
    LProp := TRttiContext.Create.GetType(actual_obj.ClassInfo).GetProperty(name);
    if LProp <> nil then
      EXIT(python.WrapProperty(actual_obj, LProp.Name));

    { then lookup fields }
    LField := TRttiContext.Create.GetType(actual_obj.ClassInfo).GetField(name);
    if LField <> nil then
      EXIT(python.WrapValue(LField.GetValue(actual_obj)));

// xxx   { lookup the extra fields }
//    if ob1.ob_type.tp_extra_props <> nil then
//    begin
//      if ob1.ob_type.tp_extra_props.Find(name, idx) then
//      begin
//        TExtraPropEntry(ob1.ob_type.tp_extra_props.Objects[idx]).
//      end;
//    end;


    raise EPythonError.CreateFmt('xxx field lookup failed for %s.%s', [actual_obj.ClassName, name]);
  end;

  function ValueFromPyobject(pyobj: PPyObject): TValue; forward;

  procedure TPythonEngine.generic_event;
  begin
    showmessage('xxx TLitePython.generic_event');
  end;

type
    tgenericevent = procedure of object;

    TMethodHandler = class(TInterfacedObject, IMethodHandler)
    public
      function Execute(const Args: array of Variant): Variant;
      function InstanceToVariant(Instance: TObject): Variant;
    end;

    function TMethodHandler.Execute(const Args: array of Variant): Variant;
    begin
      showmessage('xxx TMethodHandler.Execute');
    end;

    function TMethodHandler.InstanceToVariant(Instance: TObject): Variant;
    begin
      showmessage('xxx TMethodHandler.InstanceToVariant');
    end;

  var methodhandler: TMethodHandler;

  procedure SetEventFromPython(actual_obj: TObject; LProp: TRttiProperty; pyfunc: PPyObject);
  var
    v: TValue;
    typdata: PTypeData;
    pp: PPropInfo;

    m: TMethod;
  begin
    showmessage('aha event ' + LProp.Name + ' aha python fonk ' + python.PyObjectAsString(python.PyObject_Repr(pyfunc)));
    //v := TValue.From<tgenericevent>(python.generic_event);
    //LProp.SetValue(actual_obj, v);

    New(typdata);
    pp := GetPropInfo(actual_obj, LProp.Name, [tkMethod]);
    typdata := GetTypeData(pp.PropType^); //GetTypeData(LProp.Handle);
    ShowMEssage(inttostr(typdata.ParamCount));
    //typdata.MethodKind := mkProcedure;
    //typdata.ParamCount := 0;
    methodhandler := TMethodHandler.Create;
    m := objauto.CreateMethodPointer(methodhandler, typdata); // xxx refcount problem

    //v := TValue.From<TMethod>(m);
    //LProp.SetValue(actual_obj, v);

    SetMethodProp(actual_obj, LProp.Name, m);
  end;

{
  from http://blogs.embarcadero.com/abauer?s=fclickmethod

  PropInfo := GetPropInfo(CheckBox1, ‘OnClick’, [tkMethod]);
  FClickMethod := CreateMethodPointer(Disp, Id, PropInfo.PropType^);
  SetMethodProp(CheckBox1, ‘OnClick’, FClickMethod);
}

  var gEnableVarParameters: boolean = True;

  function puppet_set(ob1: PPyObject; name: PAnsiChar; ob2: PPyObject): integer; cdecl;
  var
    actual_obj: TObject;
    LProp: TRttiProperty;
  begin
    actual_obj := PPyObjectPuppet(ob1).actual_obj;

    { lookup the properties }
    LProp := TRttiContext.Create.GetType(actual_obj.ClassInfo).AsInstance.GetProperty(name);
    if LProp <> nil then
    begin

      { SPECIAL CASE - settings an event handler from Python }
      if LProp.PropertyType is TRttiMethodType then
      begin
        SetEventFromPython(actual_obj, LProp, ob2);
        EXIT(0);
      end;

      LProp.SetValue(actual_obj, ValueFromPyobject(ob2));
    end;

    result := 0; // or return -1 on failure
  end;

  function puppet_call(self, args, kwds : PPyObject): PPyObject; cdecl;
  var
    LContext: TRttiContext;
    LMethod: TRttiMethod;
    LReturn: TValue;
    LArgs, LArgsCopy: TValueArray;

    procedure PreCall; // check var args.
    var
      i, j: integer;
      params: TArray<TRttiParameter>;
    begin
      LArgsCopy := nil;
      params := LMethod.GetParameters;
      for i := Low(params) to High(params) do
      begin
        if TParamFlag.pfVar in params[i].Flags then
        begin
          // there's a var parameter, have a copy of arguments
          SetLength(LArgsCopy, Length(LArgs));
          for j := 0 to High(LArgsCopy) do LArgsCopy[i] := LArgs[i];
        end;
      end;
    end;

    procedure PostCall; // check var args.
    var
      i: integer;
      params: TArray<TRttiParameter>;
    begin
      params := LMethod.GetParameters;
      if LArgsCopy <> nil then
      begin
        for i := Low(LArgsCopy) to High(LArgsCopy) do
        begin
          //if LArgsCopy[i].Kind = tkInteger then //xxx
          //if LArgsCopy[i].AsInteger <> LArgs[i].AsInteger then
          //  Showmessage(LArgs[i].ToString);





          //xxx





        end;
      end;
    end;

      function TryMatchingSignature(const pythonParams: TValueArray; const delphiParams: TArray<TRttiParameter>): boolean;
      var
        i: Integer;
      begin
        Result := True;
        if Length(delphiParams) = Length(pythonParams) then // exact param count match
        begin
          for i := 0 to Length(delphiParams) - 1 do
          begin
            Result :=
                ((pythonParams[i].Kind in [tkString, tkUString, tkLString, tkWString]) and
                 (delphiParams[i].ParamType.TypeKind in [tkString, tkUString, tkLString, tkWString]))
                or
                (pythonParams[i].Kind = delphiParams[i].ParamType.TypeKind);

            if not Result then // doesn't match!
              Exit(False);
          end;
        end;
      end;

    function FindRTTIMethodBasedOnSignature(const aMethodName: ansistring): TRttiMethod;
    var
      currentMethod: TRttiMethod;
    begin
      { Here is the tricky part - Delphi has method overloading.
        Method dispatching is really slow and extra shitty because of this.
        todo: Cache the RTTI to fix this problem. }
      Result := nil;
      LArgs := python.PyTupleToTValueArray(args); // Convert Python parameters to Delphi
      for currentMethod in LContext.GetType(PPyObjectPuppet(self)^.actual_obj.ClassInfo).GetMethods do
        if SameText(currentMethod.Name, aMethodName) then
        begin
          if TryMatchingSignature(LArgs, currentMethod.GetParameters)  then
          begin
            Exit(currentMethod);
          end;
        end;
    end;

    function ErrorSignature: string;
    var
      needed, given: string;
      i: integer;
    begin
      for i := 0 to Length(LMethod.GetParameters) - 1 do
      begin
        if i > 0 then needed := needed + ',';
        needed := needed + LMethod.GetParameters[i].ParamType.ToString;
      end;
      for i := 0 to Length(LArgs) - 1 do
      begin
        if i > 0 then given := given + ',';
        given := given + GetEnumName(Typeinfo(TTypeKind), ord(LArgs[i].Kind));
      end;
      Result := Format('Needed func(%s) but given func(%s)', [needed, given]);
    end;

  begin
    LArgs := nil;
    LContext := TRttiContext.Create;
    LMethod := FindRTTIMethodBasedOnSignature(PPyObjectPuppet(self)^.method_name);
    if LMethod = nil then
      raise EPythonError.CreateFmt('Method "%s" not found!', [PPyObjectPuppet(self)^.method_name]);

    { contruct a method call.. }
    //if gEnableVarParameters then PreCall;          // Pre call
    try
      LReturn := LMethod.Invoke(PPyObjectPuppet(self)^.actual_obj, LArgs);  // Invoke the method!
    except
      raise EPythonError.CreateFmt(
        'Error invoking Delphi method "%s" (Possible cause: wrong parameters; %s). Details: %s',
        [PPyObjectPuppet(self)^.method_name, ErrorSignature, Exception(ExceptObject).Message]);
    end;
    Result := python.WrapValue(LReturn);           // Convert Delphi result to Python
    //if gEnableVarParameters then PostCall;         // Post call
  end;

  function CreatePythonType(aClass: TClass): PPyTypeObject;
  var
    typ: PPyTypeObject;
    typName: ansistring;
  begin
    // todo: need a registry
      //typName := python.ConvertToPAnsiChar(aClass.ClassName); // xxx olmuyo lan!
      typName := aClass.ClassName;
      New(typ);
      FillChar(typ^, sizeof(PyTypeObject), 0);
      with typ^ do
      begin
        tp_name := PAnsiChar(typName); // For printing
        tp_basicsize := sizeof(TPyObjectPuppet);
        tp_flags := Py_TPFLAGS_DEFAULT;
        tp_doc := '';
        tp_dealloc := @puppet_dealloc;
        tp_new := @puppet_new;
        tp_getattr := @puppet_get;
        tp_setattr := @puppet_set;
        if python.PyType_Ready(typ) < 0 then
          raise EPythonError.Create('Type cannot be PyType_Ready''d properly!');
        python.Py_INCREF(PPyObject(typ));
        if python.fModule = nil then
          raise EPythonError.Create('CreateModule must be used before wrapping types');
        python.PyModule_AddObject(python.fModule, PAnsiChar(typName), PPyObject(typ));
      end;
      Result := typ;

      { Obtain the RTTI context }
      python.fPythonType_DelphiType_Map.Add(typ, aClass);
  end;

  function CreatePythonObject(anActualObject: TObject): PPyObject;
  var
    typ: PPyTypeObject;
  begin
    // xxx
    // first create a type object for the class of DelphiEntity. xxx todo: cache types!
    typ := CreatePythonType(anActualObject.ClassType); // her tip icin ayri python tipi yaratmak gereksiz

    // now create a python object from that type
    Result := python._PyObject_New(typ);
    PPyObjectPuppet(Result).actual_obj := anActualObject;
    python.Py_INCREF(Result);
  end;

  function CreateCallablePythonType: PPyTypeObject;
  var
    typ: PPyTypeObject;
    typName: ansistring;
  begin
    // todo: need a registry
      typName := 'lhjasdhkjf'; //xxx python.ConvertToPAnsiChar(LMethod.Name); // xxx olmuyo lan!
      New(typ);
      FillChar(typ^, sizeof(PyTypeObject), 0);
      with typ^ do
      begin
        tp_name := PAnsiChar('Delphi method call ' + typName); // For printing
        tp_basicsize := sizeof(TPyObjectPuppet);
        tp_flags := Py_TPFLAGS_DEFAULT;
        tp_doc := '';
        //tp_dealloc := @puppet_dealloc;
        tp_new := @python.PyType_GenericNew;
        //tp_getattr := @puppet_get;
        //tp_setattr := @puppet_set;
        tp_call := @puppet_call;
        if python.PyType_Ready(typ) < 0 then
          raise EPythonError.Create('Type cannot be PyType_Ready''d properly!');
        python.Py_INCREF(PPyObject(typ));
      end;
      Result := typ;
  end;

// xxx function ValueToPyobject(Value: TValue): PPyObject;
//  begin
//  end;

  function ValueFromPyobject(pyobj: PPyObject): TValue;
  begin
    if python.PyString_Check(pyobj) then
      Result := python.PyString_AsString(pyobj)
    else
    if python.PyInt_Check(pyobj) then
      Result := python.PyInt_AsLong(pyobj)
    else
    begin
      raise Exception.Create('ValueFromPyobject doesn''t know how to handle ' +
        python.PyObjectAsString(python.PyObject_Repr(pyobj)));
    end;
  end;

procedure TPythonEngine.DeclareClass(aClass: TClass);
begin
  CreatePythonType(aClass);
end;

function TPythonEngine.WrapMethodCall(anActualObj: TObject; LMethod: string): PPyObject;
begin
  // todo: need a registry
  // create a facade call object
  Result := _PyObject_New(CreateCallablePythonType);
  PPyObjectPuppet(Result).actual_obj := AnActualObj;
  PPyObjectPuppet(Result).method_name := ConvertToPAnsiChar(LMethod);
  Py_INCREF(Result);
end;

function TPythonEngine.WrapProperty(anActualObj: TObject; LProp: string): PPyObject;
var
  LLProp: TRttiProperty;
  v: TValue;
begin
  LLProp := TRttiContext.Create.GetType(AnActualObj.ClassInfo).GetProperty(LProp);
  v := LLProp.GetValue(AnActualObj);
  if v.IsEmpty then
    Result := Py_None
  else
    Result := WrapValue(v);
  Py_INCREF(Result);
end;

function TPythonEngine.WrapValue(aValue: TValue): PPyObject;
begin
  Result := nil;
  case aValue.Kind of
    tkUnknown: Result := Py_None;  // procedure calls return this
    tkInteger: Result := PyInt_FromLong(AValue.AsInteger);
    tkChar: ;
    tkEnumeration:
      begin
        // booleans are represented as tkEnumeration..
        if aValue.TypeData.BaseType^ = TypeInfo(Boolean) then
          Result := ReturnBool(aValue.AsBoolean);
      end;
    tkFloat: ;
    tkString: Result := PyString_FromString(ConvertToPAnsiChar(AValue.AsString));
    tkSet: ;
    tkClass: Result := CreatePythonObject(AValue.AsObject);
    tkMethod: ;
    tkWChar: ;
    tkLString: Result := PyString_FromString(ConvertToPAnsiChar(AValue.AsString));
    tkWString: Result := PyString_FromString(ConvertToPAnsiChar(AValue.AsString));
    tkVariant: ;
    tkArray: ;
    tkRecord: ;
    tkInterface: ;
    tkInt64: ;
    tkDynArray: ;
    tkUString: Result := PyString_FromString(ConvertToPAnsiChar(AValue.AsString));
    tkClassRef: ;
    tkPointer: ;
    tkProcedure: ;
  end;

  if Result <> nil then
    Py_INCREF(Result)
  else
    raise EPythonError.CreateFmt('xxx WrapValue NOT IMPLEMENTED for "%s" (%d) (%s)',
      [aValue.ToString, Integer(aValue.Kind),
       GetEnumName(TypeInfo(TTypeKind), ORD(aValue.Kind))]);
end;

procedure TPythonEngine.CreateModule(aModuleName: ansistring);

  function MethodDefs(Count: integer): PPyMethodDef; //xxx
  begin
    GetMem(Result, Count * sizeof(PyMethodDef));
    FillChar(Result^, Count * sizeof(PyMethodDef), 0);
  end;

begin
  fModule := Py_InitModule(PAnsiChar(aModuleName), MethodDefs(999));
  if fModule = nil then
    Raise EPythonError.Create('Error initing module ' + aModuleName);
end;

procedure TPythonEngine.DeclareGlobal(const VarNameInPython: string; DelphiEntity: TObject);
var
  Result: PPyObjectPuppet;
  typ: PPyTypeObject;
begin
  // first create a type object for the class of DelphiEntity.
  //todo: xxx cache these types!
  typ := CreatePythonType(DelphiEntity.ClassType);

  // now create a python object from that type
  Result := PPyObjectPuppet( _PyObject_New(typ) );
  PPyObjectPuppet(Result).actual_obj := DelphiEntity;
  PyModule_AddObject(python.fModule, ConvertToPAnsiChar(VarNameInPython), PPyObject(Result));
  Py_INCREF(PPyObject(Result));
end;

procedure TPythonEngine.FixProp;

  function KeyFromValue: PPyTypeObject;
  var
    pair: TPair<PPyTypeObject, TClass>;
  begin
    for pair in fPythonType_DelphiType_Map do
      if pair.Value = aClass then
        EXIT(pair.Key);
    Result := nil;
  end;

var
  typ: PPyTypeObject;
  extraProp: TExtraPropEntry;
begin
  typ := KeyFromValue;
  if typ = nil then raise EPythonError.Create('xxx Unknown class');

  if typ.tp_extra_props = nil then
  begin
    typ.tp_extra_props := TStringList.Create;
    typ.tp_extra_props.Sorted := True;
    typ.tp_extra_props.Duplicates := dupIgnore;
  end;
  extraProp := TExtraPropEntry.Create;
  extraProp.GetterFunc := aGetter;
  extraProp.SetterFunc := aSetter;
  typ.tp_extra_props.AddObject(aPropName, extraProp);
end;

type
  {$M+}
  TRedirector = class
  published
    procedure WriteU(const Data: string);
    procedure WriteA(const Data: ansistring);
  end;
  {$M-}

  procedure TRedirector.WriteU(const Data: string);
  begin
    if @python.fOnOutput <> nil then
      python.fOnOutput(Data);
  end;

  procedure TRedirector.WriteA(const Data: ansistring);
  begin
    if @python.fOnOutput <> nil then
      python.fOnOutput(Data);
  end;

procedure TPythonEngine.RedirectOutput;
begin
  if fModule = nil then    //PyImport_AddModule(PAnsiChar('__main__'));
    raise EPythonError.Create('CreateModule must be used before wrapping types');
  DeclareClass(TRedirector);
  Exec(
  '_redirector = pfaidelib_core.TRedirector()  ' + #13#10 + //xxx
  'class __TPythonEngineRedirector(object):' + #13#10 +
  '    softspace = 0                       ' + #13#10 +
  '    encoding = None                     ' + #13#10 +
  '    def write(self, data):              ' + #13#10 +
  '        if type(data) == type(u""):     ' + #13#10 +
  '            _redirector.WriteU(data)    ' + #13#10 +
  '        else:                           ' + #13#10 +
  '            _redirector.WriteA(data)    ' + #13#10 +
  '    def flush(self):                    ' + #13#10 +
  '        pass                            ' + #13#10 +
  'import sys; sys.stderr=sys.stdout=__TPythonEngineRedirector();' + #13#10
  );
end;

{ TdpObject }

constructor TdpObject.Create(aPythonObj: PPyObject);
begin
  fPyObj := aPythonObj;
end;

destructor TdpObject.Destroy;
begin
  inherited;
end;

function TdpObject.GetAsString: string;
begin
  with python do
    Result := PyObjectToTValue(fPyObj).AsString;
end;

function TdpObject.GetI(const k: ansistring): integer;
begin
  with python do
    Result := PyObjectToTValue(fPyObj).AsInteger;
end;

function TdpObject.GetO(const k: ansistring): TdpObject;
var pval: PPyObject;
begin
  with python do begin
    pval := PyObject_GetAttrString(fPyObj, PAnsiChar(k));
    if pval <> nil then
      Result := python.DPO(pval)
    else
      Result := nil;
  end;
end;

function TdpObject.GetS(const k: ansistring): ansistring;
begin
  with python do
    Result := PyObjectAsString(PyObject_GetAttrString(fPyObj, PAnsiChar(k)));
end;

procedure TdpObject.PutI(const k: ansistring; const Value: integer);
begin
  with python do
    PyObject_SetAttrString(fPyObj, PAnsiChar(k), PyInt_FromLong(Value)); //todo: Returns -1 on failure
end;

procedure TdpObject.PutO(const k: ansistring; const Value: TdpObject);
begin
  with python do
    PyObject_SetAttrString(fPyObj, PAnsiChar(k), Value.fPyObj); //todo: Returns -1 on failure
end;

procedure TdpObject.PutS(const k, Value: ansistring);
begin
  with python do
    PyObject_SetAttrString(fPyObj, PAnsiChar(k), PyString_FromString(PAnsiChar(Value)));
end;

function TdpObject.Call(const Args: array of const): TdpObject;
var
  i: integer;
  v: PVarRec;
  pArgsTuple, pResult: PPyObject;
begin
  Result := nil;
  with python do
  begin
    pArgsTuple := nil;
    if Length(Args) > 0 then
    begin
      pArgsTuple := PyTuple_New(Length(Args));
      for i := low(Args) to high(Args) do
      begin
        v := @Args[i];
        case v.VType of
          vtString,
          vtUnicodeString: PyTuple_SetItem(pArgsTuple, i, WrapValue(string(v.VString)));
          vtInteger: PyTuple_SetItem(pArgsTuple, i, WrapValue(string(v.VInteger)));
        else
          raise Exception.Create('xxx Unsupported parameter type in TdpObject.Call!');
        end;
      end;
    end;

    if Assigned(fPyObj) and (PyCallable_Check(fPyObj) <> 0) then // todo: else raise?
    begin
      pResult := PyObject_CallObject(fPyObj, pArgsTuple);
      if pResult <> nil then
      begin
        Result := DPO(pResult);
        if Assigned(pArgsTuple) then Py_DECREF(pArgsTuple);
      end
      else
        PyErr_Print;
        // and Result remains nil..
    end;
  end;
end;

{ TdpDict }

function TdpDict.GetI(const k: ansistring): integer;
begin
  with python do
    Result := PyObjectToTValue(PyDict_GetItemString(fPyObj, PAnsiChar(k))).AsInteger;
end;

function TdpDict.GetO(const k: ansistring): TdpObject;
var pval: PPyObject;
begin
  with python do begin
    pval := PyDict_GetItemString(fPyObj, PAnsiChar(k));
    if pval <> nil then
      Result := DPO(pval)
    else
      Result := nil;
  end;
end;

function TdpDict.GetS(const k: ansistring): ansistring;
begin
  with python do
    Result := PyString_AsDelphiString(PyDict_GetItemString(fPyObj, PAnsiChar(k)));
end;

procedure TdpDict.PutI(const k: ansistring; const Value: integer);
begin
  with python do
    PyDict_SetItemString(fPyObj, PAnsiChar(k), PyInt_FromLong(Value));
end;

procedure TdpDict.PutO(const k: ansistring; const Value: TdpObject);
begin
  with python do
    PyDict_SetItemString(fPyObj, PAnsiChar(k), Value.fPyObj);
end;

procedure TdpDict.PutS(const k, Value: ansistring);
begin
  with python do
    PyDict_SetItemString(fPyObj, PAnsiChar(k), PyString_FromString(PAnsiChar(Value)));
end;

initialization
  python := TPythonEngine.Create;
finalization
  python.Free;
end.