-
-
Notifications
You must be signed in to change notification settings - Fork 317
/
Copy pathVarPyth.pas
2166 lines (1973 loc) · 68.3 KB
/
VarPyth.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
(**************************************************************************)
(* This unit is part of the Python for Delphi (P4D) library *)
(* Project home: https://github.com/pyscripter/python4delphi *)
(* *)
(* Project Maintainer: PyScripter (pyscripter@gmail.com) *)
(* Original Authors: Dr. Dietmar Budelsky (dbudelsky@web.de) *)
(* Morgan Martinet (https://github.com/mmm-experts) *)
(* Core developer: Lucas Belo (lucas.belo@live.com) *)
(* Contributors: See contributors.md at project home *)
(* *)
(* LICENCE and Copyright: MIT (see project home) *)
(**************************************************************************)
(* Functionality: This allows you to use Python objects like COM *)
(* automation objects, inside your Delphi source code. *)
(* This is a replacement of the former PythonAtom.pas *)
(* that uses the new custom variant types introduced *)
(* in Delphi6. *)
(**************************************************************************)
{$I Definition.Inc}
unit VarPyth;
interface
uses
Variants, PythonEngine, Classes;
type
TSequenceType = (stTuple, stList);
{ Python variant creation utils }
function VarPythonCreate( AObject : PPyObject ) : Variant; overload;
function VarPythonCreate( const AValue : Variant ) : Variant; overload;
function VarPythonCreate( const AValues : array of const; ASequenceType : TSequenceType = stList ) : Variant; overload;
function VarPythonEval( const APythonExpression : AnsiString) : Variant;
{ Python variant helper functions }
function VarPython: TVarType;
function VarIsPython(const AValue: Variant): Boolean;
function VarAsPython(const AValue: Variant): Variant;
function ExtractPythonObjectFrom(const AValue : Variant) : PPyObject;
function VarIsSame(const A, B : Variant ) : Boolean; // checks if 2 variants share the same Python object.
function VarIsSameType(const A, B : Variant ) : Boolean; // checks if 2 variants are of the same Python type.
function VarIsPythonSequence(const AValue: Variant): Boolean;
function VarIsPythonMapping(const AValue: Variant): Boolean;
function VarIsPythonNumber(const AValue: Variant): Boolean;
function VarIsPythonString(const AValue: Variant): Boolean;
function VarIsPythonInteger(const AValue: Variant): Boolean;
function VarIsPythonFloat(const AValue: Variant): Boolean;
function VarIsPythonTuple(const AValue: Variant): Boolean;
function VarIsPythonList(const AValue: Variant): Boolean;
function VarIsPythonDict(const AValue: Variant): Boolean;
function VarIsPythonClass(const AValue: Variant): Boolean;
function VarIsPythonMethod(const AValue: Variant): Boolean;
function VarIsPythonFunction(const AValue: Variant): Boolean;
function VarIsPythonModule(const AValue: Variant): Boolean;
function VarIsPythonCallable(const AValue: Variant): Boolean;
function VarIsPythonIterator(const AValue: Variant): Boolean;
function VarIsPythonUnicode(const AValue: Variant): Boolean;
function VarIsPythonDateTime(const AValue: Variant): Boolean;
function VarIsPythonDate(const AValue: Variant): Boolean;
function VarIsPythonTime(const AValue: Variant): Boolean;
function VarIsPythonDateTimeDelta(const AValue: Variant): Boolean;
function VarIsPythonTZInfo(const AValue: Variant): Boolean;
function VarIsBool(const AValue: Variant): Boolean;
function VarIsEnum(const AValue: Variant): Boolean;
function VarIsInstanceOf(const AInstance, AClass : Variant): Boolean;
function VarIsSubclassOf(const ADerived, AClass : Variant): Boolean;
function VarIsSubtypeOf(const ADerived, AType : Variant): Boolean;
function VarIsNone(const AValue : Variant): Boolean;
function VarIsTrue(const AValue : Variant): Boolean;
function VarModuleHasObject(const AModule : Variant; aObj: AnsiString): Boolean;
function NewPythonList( const ASize : Integer = 0 ): Variant;
function NewPythonTuple( const ASize : Integer ): Variant;
function NewPythonDict: Variant;
// Not really needed since you can assign a PythonVariant to a string anyway
// but it is slightly faster and in some places avoids the declaration of a variable
function VarPythonAsString(AValue : Variant) : string;
{$IFDEF FPC}
// to work around http://mantis.freepascal.org/view.php?id=20849)
function VarPythonToVariant(AValue : Variant): Variant;
{$ENDIF}
function None: Variant;
function Ellipsis: Variant;
function MainModule: Variant; // return the main module that's used for executing a script.
function BuiltinModule: Variant; // return the builtin module
function SysModule: Variant; // return the builtin module 'sys'
function DatetimeModule: Variant; // return the builtin module 'datetime'
function Import(const AModule: string): Variant; // import a Python module and return the module object.
function Reload(const AModule: Variant): Variant; //reload a Python imported module and return the module object.
function len(const AValue : Variant ): NativeInt; // return the length of a Python collection.
function _type(const AValue : Variant ): Variant; // return the type object of a Python object.
function iter(const AValue : Variant ): Variant; // return an iterator for the container AValue. You can call the 'next' method of the iterator until you catch the EPyStopIteration exception.
type
TVarPyEnumerator = record
private
FIterator: Variant;
FCurrent: Variant;
public
constructor Create(const AValue: Variant);
function MoveNext: Boolean; inline;
function GetCurrent: Variant; inline;
property Current: Variant read GetCurrent;
end;
TVarPyEnumerateHelper = record
private
FIterable: Variant;
public
constructor Create(const AValue: Variant);
function GetEnumerator: TVarPyEnumerator;
end;
function VarPyIterate(const AValue: Variant): TVarPyEnumerateHelper;
// Adds a python iterable items to a TStrings
procedure VarPyToStrings(const AValue : Variant; const AStrings: TStrings);
implementation
uses
VarUtils, SysUtils, TypInfo;
type
TNamedParamDesc = record
Index : Integer;
Name : PAnsiChar;
end;
TNamedParamArray = array of TNamedParamDesc;
{$IF not defined(FPC) and (defined(OSX64) or defined(LINUX) or defined(ANDROID) or not defined(DELPHI10_4_OR_HIGHER))}
{$DEFINE PATCHEDSYSTEMDISPINVOKE} //To correct memory leaks
{$IFEND}
{ Python variant type handler }
TPythonVariantType = class(TInvokeableVariantType, IVarInstanceReference)
protected
fNamedParams : TNamedParamArray;
function LeftPromotion(const V: TVarData; const AOperator: TVarOp;
out RequiredVarType: TVarType): Boolean; override;
function RightPromotion(const V: TVarData; const AOperator: TVarOp;
out RequiredVarType: TVarType): Boolean; override;
function GetInstance(const V: TVarData): TObject;
function EvalPython(const V: TVarData; const AName: AnsiString;
const Arguments: TVarDataArray): PPyObject;
function VarDataToPythonObject( AVarData : TVarData ) : PPyObject;
procedure PyhonVarDataCreate( var Dest : TVarData; AObject : PPyObject );
{$IFDEF FPC}
procedure VarDataClear(var Dest: TVarData);
procedure VarDataCopyNoInd(var Dest: TVarData; const Source: TVarData);
procedure VarDataCastTo(var Dest: TVarData; const Source: TVarData;
const AVarType: TVarType); overload;
{$ELSE}
function FixupIdent(const AText: string): string; override;
{$ENDIF FPC}
public
procedure Clear(var V: TVarData); override;
function IsClear(const V: TVarData): Boolean; override;
procedure Copy(var Dest: TVarData; const Source: TVarData;
const Indirect: Boolean); override;
procedure Cast(var Dest: TVarData; const Source: TVarData); override;
procedure CastTo(var Dest: TVarData; const Source: TVarData;
const AVarType: TVarType); override;
procedure BinaryOp(var Left: TVarData; const Right: TVarData;
const AOperator: TVarOp); override;
procedure UnaryOp(var Right: TVarData; const AOperator: TVarOp); override;
function CompareOp(const Left: TVarData; const Right: TVarData;
const AOperator: TVarOp): Boolean; override;
function DoFunction(var Dest: TVarData; const V: TVarData;
const AName: string; const Arguments: TVarDataArray): Boolean; override;
function DoProcedure(const V: TVarData; const AName: string;
const Arguments: TVarDataArray): Boolean; override;
function GetProperty(var Dest: TVarData; const V: TVarData;
const AName: string): Boolean; override;
function SetProperty({$IFDEF FPC}var{$ELSE}const{$ENDIF} V: TVarData; const AName: string;
const Value: TVarData): Boolean; override;
{$IFDEF DELPHIXE7_OR_HIGHER}
procedure DispInvoke(Dest: PVarData;
[Ref] const Source: TVarData; CallDesc: PCallDesc; Params: Pointer);override;
{$ELSE}
procedure DispInvoke(Dest: PVarData;
var Source: TVarData; CallDesc: PCallDesc; Params: Pointer);override;
{$ENDIF}
end;
var
{ Python variant type handler instance }
PythonVariantType: TPythonVariantType = nil;
type
{ Python data that the Python variant points to }
TPythonData = class(TObject)
private
fPyObject: PPyObject;
function GetAsString: string;
procedure SetPyObject(const Value: PPyObject);
function GetAsVariant: Variant;
function GetAsWideString: UnicodeString;
function GetAsAnsiString: AnsiString;
public
constructor Create(AObject : PPyObject);
destructor Destroy; override;
// query state
function IsNone : Boolean;
// non-destructive operations
function Equal(const Right: TPythonData): Boolean;
function LessThan(const Right: TPythonData): Boolean;
function LessOrEqualThan(const Right: TPythonData): Boolean;
function GreaterThan(const Right: TPythonData): Boolean;
function GreaterOrEqualThan(const Right: TPythonData): Boolean;
// destructive operations
procedure DoAdd(const Right: TPythonData);
procedure DoSubtract(const Right: TPythonData);
procedure DoMultiply(const Right: TPythonData);
procedure DoDivide(const Right: TPythonData);
procedure DoIntDivide(const Right: TPythonData);
procedure DoModulus(const Right: TPythonData);
procedure DoShiftLeft(const Right: TPythonData);
procedure DoShiftRight(const Right: TPythonData);
procedure DoAnd(const Right: TPythonData);
procedure DoOr(const Right: TPythonData);
procedure DoXor(const Right: TPythonData);
procedure DoNegate;
procedure DoNot;
// conversion
property AsString: string read GetAsString;
property AsAnsiString: AnsiString read GetAsAnsiString;
property AsVariant: Variant read GetAsVariant;
property AsWideString: UnicodeString read GetAsWideString;
// data
property PyObject : PPyObject read fPyObject write SetPyObject;
end;
type
{ Helper record that helps crack open TVarData }
TPythonVarData = packed record
VType: TVarType;
Reserved1, Reserved2, Reserved3: Word;
VPython: TPythonData;
Reserved4: Integer;
{$IFDEF CPU64BITS}
Reserved5: Integer; // size is 24 bytes in 64bit
{$ENDIF CPU64BITS}
end;
resourcestring
SMultiDimensionalPropsNotSupported = 'Multi-dimensional sequences or mappings are not supported in Python';
SCantConvertArg = 'Can''t convert argument #%d of %s into a Python object';
SCantConvertKeyToPythonObject = 'Can''t convert Key into a Python object';
SCantConvertValueToPythonObject = 'Can''t convert Value into a Python object';
SCantCreateNewSequenceObject = 'Can''t create a new sequence object';
SExpectedPythonVariant = 'Expected a Python variant';
{ Python variant creation utils }
function VarPythonCreate( AObject : PPyObject ) : Variant;
begin
VarClear(Result);
if Assigned(AObject) then
begin
TPythonVarData(Result).VType := VarPython;
TPythonVarData(Result).VPython := TPythonData.Create(AObject);
end; // of if
end;
function VarPythonCreate( const AValue : Variant ) : Variant;
var
_value : PPyObject;
begin
if VarIsPython(AValue) then
Result := AValue
else
with GetPythonEngine do
begin
_value := VariantAsPyObject(AValue);
try
Result := VarPythonCreate( _value );
finally
Py_XDecRef(_value);
end;
end; // of with
end;
function VarPythonCreate( const AValues : array of const; ASequenceType : TSequenceType = stList ) : Variant;
var
i : Integer;
_seq, _item : PPyObject;
begin
with GetPythonEngine do
begin
if ASequenceType = stTuple then
_seq := PyTuple_New( High(AValues)-Low(AValues)+1 )
else
_seq := PyList_New( High(AValues)-Low(AValues)+1 );
if not Assigned(_seq) then
raise Exception.Create(SCantCreateNewSequenceObject);
try
for i := Low(AValues) to High(AValues) do
begin
if (AValues[i].VType = vtVariant) and VarIsPython(AValues[i].VVariant^) then
begin
_item := ExtractPythonObjectFrom( AValues[i].VVariant^ );
Py_XIncRef(_item);
end
else
_item := VarRecAsPyObject( AValues[i] );
if ASequenceType = stTuple then
PyTuple_SetItem( _seq, i, _item )
else
PyList_SetItem( _seq, i, _item );
end; // of for
Result := VarPythonCreate( _seq );
finally
Py_XDecRef(_seq);
end; // of try
end; // of with
end;
function VarPythonEval( const APythonExpression : AnsiString) : Variant;
var
_obj : PPyObject;
begin
with GetPythonEngine do
begin
_obj := EvalString(APythonExpression);
try
Result := VarPythonCreate( _obj );
finally
Py_XDecRef(_obj);
end;
end;
end;
function VarPython: TVarType;
begin
Result := PythonVariantType.VarType;
end;
function VarIsPython(const AValue: Variant): Boolean;
begin
Result := (TVarData(AValue).VType and varTypeMask) = VarPython;
end;
function VarAsPython(const AValue: Variant): Variant;
begin
if not VarIsPython(AValue) then
VarCast(Result, AValue, VarPython)
else
Result := AValue;
end;
// note that the returned reference to the Python object is a borrowed reference (not pre-incremented).
function ExtractPythonObjectFrom(const AValue : Variant) : PPyObject;
begin
if VarIsPython(AValue) then
Result := TPythonVarData(AValue).VPython.PyObject
else
Result := nil;
end;
function VarIsSame(const A, B : Variant ) : Boolean;
begin
Result := ExtractPythonObjectFrom(A) = ExtractPythonObjectFrom(B);
end;
function VarIsSameType(const A, B : Variant ) : Boolean;
var
_obj1, _obj2 : PPyObject;
begin
_obj1 := ExtractPythonObjectFrom(A);
_obj2 := ExtractPythonObjectFrom(B);
Result := Assigned(_obj1) and Assigned(_obj2) and (_obj1^.ob_type = _obj2^.ob_type);
end;
//------------------------------------------------------------------------------
{ Python variant helper functions }
function VarIsPythonSequence(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
(GetPythonEngine.PySequence_Check(ExtractPythonObjectFrom(AValue)) <> 0);
end;
function VarIsPythonMapping(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
(GetPythonEngine.PyMapping_Check(ExtractPythonObjectFrom(AValue)) <> 0);
end;
function VarIsPythonNumber(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
(GetPythonEngine.PyNumber_Check(ExtractPythonObjectFrom(AValue)) <> 0);
end;
function VarIsPythonString(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
GetPythonEngine.PyUnicode_Check(ExtractPythonObjectFrom(AValue));
end;
function VarIsPythonInteger(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
GetPythonEngine.PyLong_Check(ExtractPythonObjectFrom(AValue));
end;
function VarIsPythonFloat(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
GetPythonEngine.PyFloat_Check(ExtractPythonObjectFrom(AValue));
end;
function VarIsPythonTuple(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
GetPythonEngine.PyTuple_Check(ExtractPythonObjectFrom(AValue));
end;
function VarIsPythonList(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
GetPythonEngine.PyList_Check(ExtractPythonObjectFrom(AValue));
end;
function VarIsPythonDict(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
GetPythonEngine.PyDict_Check(ExtractPythonObjectFrom(AValue));
end;
function VarIsPythonClass(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
(GetPythonEngine.PyClass_Check(ExtractPythonObjectFrom(AValue))
or (GetPythonEngine.PyObject_HasAttrString(ExtractPythonObjectFrom(AValue), '__bases__') <> 0));
end;
function VarIsPythonMethod(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
GetPythonEngine.PyMethod_Check(ExtractPythonObjectFrom(AValue));
end;
function VarIsPythonFunction(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
GetPythonEngine.PyFunction_Check(ExtractPythonObjectFrom(AValue));
end;
function VarIsPythonModule(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
GetPythonEngine.PyModule_Check(ExtractPythonObjectFrom(AValue));
end;
function VarIsPythonCallable(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
(GetPythonEngine.PyCallable_Check(ExtractPythonObjectFrom(AValue)) <> 0);
end;
function VarIsPythonIterator(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
(GetPythonEngine.PyIter_Check(ExtractPythonObjectFrom(AValue)));
end;
function VarIsPythonUnicode(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
GetPythonEngine.PyUnicode_Check(ExtractPythonObjectFrom(AValue));
end;
function VarIsPythonDateTime(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
GetPythonEngine.PyDateTime_Check(ExtractPythonObjectFrom(AValue));
end;
function VarIsPythonDate(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
GetPythonEngine.PyDate_Check(ExtractPythonObjectFrom(AValue));
end;
function VarIsPythonTime(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
GetPythonEngine.PyTime_Check(ExtractPythonObjectFrom(AValue));
end;
function VarIsPythonDateTimeDelta(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
GetPythonEngine.PyDelta_Check(ExtractPythonObjectFrom(AValue));
end;
function VarIsPythonTZInfo(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
GetPythonEngine.PyTZInfo_Check(ExtractPythonObjectFrom(AValue));
end;
function VarIsBool(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
GetPythonEngine.PyBool_Check(ExtractPythonObjectFrom(AValue));
end;
function VarIsEnum(const AValue: Variant): Boolean;
begin
Result := VarIsPython(AValue) and
GetPythonEngine.PyEnum_Check(ExtractPythonObjectFrom(AValue));
end;
function VarIsInstanceOf(const AInstance, AClass : Variant): Boolean;
begin
with GetPythonEngine do
begin
Result := VarIsPython(AInstance) and VarIsPython(AClass) and
(PyObject_IsInstance( ExtractPythonObjectFrom(AInstance),
ExtractPythonObjectFrom(AClass)) <> 0);
CheckError;
end; // of with
end;
function VarIsSubclassOf(const ADerived, AClass : Variant): Boolean;
begin
with GetPythonEngine do
begin
Result := VarIsPython(ADerived) and VarIsPython(AClass) and
(PyObject_IsSubclass( ExtractPythonObjectFrom(ADerived),
ExtractPythonObjectFrom(AClass)) <> 0);
CheckError;
end; // of with
end;
function VarIsSubtypeOf(const ADerived, AType : Variant): Boolean;
begin
with GetPythonEngine do
begin
Result := VarIsPython(ADerived) and VarIsPython(AType) and
(PyType_IsSubtype( ExtractPythonObjectFrom(ADerived)^.ob_type,
PPyTypeObject(ExtractPythonObjectFrom(AType))) <> 0);
CheckError;
end; // of with
end;
function VarIsNone(const AValue : Variant): Boolean;
begin
Result := VarIsPython(AValue) and
(ExtractPythonObjectFrom(AValue) = GetPythonEngine.Py_None);
end;
function VarIsTrue(const AValue : Variant): Boolean;
begin
Result := AValue; // the cast into a boolean will call the PyObject_IsTrue API.
end;
function VarModuleHasObject(const AModule : Variant; aObj: AnsiString): Boolean;
begin
with GetPythonEngine do
Result := VarIsPython(AModule) and
PyModule_Check(ExtractPythonObjectFrom(AModule)) and
Assigned(PyDict_GetItemString(
PyModule_GetDict(ExtractPythonObjectFrom(AModule)),PAnsiChar(aObj)));
end;
function NewPythonList( const ASize : Integer = 0 ): Variant;
var
_list : PPyObject;
begin
with GetPythonEngine do
begin
_list := PyList_New(ASize);
try
Result := VarPythonCreate( _list );
finally
Py_XDecRef(_list);
end; // of try
end; // of with
end;
function NewPythonTuple( const ASize : Integer ): Variant;
var
_tuple : PPyObject;
begin
with GetPythonEngine do
begin
_tuple := PyTuple_New(ASize);
try
Result := VarPythonCreate( _tuple );
finally
Py_XDecRef(_tuple);
end; // of try
end; // of with
end;
function NewPythonDict: Variant;
var
_dict : PPyObject;
begin
with GetPythonEngine do
begin
_dict := PyDict_New;
try
Result := VarPythonCreate( _dict );
finally
Py_XDecRef(_dict);
end; // of try
end; // of with
end;
function VarPythonAsString(AValue : Variant) : string;
begin
if VarIsPython(AValue) then
Result := TPythonVarData(AValue).VPython.AsString
else
Result := AValue;
end;
{$IFDEF FPC}
function VarPythonToVariant(AValue : Variant): Variant;
begin
if VarIsPython(AValue) then
Result :=
GetPythonEngine.PyObjectAsVariant(TPythonVarData(AValue).VPython.PyObject)
else
Result := AValue;
end;
{$ENDIF}
function None : Variant;
begin
with GetPythonEngine do
Result := VarPythonCreate(Py_None);
end;
function Ellipsis : Variant;
begin
with GetPythonEngine do
Result := VarPythonCreate(Py_Ellipsis);
end;
function MainModule : Variant;
var
_main : PPyObject;
begin
_main := GetPythonEngine.GetMainModule; // the refcount is not pre-incremented
Assert(Assigned(_main));
Result := VarPythonCreate(_main);
end;
function BuiltinModule : Variant;
begin
Result := Import(GetPythonEngine.BuiltInModuleName);
end;
function SysModule : Variant;
begin
Result := Import('sys');
end;
function DatetimeModule : Variant; // return the builtin module 'datetime'
begin
Result := Import('datetime');
end;
function Import(const AModule: string): Variant;
var
_module : PPyObject;
_module_name : PPyObject;
begin
with GetPythonEngine do
begin
_module_name := PyUnicodeFromString(AModule);
try
_module := PyImport_Import(_module_name);
CheckError;
finally
Py_XDecRef(_module_name);
end; // of try
Assert(Assigned(_module));
try
Result := VarPythonCreate(_module);
finally
Py_XDecRef(_module);
end; // of try
end; // of with
end;
function Reload(const AModule: Variant): Variant;
var
LModule: PPyObject;
begin
with GetPythonEngine() do begin
LModule := PyImport_ReloadModule(ExtractPythonObjectFrom(AModule));
CheckError();
Assert(Assigned(LModule));
try
Result := VarPythonCreate(LModule);
finally
Py_XDecRef(LModule);
end; // of try
end; // of with
end;
function GetObjectLength(AObject: PPyObject): NativeInt;
begin
with GetPythonEngine do
begin
PyErr_Clear;
Result := PyObject_Length(AObject);
CheckError;
end; // of with
end;
// returns the length of a Python collection.
function len(const AValue : Variant ) : NativeInt;
begin
if VarIsPython(AValue) then
Result := GetObjectLength( ExtractPythonObjectFrom(AValue) )
else
raise Exception.Create(SExpectedPythonVariant);
end;
function _type(const AValue : Variant ) : Variant;
begin
if VarIsPython(AValue) then
Result := VarPythonCreate( PPyObject( ExtractPythonObjectFrom(AValue)^.ob_type ) )
else
raise Exception.Create(SExpectedPythonVariant);
end;
function iter(const AValue : Variant ) : Variant;
var
_iter : PPyObject;
begin
if VarIsPython(AValue) then
with GetPythonEngine do
begin
PyErr_Clear;
_iter := PyObject_GetIter(ExtractPythonObjectFrom(AValue));
CheckError;
try
Result := VarPythonCreate(_iter);
finally
Py_XDecRef(_iter);
end;
end
else
raise Exception.Create(SExpectedPythonVariant);
end;
//------------------------------------------------------------------------------
{ TPythonVariantType }
procedure TPythonVariantType.BinaryOp(var Left: TVarData;
const Right: TVarData; const AOperator: TVarOp);
begin
if Right.VType = VarType then
case Left.VType of
varString, varUString:
case AOperator of
opAdd:
Variant(Left) := Variant(Left) + TPythonVarData(Right).VPython.AsString;
else
RaiseInvalidOp;
end; // of varString
else
if Left.VType = VarType then
case AOperator of
opAdd:
TPythonVarData(Left).VPython.DoAdd(TPythonVarData(Right).VPython);
opSubtract:
TPythonVarData(Left).VPython.DoSubtract(TPythonVarData(Right).VPython);
opMultiply:
TPythonVarData(Left).VPython.DoMultiply(TPythonVarData(Right).VPython);
opDivide:
TPythonVarData(Left).VPython.DoDivide(TPythonVarData(Right).VPython);
opIntDivide:
TPythonVarData(Left).VPython.DoIntDivide(TPythonVarData(Right).VPython);
opModulus:
TPythonVarData(Left).VPython.DoModulus(TPythonVarData(Right).VPython);
opShiftLeft:
TPythonVarData(Left).VPython.DoShiftLeft(TPythonVarData(Right).VPython);
opShiftRight:
TPythonVarData(Left).VPython.DoShiftRight(TPythonVarData(Right).VPython);
opAnd:
TPythonVarData(Left).VPython.DoAnd(TPythonVarData(Right).VPython);
opOr:
TPythonVarData(Left).VPython.DoOr(TPythonVarData(Right).VPython);
opXor:
TPythonVarData(Left).VPython.DoXor(TPythonVarData(Right).VPython);
else
RaiseInvalidOp;
end // of case
else
RaiseInvalidOp;
end // of case
else
RaiseInvalidOp;
end;
procedure TPythonVariantType.Cast(var Dest: TVarData;
const Source: TVarData);
var
_object : PPyObject;
begin
_object := VarDataToPythonObject(Source);
try
PyhonVarDataCreate( Dest, _object );
finally
GetPythonEngine.Py_XDECREF(_object);
end;
end;
procedure TPythonVariantType.CastTo(var Dest: TVarData;
const Source: TVarData; const AVarType: TVarType);
var
V : Variant;
begin
if Source.VType = VarType then
case AVarType of
varOleStr:
VarDataFromOleStr(Dest, TPythonVarData(Source).VPython.AsWideString);
varUString:
{$IFDEF FPC}
VarDataFromOleStr(Dest, TPythonVarData(Source).VPython.AsWideString);
{$ELSE}
VarDataFromStr(Dest, TPythonVarData(Source).VPython.AsWideString);
{$ENDIF}
varString:
// Preserve AnsiStrings
{$IFDEF FPC}
Variant(Dest) := TPythonVarData(Source).VPython.AsWideString;
{$ELSE}
VarDataFromLStr(Dest, TPythonVarData(Source).VPython.AsAnsiString);
{$ENDIF}
else
if AVarType and varTypeMask = varBoolean then
begin
Dest.VType := varBoolean;
Dest.VBoolean := GetPythonEngine.PyObject_IsTrue( TPythonVarData(Source).VPython.PyObject ) = 1;
end
else
begin
V := TPythonVarData(Source).VPython.AsVariant;
VarDataCastTo(Dest, TVarData(V), AVarType);
end;
end // of case
else
inherited;
end;
{$IFDEF FPC}
procedure TPythonVariantType.VarDataClear(var Dest: TVarData);
begin
VarClear(Variant(Dest));
end;
procedure TPythonVariantType.VarDataCopyNoInd(var Dest: TVarData; const Source: TVarData);
begin
VarCopyNoInd(Variant(Dest), Variant(Source));
end;
procedure TPythonVariantType.VarDataCastTo(var Dest: TVarData; const Source: TVarData;
const AVarType: TVarType); overload;
begin
VarCast(Variant(Dest), Variant(Source), AVarType);
end;
{$ENDIF}
procedure TPythonVariantType.Clear(var V: TVarData);
begin
V.VType := varEmpty;
FreeAndNil(TPythonVarData(V).VPython);
end;
function TPythonVariantType.CompareOp(const Left, Right: TVarData;
const AOperator: TVarOp): Boolean;
begin
Result := False;
if (Left.VType = VarType) and (Right.VType = VarType) then
case AOperator of
opCmpEQ:
Result := TPythonVarData(Left).VPython.Equal(TPythonVarData(Right).VPython);
opCmpNE:
Result := not TPythonVarData(Left).VPython.Equal(TPythonVarData(Right).VPython);
opCmpLT:
Result := TPythonVarData(Left).VPython.LessThan(TPythonVarData(Right).VPython);
opCmpLE:
Result := TPythonVarData(Left).VPython.LessOrEqualThan(TPythonVarData(Right).VPython);
opCmpGT:
Result := TPythonVarData(Left).VPython.GreaterThan(TPythonVarData(Right).VPython);
opCmpGE:
Result := TPythonVarData(Left).VPython.GreaterOrEqualThan(TPythonVarData(Right).VPython);
else
RaiseInvalidOp;
end // of case
else
RaiseInvalidOp;
end;
procedure TPythonVariantType.Copy(var Dest: TVarData;
const Source: TVarData; const Indirect: Boolean);
begin
if Indirect and VarDataIsByRef(Source) then
VarDataCopyNoInd(Dest, Source)
else
PyhonVarDataCreate( Dest, TPythonVarData(Source).VPython.PyObject );
end;
procedure SetClearVarToEmptyParam(var V: TVarData);
begin
VarClear(Variant(V));
V.VType := varError;
{$IFNDEF FPC}
V.VError := VAR_PARAMNOTFOUND;
{$ELSE}
V.VError := HRESULT($80020004); {DISP_E_PARAMNOTFOUND}
{$ENDIF}
end;
const
CDoMethod = $01;
CPropertyGet = $02;
CPropertySet = $04;
{$IF defined(PATCHEDSYSTEMDISPINVOKE) and (defined(OSX64) or defined(LINUX) or defined(ANDROID))}
{
Fixes https://quality.embarcadero.com/browse/RSP-28097
}
var
_EmptyBSTR: PWideChar = nil;
Const
SDispatchError = 'Variant method calls not supported';
procedure _DispInvokeError;
begin
raise EVariantDispatchError.Create(SDispatchError);
end;
function GetDispatchInvokeArgs(CallDesc: PCallDesc; Params: Pointer; var Strings: TStringRefList; OrderLTR : Boolean): TVarDataArray;
const
{ Parameter type masks - keep in sync with decl.h/ap* enumerations}
atString = $48;
atUString = $4A;
atVarMask = $3F;
atTypeMask = $7F;
atByRef = $80;
var
I: Integer;
ArgType: Byte;
PVarParm: PVarData;
StringCount: Integer;
VAList: TVarArgList;
Temp: Pointer;
begin
VAList := TVarArgList(Params^);
StringCount := 0;
SetLength(Result, CallDesc^.ArgCount);
for I := 0 to CallDesc^.ArgCount-1 do
begin
ArgType := CallDesc^.ArgTypes[I];
if OrderLTR then
PVarParm := @Result[I]
else
PVarParm := @Result[CallDesc^.ArgCount-I-1];
if (ArgType and atByRef) = atByRef then
begin
Temp := VarArgGetValue(VAList, Pointer);
if (ArgType and atTypeMask) = atString then
begin
PVarData(PVarParm)^.VType := varByRef or varOleStr;
PVarData(PVarParm)^.VPointer := Strings[StringCount].FromAnsi( PAnsiString(Temp));
Inc(StringCount);
end
else
if (ArgType and atTypeMask) = atUString then
begin
PVarData(PVarParm)^.VType := varByRef or varOleStr;
PVarData(PVarParm)^.VPointer := Strings[StringCount].FromUnicode(PUnicodeString(Temp));
Inc(StringCount);