FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
pythonnet/src/runtime/DelegateManager.cs at master · generalloki/pythonnet · GitHub
generalloki
pythonnet
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
pythonnet
/
src
/
runtime
/
DelegateManager.cs
Copy path
More file actions
More file actions
Latest commit
History
History
History
343 lines (303 loc) · 13.8 KB
Breadcrumbs
pythonnet
/
src
/
runtime
/
DelegateManager.cs
Copy path
File metadata and controls
343 lines (303 loc) · 13.8 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
using
System
;
using
System
.
Collections
.
Generic
;
using
System
.
Linq
;
using
System
.
Reflection
;
using
System
.
Reflection
.
Emit
;
using
System
.
Text
;
using
Python
.
Runtime
.
Native
;
namespace
Python
.
Runtime
{
/// <summary>
/// The DelegateManager class manages the creation of true managed
/// delegate instances that dispatch calls to Python methods.
/// </summary>
internal
class
DelegateManager
{
private
readonly
Dictionary
<
Type
,
Type
>
cache
=
new
(
)
;
private
readonly
Type
basetype
=
typeof
(
Dispatcher
)
;
private
readonly
Type
arrayType
=
typeof
(
object
[
]
)
;
private
readonly
Type
voidtype
=
typeof
(
void
)
;
private
readonly
Type
typetype
=
typeof
(
Type
)
;
private
readonly
Type
pyobjType
=
typeof
(
PyObject
)
;
private
readonly
CodeGenerator
codeGenerator
=
new
(
)
;
private
readonly
ConstructorInfo
arrayCtor
;
private
readonly
MethodInfo
dispatch
;
public
DelegateManager
(
)
{
arrayCtor
=
arrayType
.
GetConstructor
(
new
[
]
{
typeof
(
int
)
}
)
;
dispatch
=
basetype
.
GetMethod
(
"Dispatch"
)
;
}
/// <summary>
/// GetDispatcher is responsible for creating a class that provides
/// an appropriate managed callback method for a given delegate type.
/// </summary>
private
Type
GetDispatcher
(
Type
dtype
)
{
// If a dispatcher type for the given delegate type has already
// been generated, get it from the cache. The cache maps delegate
// types to generated dispatcher types. A possible optimization
// for the future would be to generate dispatcher types based on
// unique signatures rather than delegate types, since multiple
// delegate types with the same sig could use the same dispatcher.
if
(
cache
.
TryGetValue
(
dtype
,
out
Type
item
)
)
{
return
item
;
}
string
name
=
$
"__
{
dtype
.
FullName
}
Dispatcher"
;
name
=
name
.
Replace
(
'.'
,
'_'
)
;
name
=
name
.
Replace
(
'+'
,
'_'
)
;
TypeBuilder
tb
=
codeGenerator
.
DefineType
(
name
,
basetype
)
;
// Generate a constructor for the generated type that calls the
// appropriate constructor of the Dispatcher base type.
MethodAttributes
ma
=
MethodAttributes
.
Public
|
MethodAttributes
.
HideBySig
|
MethodAttributes
.
SpecialName
|
MethodAttributes
.
RTSpecialName
;
var
cc
=
CallingConventions
.
Standard
;
Type
[
]
args
=
{
pyobjType
,
typetype
}
;
ConstructorBuilder
cb
=
tb
.
DefineConstructor
(
ma
,
cc
,
args
)
;
ConstructorInfo
ci
=
basetype
.
GetConstructor
(
BindingFlags
.
Instance
|
BindingFlags
.
NonPublic
,
null
,
args
,
null
)
;
ILGenerator
il
=
cb
.
GetILGenerator
(
)
;
il
.
Emit
(
OpCodes
.
Ldarg_0
)
;
il
.
Emit
(
OpCodes
.
Ldarg_1
)
;
il
.
Emit
(
OpCodes
.
Ldarg_2
)
;
il
.
Emit
(
OpCodes
.
Call
,
ci
)
;
il
.
Emit
(
OpCodes
.
Ret
)
;
// Method generation: we generate a method named "Invoke" on the
// dispatcher type, whose signature matches the delegate type for
// which it is generated. The method body simply packages the
// arguments and hands them to the Dispatch() method, which deals
// with converting the arguments, calling the Python method and
// converting the result of the call.
MethodInfo
method
=
dtype
.
GetMethod
(
"Invoke"
)
;
ParameterInfo
[
]
pi
=
method
.
GetParameters
(
)
;
var
signature
=
new
Type
[
pi
.
Length
]
;
for
(
var
i
=
0
;
i
<
pi
.
Length
;
i
++
)
{
signature
[
i
]
=
pi
[
i
]
.
ParameterType
;
}
MethodBuilder
mb
=
tb
.
DefineMethod
(
"Invoke"
,
MethodAttributes
.
Public
,
method
.
ReturnType
,
signature
)
;
il
=
mb
.
GetILGenerator
(
)
;
// loc_0 = new object[pi.Length]
il
.
DeclareLocal
(
arrayType
)
;
il
.
Emit
(
OpCodes
.
Ldc_I4
,
pi
.
Length
)
;
il
.
Emit
(
OpCodes
.
Newobj
,
arrayCtor
)
;
il
.
Emit
(
OpCodes
.
Stloc_0
)
;
bool
anyByRef
=
false
;
for
(
var
c
=
0
;
c
<
signature
.
Length
;
c
++
)
{
Type
t
=
signature
[
c
]
;
il
.
Emit
(
OpCodes
.
Ldloc_0
)
;
il
.
Emit
(
OpCodes
.
Ldc_I4
,
c
)
;
il
.
Emit
(
OpCodes
.
Ldarg_S
,
(
byte
)
(
c
+
1
)
)
;
if
(
t
.
IsByRef
)
{
// The argument is a pointer. We must dereference the pointer to get the value or object it points to.
t
=
t
.
GetElementType
(
)
;
if
(
t
.
IsValueType
)
{
il
.
Emit
(
OpCodes
.
Ldobj
,
t
)
;
}
else
{
il
.
Emit
(
OpCodes
.
Ldind_Ref
)
;
}
anyByRef
=
true
;
}
if
(
t
.
IsValueType
)
{
il
.
Emit
(
OpCodes
.
Box
,
t
)
;
}
// args[c] = arg
il
.
Emit
(
OpCodes
.
Stelem_Ref
)
;
}
il
.
Emit
(
OpCodes
.
Ldarg_0
)
;
il
.
Emit
(
OpCodes
.
Ldloc_0
)
;
il
.
Emit
(
OpCodes
.
Call
,
dispatch
)
;
if
(
anyByRef
)
{
// Dispatch() will have modified elements of the args list that correspond to out parameters.
CodeGenerator
.
GenerateMarshalByRefsBack
(
il
,
signature
)
;
}
if
(
method
.
ReturnType
==
voidtype
)
{
il
.
Emit
(
OpCodes
.
Pop
)
;
}
else
if
(
method
.
ReturnType
.
IsValueType
)
{
il
.
Emit
(
OpCodes
.
Unbox_Any
,
method
.
ReturnType
)
;
}
il
.
Emit
(
OpCodes
.
Ret
)
;
Type
disp
=
tb
.
CreateType
(
)
;
cache
[
dtype
]
=
disp
;
return
disp
;
}
/// <summary>
/// Given a delegate type and a callable Python object, GetDelegate
/// returns an instance of the delegate type. The delegate instance
/// returned will dispatch calls to the given Python object.
/// </summary>
internal
Delegate
GetDelegate
(
Type
dtype
,
PyObject
callable
)
{
Type
dispatcher
=
GetDispatcher
(
dtype
)
;
object
[
]
args
=
{
callable
,
dtype
}
;
object
o
=
Activator
.
CreateInstance
(
dispatcher
,
args
)
;
return
Delegate
.
CreateDelegate
(
dtype
,
o
,
"Invoke"
)
;
}
}
/* When a delegate instance is created that has a Python implementation,
the delegate manager generates a custom subclass of Dispatcher and
instantiates it, passing the IntPtr of the Python callable.
The "real" delegate is created using CreateDelegate, passing the
instance of the generated type and the name of the (generated)
implementing method (Invoke).
The true delegate instance holds the only reference to the dispatcher
instance, which ensures that when the delegate dies, the finalizer
of the referenced instance will be able to decref the Python
callable.
A possible alternate strategy would be to create custom subclasses
of the required delegate type, storing the IntPtr in it directly.
This would be slightly cleaner, but I'm not sure if delegates are
too "special" for this to work. It would be more work, so for now
the 80/20 rule applies :) */
public
class
Dispatcher
{
readonly
PyObject
target
;
readonly
Type
dtype
;
protected
Dispatcher
(
PyObject
target
,
Type
dtype
)
{
this
.
target
=
target
;
this
.
dtype
=
dtype
;
}
public
object
?
Dispatch
(
object
?
[
]
args
)
{
PyGILState
gs
=
PythonEngine
.
AcquireLock
(
)
;
try
{
return
TrueDispatch
(
args
)
;
}
finally
{
PythonEngine
.
ReleaseLock
(
gs
)
;
}
}
private
object
?
TrueDispatch
(
object
?
[
]
args
)
{
MethodInfo
method
=
dtype
.
GetMethod
(
"Invoke"
)
;
ParameterInfo
[
]
pi
=
method
.
GetParameters
(
)
;
Type
rtype
=
method
.
ReturnType
;
NewReference
callResult
;
using
(
var
pyargs
=
Runtime
.
PyTuple_New
(
pi
.
Length
)
)
{
for
(
var
i
=
0
;
i
<
pi
.
Length
;
i
++
)
{
// Here we own the reference to the Python value, and we
// give the ownership to the arg tuple.
using
var
arg
=
Converter
.
ToPython
(
args
[
i
]
,
pi
[
i
]
.
ParameterType
)
;
int
res
=
Runtime
.
PyTuple_SetItem
(
pyargs
.
Borrow
(
)
,
i
,
arg
.
StealOrThrow
(
)
)
;
if
(
res
!=
0
)
{
throw
PythonException
.
ThrowLastAsClrException
(
)
;
}
}
callResult
=
Runtime
.
PyObject_Call
(
target
,
pyargs
.
Borrow
(
)
,
null
)
;
}
if
(
callResult
.
IsNull
(
)
)
{
throw
PythonException
.
ThrowLastAsClrException
(
)
;
}
using
(
callResult
)
{
BorrowedReference
op
=
callResult
.
Borrow
(
)
;
int
byRefCount
=
pi
.
Count
(
parameterInfo
=>
parameterInfo
.
ParameterType
.
IsByRef
)
;
if
(
byRefCount
>
0
)
{
// By symmetry with MethodBinder.Invoke, when there are out
// parameters we expect to receive a tuple containing
// the result, if any, followed by the out parameters. If there is only
// one out parameter and the return type of the method is void,
// we instead receive the out parameter as the result from Python.
bool
isVoid
=
rtype
==
typeof
(
void
)
;
int
tupleSize
=
byRefCount
+
(
isVoid
?
0
:
1
)
;
if
(
isVoid
&&
byRefCount
==
1
)
{
// The return type is void and there is a single out parameter.
for
(
int
i
=
0
;
i
<
pi
.
Length
;
i
++
)
{
Type
t
=
pi
[
i
]
.
ParameterType
;
if
(
t
.
IsByRef
)
{
if
(
!
Converter
.
ToManaged
(
op
,
t
,
out
args
[
i
]
,
true
)
)
{
Exceptions
.
RaiseTypeError
(
$
"The Python function did not return
{
t
.
GetElementType
(
)
}
(the out parameter type)"
)
;
throw
PythonException
.
ThrowLastAsClrException
(
)
;
}
break
;
}
}
return
null
;
}
else
if
(
Runtime
.
PyTuple_Check
(
op
)
&&
Runtime
.
PyTuple_Size
(
op
)
==
tupleSize
)
{
int
index
=
isVoid
?
0
:
1
;
for
(
int
i
=
0
;
i
<
pi
.
Length
;
i
++
)
{
Type
t
=
pi
[
i
]
.
ParameterType
;
if
(
t
.
IsByRef
)
{
BorrowedReference
item
=
Runtime
.
PyTuple_GetItem
(
op
,
index
++
)
;
if
(
!
Converter
.
ToManaged
(
item
,
t
,
out
args
[
i
]
,
true
)
)
{
Exceptions
.
RaiseTypeError
(
$
"The Python function returned a tuple where element
{
i
}
was not
{
t
.
GetElementType
(
)
}
(the out parameter type)"
)
;
throw
PythonException
.
ThrowLastAsClrException
(
)
;
}
}
}
if
(
isVoid
)
{
return
null
;
}
BorrowedReference
item0
=
Runtime
.
PyTuple_GetItem
(
op
,
0
)
;
if
(
!
Converter
.
ToManaged
(
item0
,
rtype
,
out
object
?
result0
,
true
)
)
{
Exceptions
.
RaiseTypeError
(
$
"The Python function returned a tuple where element 0 was not
{
rtype
}
(the return type)"
)
;
throw
PythonException
.
ThrowLastAsClrException
(
)
;
}
return
result0
;
}
else
{
string
tpName
=
Runtime
.
PyObject_GetTypeName
(
op
)
;
if
(
Runtime
.
PyTuple_Check
(
op
)
)
{
tpName
+=
$
" of size
{
Runtime
.
PyTuple_Size
(
op
)
}
"
;
}
var
sb
=
new
StringBuilder
(
)
;
if
(
!
isVoid
)
sb
.
Append
(
rtype
.
FullName
)
;
for
(
int
i
=
0
;
i
<
pi
.
Length
;
i
++
)
{
Type
t
=
pi
[
i
]
.
ParameterType
;
if
(
t
.
IsByRef
)
{
if
(
sb
.
Length
>
0
)
sb
.
Append
(
","
)
;
sb
.
Append
(
t
.
GetElementType
(
)
.
FullName
)
;
}
}
string
returnValueString
=
isVoid
?
""
:
"the return value and "
;
Exceptions
.
RaiseTypeError
(
$
"Expected a tuple (
{
sb
}
) of
{
returnValueString
}
the values for out and ref parameters, got
{
tpName
}
."
)
;
throw
PythonException
.
ThrowLastAsClrException
(
)
;
}
}
if
(
rtype
==
typeof
(
void
)
)
{
return
null
;
}
if
(
!
Converter
.
ToManaged
(
op
,
rtype
,
out
object
?
result
,
true
)
)
{
throw
PythonException
.
ThrowLastAsClrException
(
)
;
}
return
result
;
}
}
}
}
Back
|
FazBrowse Home
|
New Git URL