FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
pythonnet/src/runtime/classderived.cs at refactor-qc-pythonnet5 · QuantConnect/pythonnet · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
QuantConnect
/
pythonnet
Public
forked from
pythonnet/pythonnet
Notifications
You must be signed in to change notification settings
Fork
31
Star
29
Code
Issues
5
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
pythonnet
/
src
/
runtime
/
classderived.cs
Copy path
More file actions
More file actions
Latest commit
History
History
History
902 lines (806 loc) · 36.9 KB
Breadcrumbs
pythonnet
/
src
/
runtime
/
classderived.cs
Copy path
File metadata and controls
902 lines (806 loc) · 36.9 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
using
System
;
using
System
.
Collections
.
Generic
;
using
System
.
Linq
;
using
System
.
Reflection
;
using
System
.
Reflection
.
Emit
;
using
System
.
Resources
;
using
System
.
Runtime
.
InteropServices
;
using
System
.
Threading
.
Tasks
;
namespace
Python
.
Runtime
{
/// <summary>
/// Managed class that provides the implementation for reflected types.
/// Managed classes and value types are represented in Python by actual
/// Python type objects. Each of those type objects is associated with
/// an instance of ClassObject, which provides its implementation.
/// </summary>
/// <remarks>
/// interface used to identify which C# types were dynamically created as python subclasses
/// </remarks>
public
interface
IPythonDerivedType
{
}
[
Serializable
]
internal
class
ClassDerivedObject
:
ClassObject
{
private
static
Dictionary
<
string
,
AssemblyBuilder
>
assemblyBuilders
;
private
static
Dictionary
<
Tuple
<
string
,
string
>
,
ModuleBuilder
>
moduleBuilders
;
static
ClassDerivedObject
(
)
{
assemblyBuilders
=
new
Dictionary
<
string
,
AssemblyBuilder
>
(
)
;
moduleBuilders
=
new
Dictionary
<
Tuple
<
string
,
string
>
,
ModuleBuilder
>
(
)
;
}
public
static
void
Reset
(
)
{
assemblyBuilders
=
new
Dictionary
<
string
,
AssemblyBuilder
>
(
)
;
moduleBuilders
=
new
Dictionary
<
Tuple
<
string
,
string
>
,
ModuleBuilder
>
(
)
;
}
internal
ClassDerivedObject
(
Type
tp
)
:
base
(
tp
)
{
}
/// <summary>
/// Implements __new__ for derived classes of reflected classes.
/// </summary>
public
new
static
IntPtr
tp_new
(
IntPtr
tp
,
IntPtr
args
,
IntPtr
kw
)
{
var
cls
=
GetManagedObject
(
tp
)
as
ClassDerivedObject
;
// call the managed constructor
object
obj
=
cls
.
binder
.
InvokeRaw
(
IntPtr
.
Zero
,
args
,
kw
)
;
if
(
obj
==
null
)
{
return
IntPtr
.
Zero
;
}
// return the pointer to the python object
// (this indirectly calls ClassDerivedObject.ToPython)
return
Converter
.
ToPython
(
obj
,
cls
.
GetType
(
)
)
;
}
public
new
static
void
tp_dealloc
(
IntPtr
ob
)
{
var
self
=
(
CLRObject
)
GetManagedObject
(
ob
)
;
// don't let the python GC destroy this object
Runtime
.
PyObject_GC_UnTrack
(
self
.
pyHandle
)
;
// The python should now have a ref count of 0, but we don't actually want to
// deallocate the object until the C# object that references it is destroyed.
// So we don't call PyObject_GC_Del here and instead we set the python
// reference to a weak reference so that the C# object can be collected.
GCHandle
gc
=
GCHandle
.
Alloc
(
self
,
GCHandleType
.
Weak
)
;
int
gcOffset
=
ObjectOffset
.
magic
(
Runtime
.
PyObject_TYPE
(
self
.
pyHandle
)
)
;
Marshal
.
WriteIntPtr
(
self
.
pyHandle
,
gcOffset
,
(
IntPtr
)
gc
)
;
self
.
gcHandle
.
Free
(
)
;
self
.
gcHandle
=
gc
;
}
/// <summary>
/// Called from Converter.ToPython for types that are python subclasses of managed types.
/// The referenced python object is returned instead of a new wrapper.
/// </summary>
internal
static
IntPtr
ToPython
(
IPythonDerivedType
obj
)
{
// derived types have a __pyobj__ field that gets set to the python
// object in the overridden constructor
FieldInfo
fi
=
obj
.
GetType
(
)
.
GetField
(
"__pyobj__"
)
;
var
self
=
(
CLRObject
)
fi
.
GetValue
(
obj
)
;
Runtime
.
XIncref
(
self
.
pyHandle
)
;
// when the C# constructor creates the python object it starts as a weak
// reference with a reference count of 0. Now we're passing this object
// to Python the reference count needs to be incremented and the reference
// needs to be replaced with a strong reference to stop the C# object being
// collected while Python still has a reference to it.
if
(
Runtime
.
Refcount
(
self
.
pyHandle
)
==
1
)
{
#if
PYTHON_WITH_PYDEBUG
Runtime
.
_Py_NewReference
(
self
.
pyHandle
)
;
#endif
GCHandle
gc
=
GCHandle
.
Alloc
(
self
,
GCHandleType
.
Normal
)
;
Marshal
.
WriteIntPtr
(
self
.
pyHandle
,
ObjectOffset
.
magic
(
self
.
tpHandle
)
,
(
IntPtr
)
gc
)
;
self
.
gcHandle
.
Free
(
)
;
self
.
gcHandle
=
gc
;
// now the object has a python reference it's safe for the python GC to track it
Runtime
.
PyObject_GC_Track
(
self
.
pyHandle
)
;
}
return
self
.
pyHandle
;
}
/// <summary>
/// Creates a new managed type derived from a base type with any virtual
/// methods overridden to call out to python if the associated python
/// object has overridden the method.
/// </summary>
internal
static
Type
CreateDerivedType
(
string
name
,
Type
baseType
,
IntPtr
py_dict
,
string
namespaceStr
,
string
assemblyName
,
string
moduleName
=
"Python.Runtime.Dynamic.dll"
)
{
if
(
null
!=
namespaceStr
)
{
name
=
namespaceStr
+
"."
+
name
;
}
if
(
null
==
assemblyName
)
{
assemblyName
=
"Python.Runtime.Dynamic"
;
}
ModuleBuilder
moduleBuilder
=
GetModuleBuilder
(
assemblyName
,
moduleName
)
;
Type
baseClass
=
baseType
;
var
interfaces
=
new
List
<
Type
>
{
typeof
(
IPythonDerivedType
)
}
;
// if the base type is an interface then use System.Object as the base class
// and add the base type to the list of interfaces this new class will implement.
if
(
baseType
.
IsInterface
)
{
interfaces
.
Add
(
baseType
)
;
baseClass
=
typeof
(
object
)
;
}
TypeBuilder
typeBuilder
=
moduleBuilder
.
DefineType
(
name
,
TypeAttributes
.
Public
|
TypeAttributes
.
Class
,
baseClass
,
interfaces
.
ToArray
(
)
)
;
// add a field for storing the python object pointer
// FIXME: fb not used
FieldBuilder
fb
=
typeBuilder
.
DefineField
(
"__pyobj__"
,
typeof
(
CLRObject
)
,
FieldAttributes
.
Public
)
;
// override any constructors
ConstructorInfo
[
]
constructors
=
baseClass
.
GetConstructors
(
)
;
foreach
(
ConstructorInfo
ctor
in
constructors
)
{
AddConstructor
(
ctor
,
baseType
,
typeBuilder
)
;
}
// Override any properties explicitly overridden in python
var
pyProperties
=
new
HashSet
<
string
>
(
)
;
if
(
py_dict
!=
IntPtr
.
Zero
&&
Runtime
.
PyDict_Check
(
py_dict
)
)
{
Runtime
.
XIncref
(
py_dict
)
;
using
(
var
dict
=
new
PyDict
(
py_dict
)
)
using
(
PyObject
keys
=
dict
.
Keys
(
)
)
{
foreach
(
PyObject
pyKey
in
keys
)
{
using
(
PyObject
value
=
dict
[
pyKey
]
)
{
if
(
value
.
HasAttr
(
"_clr_property_type_"
)
)
{
string
propertyName
=
pyKey
.
ToString
(
)
;
pyProperties
.
Add
(
propertyName
)
;
// Add the property to the type
AddPythonProperty
(
propertyName
,
value
,
typeBuilder
)
;
}
}
}
}
}
// override any virtual methods not already overridden by the properties above
MethodInfo
[
]
methods
=
baseType
.
GetMethods
(
)
;
var
virtualMethods
=
new
HashSet
<
string
>
(
)
;
foreach
(
MethodInfo
method
in
methods
)
{
if
(
!
method
.
Attributes
.
HasFlag
(
MethodAttributes
.
Virtual
)
|
method
.
Attributes
.
HasFlag
(
MethodAttributes
.
Final
)
)
{
continue
;
}
// skip if this property has already been overridden
if
(
(
method
.
Name
.
StartsWith
(
"get_"
)
||
method
.
Name
.
StartsWith
(
"set_"
)
)
&&
pyProperties
.
Contains
(
method
.
Name
.
Substring
(
4
)
)
)
{
continue
;
}
// keep track of the virtual methods redirected to the python instance
virtualMethods
.
Add
(
method
.
Name
)
;
// override the virtual method to call out to the python method, if there is one.
AddVirtualMethod
(
method
,
baseType
,
typeBuilder
)
;
}
// Add any additional methods and properties explicitly exposed from Python.
if
(
py_dict
!=
IntPtr
.
Zero
&&
Runtime
.
PyDict_Check
(
py_dict
)
)
{
Runtime
.
XIncref
(
py_dict
)
;
using
(
var
dict
=
new
PyDict
(
py_dict
)
)
using
(
PyObject
keys
=
dict
.
Keys
(
)
)
{
foreach
(
PyObject
pyKey
in
keys
)
{
using
(
PyObject
value
=
dict
[
pyKey
]
)
{
if
(
value
.
HasAttr
(
"_clr_return_type_"
)
&&
value
.
HasAttr
(
"_clr_arg_types_"
)
)
{
string
methodName
=
pyKey
.
ToString
(
)
;
// if this method has already been redirected to the python method skip it
if
(
virtualMethods
.
Contains
(
methodName
)
)
{
continue
;
}
// Add the method to the type
AddPythonMethod
(
methodName
,
value
,
typeBuilder
)
;
}
}
}
}
}
// add the destructor so the python object created in the constructor gets destroyed
MethodBuilder
methodBuilder
=
typeBuilder
.
DefineMethod
(
"Finalize"
,
MethodAttributes
.
Family
|
MethodAttributes
.
Virtual
|
MethodAttributes
.
HideBySig
,
CallingConventions
.
Standard
,
typeof
(
void
)
,
Type
.
EmptyTypes
)
;
ILGenerator
il
=
methodBuilder
.
GetILGenerator
(
)
;
il
.
Emit
(
OpCodes
.
Ldarg_0
)
;
il
.
Emit
(
OpCodes
.
Call
,
typeof
(
PythonDerivedType
)
.
GetMethod
(
"Finalize"
)
)
;
il
.
Emit
(
OpCodes
.
Ldarg_0
)
;
il
.
Emit
(
OpCodes
.
Call
,
baseClass
.
GetMethod
(
"Finalize"
,
BindingFlags
.
NonPublic
|
BindingFlags
.
Instance
)
)
;
il
.
Emit
(
OpCodes
.
Ret
)
;
Type
type
=
typeBuilder
.
CreateType
(
)
;
// scan the assembly so the newly added class can be imported
Assembly
assembly
=
Assembly
.
GetAssembly
(
type
)
;
AssemblyManager
.
ScanAssembly
(
assembly
)
;
// FIXME: assemblyBuilder not used
AssemblyBuilder
assemblyBuilder
=
assemblyBuilders
[
assemblyName
]
;
return
type
;
}
/// <summary>
/// Add a constructor override that calls the python ctor after calling the base type constructor.
/// </summary>
/// <param name="ctor">constructor to be called before calling the python ctor</param>
/// <param name="baseType">Python callable object</param>
/// <param name="typeBuilder">TypeBuilder for the new type the ctor is to be added to</param>
private
static
void
AddConstructor
(
ConstructorInfo
ctor
,
Type
baseType
,
TypeBuilder
typeBuilder
)
{
ParameterInfo
[
]
parameters
=
ctor
.
GetParameters
(
)
;
Type
[
]
parameterTypes
=
(
from
param
in
parameters
select
param
.
ParameterType
)
.
ToArray
(
)
;
// create a method for calling the original constructor
string
baseCtorName
=
"_"
+
baseType
.
Name
+
"__cinit__"
;
MethodBuilder
methodBuilder
=
typeBuilder
.
DefineMethod
(
baseCtorName
,
MethodAttributes
.
Public
|
MethodAttributes
.
Final
|
MethodAttributes
.
HideBySig
,
typeof
(
void
)
,
parameterTypes
)
;
// emit the assembly for calling the original method using call instead of callvirt
ILGenerator
il
=
methodBuilder
.
GetILGenerator
(
)
;
il
.
Emit
(
OpCodes
.
Ldarg_0
)
;
for
(
var
i
=
0
;
i
<
parameters
.
Length
;
++
i
)
{
il
.
Emit
(
OpCodes
.
Ldarg
,
i
+
1
)
;
}
il
.
Emit
(
OpCodes
.
Call
,
ctor
)
;
il
.
Emit
(
OpCodes
.
Ret
)
;
// override the original method with a new one that dispatches to python
ConstructorBuilder
cb
=
typeBuilder
.
DefineConstructor
(
MethodAttributes
.
Public
|
MethodAttributes
.
ReuseSlot
|
MethodAttributes
.
HideBySig
,
ctor
.
CallingConvention
,
parameterTypes
)
;
il
=
cb
.
GetILGenerator
(
)
;
il
.
DeclareLocal
(
typeof
(
object
[
]
)
)
;
il
.
Emit
(
OpCodes
.
Ldarg_0
)
;
il
.
Emit
(
OpCodes
.
Ldstr
,
baseCtorName
)
;
il
.
Emit
(
OpCodes
.
Ldc_I4
,
parameters
.
Length
)
;
il
.
Emit
(
OpCodes
.
Newarr
,
typeof
(
object
)
)
;
il
.
Emit
(
OpCodes
.
Stloc_0
)
;
for
(
var
i
=
0
;
i
<
parameters
.
Length
;
++
i
)
{
il
.
Emit
(
OpCodes
.
Ldloc_0
)
;
il
.
Emit
(
OpCodes
.
Ldc_I4
,
i
)
;
il
.
Emit
(
OpCodes
.
Ldarg
,
i
+
1
)
;
if
(
parameterTypes
[
i
]
.
IsValueType
)
{
il
.
Emit
(
OpCodes
.
Box
,
parameterTypes
[
i
]
)
;
}
il
.
Emit
(
OpCodes
.
Stelem
,
typeof
(
object
)
)
;
}
il
.
Emit
(
OpCodes
.
Ldloc_0
)
;
il
.
Emit
(
OpCodes
.
Call
,
typeof
(
PythonDerivedType
)
.
GetMethod
(
"InvokeCtor"
)
)
;
il
.
Emit
(
OpCodes
.
Ret
)
;
}
/// <summary>
/// Add a virtual method override that checks for an override on the python instance
/// and calls it, otherwise fall back to the base class method.
/// </summary>
/// <param name="method">virtual method to be overridden</param>
/// <param name="baseType">Python callable object</param>
/// <param name="typeBuilder">TypeBuilder for the new type the method is to be added to</param>
private
static
void
AddVirtualMethod
(
MethodInfo
method
,
Type
baseType
,
TypeBuilder
typeBuilder
)
{
ParameterInfo
[
]
parameters
=
method
.
GetParameters
(
)
;
Type
[
]
parameterTypes
=
(
from
param
in
parameters
select
param
.
ParameterType
)
.
ToArray
(
)
;
// If the method isn't abstract create a method for calling the original method
string
baseMethodName
=
null
;
if
(
!
method
.
IsAbstract
)
{
baseMethodName
=
"_"
+
baseType
.
Name
+
"__"
+
method
.
Name
;
MethodBuilder
baseMethodBuilder
=
typeBuilder
.
DefineMethod
(
baseMethodName
,
MethodAttributes
.
Public
|
MethodAttributes
.
Final
|
MethodAttributes
.
HideBySig
,
method
.
ReturnType
,
parameterTypes
)
;
// emit the assembly for calling the original method using call instead of callvirt
ILGenerator
baseIl
=
baseMethodBuilder
.
GetILGenerator
(
)
;
baseIl
.
Emit
(
OpCodes
.
Ldarg_0
)
;
for
(
var
i
=
0
;
i
<
parameters
.
Length
;
++
i
)
{
baseIl
.
Emit
(
OpCodes
.
Ldarg
,
i
+
1
)
;
}
baseIl
.
Emit
(
OpCodes
.
Call
,
method
)
;
baseIl
.
Emit
(
OpCodes
.
Ret
)
;
}
// override the original method with a new one that dispatches to python
MethodBuilder
methodBuilder
=
typeBuilder
.
DefineMethod
(
method
.
Name
,
MethodAttributes
.
Public
|
MethodAttributes
.
ReuseSlot
|
MethodAttributes
.
Virtual
|
MethodAttributes
.
HideBySig
,
method
.
CallingConvention
,
method
.
ReturnType
,
parameterTypes
)
;
ILGenerator
il
=
methodBuilder
.
GetILGenerator
(
)
;
il
.
DeclareLocal
(
typeof
(
object
[
]
)
)
;
il
.
Emit
(
OpCodes
.
Ldarg_0
)
;
il
.
Emit
(
OpCodes
.
Ldstr
,
method
.
Name
)
;
// don't fall back to the base type's method if it's abstract
if
(
null
!=
baseMethodName
)
{
il
.
Emit
(
OpCodes
.
Ldstr
,
baseMethodName
)
;
}
else
{
il
.
Emit
(
OpCodes
.
Ldnull
)
;
}
il
.
Emit
(
OpCodes
.
Ldc_I4
,
parameters
.
Length
)
;
il
.
Emit
(
OpCodes
.
Newarr
,
typeof
(
object
)
)
;
il
.
Emit
(
OpCodes
.
Stloc_0
)
;
for
(
var
i
=
0
;
i
<
parameters
.
Length
;
++
i
)
{
il
.
Emit
(
OpCodes
.
Ldloc_0
)
;
il
.
Emit
(
OpCodes
.
Ldc_I4
,
i
)
;
il
.
Emit
(
OpCodes
.
Ldarg
,
i
+
1
)
;
if
(
parameterTypes
[
i
]
.
IsValueType
)
{
il
.
Emit
(
OpCodes
.
Box
,
parameterTypes
[
i
]
)
;
}
il
.
Emit
(
OpCodes
.
Stelem
,
typeof
(
object
)
)
;
}
il
.
Emit
(
OpCodes
.
Ldloc_0
)
;
if
(
method
.
ReturnType
==
typeof
(
void
)
)
{
il
.
Emit
(
OpCodes
.
Call
,
typeof
(
PythonDerivedType
)
.
GetMethod
(
"InvokeMethodVoid"
)
)
;
}
else
{
il
.
Emit
(
OpCodes
.
Call
,
typeof
(
PythonDerivedType
)
.
GetMethod
(
"InvokeMethod"
)
.
MakeGenericMethod
(
method
.
ReturnType
)
)
;
}
il
.
Emit
(
OpCodes
.
Ret
)
;
}
/// <summary>
/// Python method may have the following function attributes set to control how they're exposed:
/// - _clr_return_type_ - method return type (required)
/// - _clr_arg_types_ - list of method argument types (required)
/// - _clr_method_name_ - method name, if different from the python method name (optional)
/// </summary>
/// <param name="methodName">Method name to add to the type</param>
/// <param name="func">Python callable object</param>
/// <param name="typeBuilder">TypeBuilder for the new type the method/property is to be added to</param>
private
static
void
AddPythonMethod
(
string
methodName
,
PyObject
func
,
TypeBuilder
typeBuilder
)
{
if
(
func
.
HasAttr
(
"_clr_method_name_"
)
)
{
using
(
PyObject
pyMethodName
=
func
.
GetAttr
(
"_clr_method_name_"
)
)
{
methodName
=
pyMethodName
.
ToString
(
)
;
}
}
using
(
PyObject
pyReturnType
=
func
.
GetAttr
(
"_clr_return_type_"
)
)
using
(
PyObject
pyArgTypes
=
func
.
GetAttr
(
"_clr_arg_types_"
)
)
{
var
returnType
=
pyReturnType
.
AsManagedObject
(
typeof
(
Type
)
)
as
Type
;
if
(
returnType
==
null
)
{
returnType
=
typeof
(
void
)
;
}
if
(
!
pyArgTypes
.
IsIterable
(
)
)
{
throw
new
ArgumentException
(
"_clr_arg_types_ must be a list or tuple of CLR types"
)
;
}
var
argTypes
=
new
List
<
Type
>
(
)
;
foreach
(
PyObject
pyArgType
in
pyArgTypes
)
{
var
argType
=
pyArgType
.
AsManagedObject
(
typeof
(
Type
)
)
as
Type
;
if
(
argType
==
null
)
{
throw
new
ArgumentException
(
"_clr_arg_types_ must be a list or tuple of CLR types"
)
;
}
argTypes
.
Add
(
argType
)
;
}
// add the method to call back into python
MethodAttributes
methodAttribs
=
MethodAttributes
.
Public
|
MethodAttributes
.
Virtual
|
MethodAttributes
.
ReuseSlot
|
MethodAttributes
.
HideBySig
;
MethodBuilder
methodBuilder
=
typeBuilder
.
DefineMethod
(
methodName
,
methodAttribs
,
returnType
,
argTypes
.
ToArray
(
)
)
;
ILGenerator
il
=
methodBuilder
.
GetILGenerator
(
)
;
il
.
DeclareLocal
(
typeof
(
object
[
]
)
)
;
il
.
Emit
(
OpCodes
.
Ldarg_0
)
;
il
.
Emit
(
OpCodes
.
Ldstr
,
methodName
)
;
il
.
Emit
(
OpCodes
.
Ldnull
)
;
// don't fall back to the base type's method
il
.
Emit
(
OpCodes
.
Ldc_I4
,
argTypes
.
Count
)
;
il
.
Emit
(
OpCodes
.
Newarr
,
typeof
(
object
)
)
;
il
.
Emit
(
OpCodes
.
Stloc_0
)
;
for
(
var
i
=
0
;
i
<
argTypes
.
Count
;
++
i
)
{
il
.
Emit
(
OpCodes
.
Ldloc_0
)
;
il
.
Emit
(
OpCodes
.
Ldc_I4
,
i
)
;
il
.
Emit
(
OpCodes
.
Ldarg
,
i
+
1
)
;
if
(
argTypes
[
i
]
.
IsValueType
)
{
il
.
Emit
(
OpCodes
.
Box
,
argTypes
[
i
]
)
;
}
il
.
Emit
(
OpCodes
.
Stelem
,
typeof
(
object
)
)
;
}
il
.
Emit
(
OpCodes
.
Ldloc_0
)
;
if
(
returnType
==
typeof
(
void
)
)
{
il
.
Emit
(
OpCodes
.
Call
,
typeof
(
PythonDerivedType
)
.
GetMethod
(
"InvokeMethodVoid"
)
)
;
}
else
{
il
.
Emit
(
OpCodes
.
Call
,
typeof
(
PythonDerivedType
)
.
GetMethod
(
"InvokeMethod"
)
.
MakeGenericMethod
(
returnType
)
)
;
}
il
.
Emit
(
OpCodes
.
Ret
)
;
}
}
/// <summary>
/// Python properties may have the following function attributes set to control how they're exposed:
/// - _clr_property_type_ - property type (required)
/// </summary>
/// <param name="propertyName">Property name to add to the type</param>
/// <param name="func">Python property object</param>
/// <param name="typeBuilder">TypeBuilder for the new type the method/property is to be added to</param>
private
static
void
AddPythonProperty
(
string
propertyName
,
PyObject
func
,
TypeBuilder
typeBuilder
)
{
// add the method to call back into python
MethodAttributes
methodAttribs
=
MethodAttributes
.
Public
|
MethodAttributes
.
Virtual
|
MethodAttributes
.
ReuseSlot
|
MethodAttributes
.
HideBySig
|
MethodAttributes
.
SpecialName
;
using
(
PyObject
pyPropertyType
=
func
.
GetAttr
(
"_clr_property_type_"
)
)
{
var
propertyType
=
pyPropertyType
.
AsManagedObject
(
typeof
(
Type
)
)
as
Type
;
if
(
propertyType
==
null
)
{
throw
new
ArgumentException
(
"_clr_property_type must be a CLR type"
)
;
}
PropertyBuilder
propertyBuilder
=
typeBuilder
.
DefineProperty
(
propertyName
,
PropertyAttributes
.
None
,
propertyType
,
null
)
;
if
(
func
.
HasAttr
(
"fget"
)
)
{
using
(
PyObject
pyfget
=
func
.
GetAttr
(
"fget"
)
)
{
if
(
pyfget
.
IsTrue
(
)
)
{
MethodBuilder
methodBuilder
=
typeBuilder
.
DefineMethod
(
"get_"
+
propertyName
,
methodAttribs
,
propertyType
,
null
)
;
ILGenerator
il
=
methodBuilder
.
GetILGenerator
(
)
;
il
.
Emit
(
OpCodes
.
Ldarg_0
)
;
il
.
Emit
(
OpCodes
.
Ldstr
,
propertyName
)
;
il
.
Emit
(
OpCodes
.
Call
,
typeof
(
PythonDerivedType
)
.
GetMethod
(
"InvokeGetProperty"
)
.
MakeGenericMethod
(
propertyType
)
)
;
il
.
Emit
(
OpCodes
.
Ret
)
;
propertyBuilder
.
SetGetMethod
(
methodBuilder
)
;
}
}
}
if
(
func
.
HasAttr
(
"fset"
)
)
{
using
(
PyObject
pyset
=
func
.
GetAttr
(
"fset"
)
)
{
if
(
pyset
.
IsTrue
(
)
)
{
MethodBuilder
methodBuilder
=
typeBuilder
.
DefineMethod
(
"set_"
+
propertyName
,
methodAttribs
,
null
,
new
[
]
{
propertyType
}
)
;
ILGenerator
il
=
methodBuilder
.
GetILGenerator
(
)
;
il
.
Emit
(
OpCodes
.
Ldarg_0
)
;
il
.
Emit
(
OpCodes
.
Ldstr
,
propertyName
)
;
il
.
Emit
(
OpCodes
.
Ldarg_1
)
;
il
.
Emit
(
OpCodes
.
Call
,
typeof
(
PythonDerivedType
)
.
GetMethod
(
"InvokeSetProperty"
)
.
MakeGenericMethod
(
propertyType
)
)
;
il
.
Emit
(
OpCodes
.
Ret
)
;
propertyBuilder
.
SetSetMethod
(
methodBuilder
)
;
}
}
}
}
}
private
static
ModuleBuilder
GetModuleBuilder
(
string
assemblyName
,
string
moduleName
)
{
// find or create a dynamic assembly and module
AppDomain
domain
=
AppDomain
.
CurrentDomain
;
ModuleBuilder
moduleBuilder
;
if
(
moduleBuilders
.
ContainsKey
(
Tuple
.
Create
(
assemblyName
,
moduleName
)
)
)
{
moduleBuilder
=
moduleBuilders
[
Tuple
.
Create
(
assemblyName
,
moduleName
)
]
;
}
else
{
AssemblyBuilder
assemblyBuilder
;
if
(
assemblyBuilders
.
ContainsKey
(
assemblyName
)
)
{
assemblyBuilder
=
assemblyBuilders
[
assemblyName
]
;
}
else
{
assemblyBuilder
=
domain
.
DefineDynamicAssembly
(
new
AssemblyName
(
assemblyName
)
,
AssemblyBuilderAccess
.
Run
)
;
assemblyBuilders
[
assemblyName
]
=
assemblyBuilder
;
}
moduleBuilder
=
assemblyBuilder
.
DefineDynamicModule
(
moduleName
)
;
moduleBuilders
[
Tuple
.
Create
(
assemblyName
,
moduleName
)
]
=
moduleBuilder
;
}
return
moduleBuilder
;
}
}
/// <summary>
/// PythonDerivedType contains static methods used by the dynamically created
/// derived type that allow it to call back into python from overridden virtual
/// methods, and also handle the construction and destruction of the python
/// object.
/// </summary>
/// <remarks>
/// This has to be public as it's called from methods on dynamically built classes
/// potentially in other assemblies.
/// </remarks>
public
class
PythonDerivedType
{
/// <summary>
/// This is the implementation of the overridden methods in the derived
/// type. It looks for a python method with the same name as the method
/// on the managed base class and if it exists and isn't the managed
/// method binding (i.e. it has been overridden in the derived python
/// class) it calls it, otherwise it calls the base method.
/// </summary>
public
static
T
InvokeMethod
<
T
>
(
IPythonDerivedType
obj
,
string
methodName
,
string
origMethodName
,
object
[
]
args
)
{
FieldInfo
fi
=
obj
.
GetType
(
)
.
GetField
(
"__pyobj__"
)
;
var
self
=
(
CLRObject
)
fi
.
GetValue
(
obj
)
;
if
(
null
!=
self
)
{
var
disposeList
=
new
List
<
PyObject
>
(
)
;
IntPtr
gs
=
Runtime
.
PyGILState_Ensure
(
)
;
try
{
Runtime
.
XIncref
(
self
.
pyHandle
)
;
var
pyself
=
new
PyObject
(
self
.
pyHandle
)
;
disposeList
.
Add
(
pyself
)
;
Runtime
.
XIncref
(
Runtime
.
PyNone
)
;
var
pynone
=
new
PyObject
(
Runtime
.
PyNone
)
;
disposeList
.
Add
(
pynone
)
;
PyObject
method
=
pyself
.
GetAttr
(
methodName
,
pynone
)
;
disposeList
.
Add
(
method
)
;
if
(
method
.
Handle
!=
Runtime
.
PyNone
)
{
// if the method hasn't been overridden then it will be a managed object
ManagedType
managedMethod
=
ManagedType
.
GetManagedObject
(
method
.
Handle
)
;
if
(
null
==
managedMethod
)
{
var
pyargs
=
new
PyObject
[
args
.
Length
]
;
for
(
var
i
=
0
;
i
<
args
.
Length
;
++
i
)
{
pyargs
[
i
]
=
new
PyObject
(
Converter
.
ToPythonImplicit
(
args
[
i
]
)
)
;
disposeList
.
Add
(
pyargs
[
i
]
)
;
}
PyObject
py_result
=
method
.
Invoke
(
pyargs
)
;
disposeList
.
Add
(
py_result
)
;
return
(
T
)
py_result
.
AsManagedObject
(
typeof
(
T
)
)
;
}
}
}
finally
{
foreach
(
PyObject
x
in
disposeList
)
{
x
?
.
Dispose
(
)
;
}
Runtime
.
PyGILState_Release
(
gs
)
;
}
}
if
(
origMethodName
==
null
)
{
throw
new
NotImplementedException
(
"Python object does not have a '"
+
methodName
+
"' method"
)
;
}
return
(
T
)
obj
.
GetType
(
)
.
InvokeMember
(
origMethodName
,
BindingFlags
.
InvokeMethod
,
null
,
obj
,
args
)
;
}
public
static
void
InvokeMethodVoid
(
IPythonDerivedType
obj
,
string
methodName
,
string
origMethodName
,
object
[
]
args
)
{
FieldInfo
fi
=
obj
.
GetType
(
)
.
GetField
(
"__pyobj__"
)
;
var
self
=
(
CLRObject
)
fi
.
GetValue
(
obj
)
;
if
(
null
!=
self
)
{
var
disposeList
=
new
List
<
PyObject
>
(
)
;
IntPtr
gs
=
Runtime
.
PyGILState_Ensure
(
)
;
try
{
Runtime
.
XIncref
(
self
.
pyHandle
)
;
var
pyself
=
new
PyObject
(
self
.
pyHandle
)
;
disposeList
.
Add
(
pyself
)
;
Runtime
.
XIncref
(
Runtime
.
PyNone
)
;
var
pynone
=
new
PyObject
(
Runtime
.
PyNone
)
;
disposeList
.
Add
(
pynone
)
;
PyObject
method
=
pyself
.
GetAttr
(
methodName
,
pynone
)
;
disposeList
.
Add
(
method
)
;
if
(
method
.
Handle
!=
Runtime
.
PyNone
)
{
// if the method hasn't been overridden then it will be a managed object
ManagedType
managedMethod
=
ManagedType
.
GetManagedObject
(
method
.
Handle
)
;
if
(
null
==
managedMethod
)
{
var
pyargs
=
new
PyObject
[
args
.
Length
]
;
for
(
var
i
=
0
;
i
<
args
.
Length
;
++
i
)
{
pyargs
[
i
]
=
new
PyObject
(
Converter
.
ToPythonImplicit
(
args
[
i
]
)
)
;
disposeList
.
Add
(
pyargs
[
i
]
)
;
}
PyObject
py_result
=
method
.
Invoke
(
pyargs
)
;
disposeList
.
Add
(
py_result
)
;
return
;
}
}
}
finally
{
foreach
(
PyObject
x
in
disposeList
)
{
x
?
.
Dispose
(
)
;
}
Runtime
.
PyGILState_Release
(
gs
)
;
}
}
if
(
origMethodName
==
null
)
{
throw
new
NotImplementedException
(
$
"Python object does not have a '
{
methodName
}
' method"
)
;
}
obj
.
GetType
(
)
.
InvokeMember
(
origMethodName
,
BindingFlags
.
InvokeMethod
,
null
,
obj
,
args
)
;
}
public
static
T
InvokeGetProperty
<
T
>
(
IPythonDerivedType
obj
,
string
propertyName
)
{
FieldInfo
fi
=
obj
.
GetType
(
)
.
GetField
(
"__pyobj__"
)
;
var
self
=
(
CLRObject
)
fi
.
GetValue
(
obj
)
;
if
(
null
==
self
)
{
throw
new
NullReferenceException
(
"Instance must be specified when getting a property"
)
;
}
IntPtr
gs
=
Runtime
.
PyGILState_Ensure
(
)
;
try
{
Runtime
.
XIncref
(
self
.
pyHandle
)
;
using
(
var
pyself
=
new
PyObject
(
self
.
pyHandle
)
)
using
(
PyObject
pyvalue
=
pyself
.
GetAttr
(
propertyName
)
)
{
return
(
T
)
pyvalue
.
AsManagedObject
(
typeof
(
T
)
)
;
}
}
finally
{
Runtime
.
PyGILState_Release
(
gs
)
;
}
}
public
static
void
InvokeSetProperty
<
T
>
(
IPythonDerivedType
obj
,
string
propertyName
,
T
value
)
{
FieldInfo
fi
=
obj
.
GetType
(
)
.
GetField
(
"__pyobj__"
)
;
var
self
=
(
CLRObject
)
fi
.
GetValue
(
obj
)
;
if
(
null
==
self
)
{
throw
new
NullReferenceException
(
"Instance must be specified when setting a property"
)
;
}
IntPtr
gs
=
Runtime
.
PyGILState_Ensure
(
)
;
try
{
Runtime
.
XIncref
(
self
.
pyHandle
)
;
using
(
var
pyself
=
new
PyObject
(
self
.
pyHandle
)
)
using
(
var
pyvalue
=
new
PyObject
(
Converter
.
ToPythonImplicit
(
value
)
)
)
{
pyself
.
SetAttr
(
propertyName
,
pyvalue
)
;
}
}
finally
{
Runtime
.
PyGILState_Release
(
gs
)
;
}
}
public
static
void
InvokeCtor
(
IPythonDerivedType
obj
,
string
origCtorName
,
object
[
]
args
)
{
// call the base constructor
obj
.
GetType
(
)
.
InvokeMember
(
origCtorName
,
BindingFlags
.
InvokeMethod
,
null
,
obj
,
args
)
;
CLRObject
self
=
null
;
IntPtr
gs
=
Runtime
.
PyGILState_Ensure
(
)
;
try
{
// create the python object
IntPtr
type
=
TypeManager
.
GetTypeHandle
(
obj
.
GetType
(
)
)
;
self
=
new
CLRObject
(
obj
,
type
)
;
// set __pyobj__ to self and deref the python object which will allow this
// object to be collected.
FieldInfo
fi
=
obj
.
GetType
(
)
.
GetField
(
"__pyobj__"
)
;
fi
.
SetValue
(
obj
,
self
)
;
}
finally
{
// Decrement the python object's reference count.
// This doesn't actually destroy the object, it just sets the reference to this object
// to be a weak reference and it will be destroyed when the C# object is destroyed.
if
(
null
!=
self
)
{
Runtime
.
XDecref
(
self
.
pyHandle
)
;
}
Runtime
.
PyGILState_Release
(
gs
)
;
}
}
public
static
void
Finalize
(
IPythonDerivedType
obj
)
{
FieldInfo
fi
=
obj
.
GetType
(
)
.
GetField
(
"__pyobj__"
)
;
var
self
=
(
CLRObject
)
fi
.
GetValue
(
obj
)
;
// If python's been terminated then just free the gchandle.
lock
(
Runtime
.
IsFinalizingLock
)
{
if
(
0
==
Runtime
.
Py_IsInitialized
(
)
||
Runtime
.
IsFinalizing
)
{
if
(
self
.
gcHandle
.
IsAllocated
)
self
.
gcHandle
.
Free
(
)
;
return
;
}
}
// delete the python object in an async task as we may not be able to acquire
// the GIL immediately and we don't want to block the GC thread.
// FIXME: t isn't used
Task
t
=
Task
.
Factory
.
StartNew
(
(
)
=>
{
lock
(
Runtime
.
IsFinalizingLock
)
{
// If python's been terminated then just free the gchandle.
if
(
0
==
Runtime
.
Py_IsInitialized
(
)
||
Runtime
.
IsFinalizing
)
{
if
(
self
.
gcHandle
.
IsAllocated
)
self
.
gcHandle
.
Free
(
)
;
return
;
}
IntPtr
gs
=
Runtime
.
PyGILState_Ensure
(
)
;
try
{
// the C# object is being destroyed which must mean there are no more
// references to the Python object as well so now we can dealloc the
// python object.
IntPtr
dict
=
Marshal
.
ReadIntPtr
(
self
.
pyHandle
,
ObjectOffset
.
TypeDictOffset
(
self
.
tpHandle
)
)
;
if
(
dict
!=
IntPtr
.
Zero
)
{
Runtime
.
XDecref
(
dict
)
;
}
Runtime
.
PyObject_GC_Del
(
self
.
pyHandle
)
;
self
.
gcHandle
.
Free
(
)
;
}
finally
{
Runtime
.
PyGILState_Release
(
gs
)
;
}
}
}
)
;
}
}
}
Back
|
FazBrowse Home
|
New Git URL