Source

delPython / delPython.pas

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

  (c) 2009 M.Utku Karatas. <m.utku.k@gmail.com>
  This library is freely distributable under the terms of the MIT license.
  Inspired by jQuery by John Resig and the jQuery Team - jquery.com.

  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.

  * Some portions of code from PythonForDelphi package (xxx attribution to all P4D contributors).
}
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;
  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;
  ternaryfunc = function(self, args, kwds : PPyObject): PPyObject; cdecl;

  PPyMethodDef = ^PyMethodDef;
  PyMethodDef = packed record
    ml_name: PAnsiChar;
    ml_meth: PyCFunction;
    ml_flags: integer;
    ml_doc: PAnsiChar;
  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
  end;

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

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

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

  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;
    PyString_Type: PPyTypeObject;
    PyUnicode_Type: PPyTypeObject;
    PyInt_Type: PPyTypeObject;
    PyTuple_Type: PPyTypeObject;
    Py_None: PPyObject;
  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 GetMainModule: PPyObject;
    function PyObjectAsString(obj: PPyObject): AnsiString;
    function PyTupleToTValueArray(tuple: PPyObject): TValueArray;
    function PyObjectToTValue(obj: PPyObject): TValue;
    procedure RaiseError;
    procedure CheckError;
  public
    function Import(const funcname: AnsiString; canFail: Boolean = True): Pointer;
    procedure LoadDll(const DllPath: string); // raise exc. on errors
  end;

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

    { high level execution }
    procedure Exec(const Code: string);
    function Eval(const Code: string): PPyObject;
    function EvalStr(const Code: string): string;
  public
    { interfacing Delphi to Python }
    fPythonType_DelphiType_Map: TDictionary<PPyTypeObject, TClass>;
    fModule: PPyObject;
    procedure CreateModule(aModuleName: AnsiString);

    procedure Wrap(aClass: TClass);
    function WrapMethodCall(anActualObj: TObject; LMethod: string): PPyObject;
    function WrapProperty(anActualObj: TObject; LProp: string): PPyObject;
    function WrapValue(aValue: TValue): PPyObject;

    procedure DeclareGlobal(const NameInPython: string; DelphiEntity: TObject);
  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 EDllImportError.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 EDllImportError.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');

  Py_None := Import('_Py_NoneStruct');
  PyString_Type := Import('PyString_Type');
  PyUnicode_Type := Import('PyUnicode_Type');
  PyInt_Type := Import('PyInt_Type');
  PyTuple_Type := Import('PyTuple_Type');

  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 Exception.Create('xxx unsupported type');
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;

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;

procedure TPythonDLL.RaiseError;
var
  err_type, err_value: PPyObject;
  s_type, s_value: AnsiString;
begin
  err_type := PySys_GetObject('last_type');
  err_value := PySys_GetObject('last_value');
  if Assigned(err_type) then
  begin
    // s_type := GetTypeAsString(err_type);
    // s_type := PyObjectAsString(err_type);
    s_type := PyObjectAsString(err_type);
    s_value := PyObjectAsString(err_value);
    raise EPythonError.CreateFmt('Python raised error %s with %s', [s_type, s_value]);
  end;
end;

procedure TPythonDLL.CheckError;
begin
  PyErr_Print;
  RaiseError;
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;

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;

procedure TPythonEngine.Exec(const Code: string);
var
  ansiCode: AnsiString;
  pyobj: PPyObject;
  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);

  pyobj := PyRun_String(PAnsiChar(ansiCode), file_input, _globals, _locals);
  if pyobj = nil then
    CheckError;
  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 := PyRun_String(PAnsiChar(ansiCode), eval_input, _globals, _locals);
  if Result = nil then
    CheckError;
  //Py_XDECREF(Result);
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..
    //LMethodName: string;
  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;
  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));

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

    { 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 fields }
    raise Exception.CreateFmt('xxx field lookup failed %s.%s', [actual_obj.ClassName, name]);
  end;

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

  procedure TPythonEngine.generic_event;
  begin
    showmessage('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('TMethodHandler.Execute');
    end;

    function TMethodHandler.InstanceToVariant(Instance: TObject): Variant;
    begin
      showmessage('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);
}

  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
    LMethod: TRttiMethod;
    LReturn: TValue;
    LArgs: TValueArray;
  begin
    with PPyObjectPuppet(self)^ do
    begin
      LMethod := TRttiContext.Create.GetType(actual_obj.ClassInfo).GetMethod(method_name);

      { contruct a method call.. }
      LArgs := python.PyTupleToTValueArray(args);
      LReturn := LMethod.Invoke(actual_obj, LArgs);
      Result := python.WrapValue(LReturn);
    end;
  end;

  function CreatePythonType(aClass: TClass): PPyTypeObject;
  var
    typ: PPyTypeObject;
    typName: ansistring;
  begin
    // todo: need a registry
      typName := python.ConvertToPAnsiChar(aClass.ClassName); // xxx olmuyo lan!
      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));
        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.Wrap(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 := PyString_FromString(ConvertToPAnsiChar(v.ToString));
  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: ;
    tkFloat: ;
    tkString: Result := PyString_FromString(ConvertToPAnsiChar(AValue.AsString));
    tkSet: ;
    tkClass: Result := CreatePythonObject(AValue.AsObject);
    tkMethod: ;
    tkWChar: ;
    tkLString: ;
    tkWString: ;
    tkVariant: ;
    tkArray: ;
    tkRecord: ;
    tkInterface: ;
    tkInt64: ;
    tkDynArray: ;
    tkUString: ;
    tkClassRef: ;
    tkPointer: ;
    tkProcedure: ;
  end;

  if Result <> nil then
    Py_INCREF(Result)
  else
    raise Exception.CreateFmt('xxx WrapValue fail for %s (%d)', [aValue.ToString, Integer(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 NameInPython: string; DelphiEntity: TObject);
var
  Result: PPyObjectPuppet;
  typ: PPyTypeObject;
begin
  // xxx
  // first create a type object for the class of DelphiEntity. xxx todo: cache 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(GetMainModule {xxx python.fModule}, ConvertToPAnsiChar(NameInPython), PPyObject(Result));
  Py_INCREF(PPyObject(Result));
end;

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