FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
pythonnet/src/runtime/importhook.cs at master · sdpython/pythonnet · GitHub
This repository was archived by the owner on Jul 22, 2023. It is now read-only.
sdpython
pythonnet
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
pythonnet
/
src
/
runtime
/
importhook.cs
Copy path
More file actions
More file actions
Latest commit
History
History
History
399 lines (349 loc) · 14.4 KB
Breadcrumbs
pythonnet
/
src
/
runtime
/
importhook.cs
Copy path
File metadata and controls
399 lines (349 loc) · 14.4 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
using
System
;
using
System
.
Collections
.
Generic
;
using
System
.
Runtime
.
InteropServices
;
namespace
Python
.
Runtime
{
/// <summary>
/// Implements the "import hook" used to integrate Python with the CLR.
/// </summary>
internal
static
class
ImportHook
{
private
static
IntPtr
py_import
;
private
static
CLRModule
root
;
private
static
MethodWrapper
hook
;
private
static
IntPtr
py_clr_module
;
private
static
IntPtr
module_def
=
IntPtr
.
Zero
;
internal
static
void
InitializeModuleDef
(
)
{
if
(
module_def
==
IntPtr
.
Zero
)
{
module_def
=
ModuleDefOffset
.
AllocModuleDef
(
"clr"
)
;
}
}
internal
static
void
ReleaseModuleDef
(
)
{
if
(
module_def
==
IntPtr
.
Zero
)
{
return
;
}
ModuleDefOffset
.
FreeModuleDef
(
module_def
)
;
module_def
=
IntPtr
.
Zero
;
}
/// <summary>
/// Initialize just the __import__ hook itself.
/// </summary>
static
void
InitImport
(
)
{
// We replace the built-in Python __import__ with our own: first
// look in CLR modules, then if we don't find any call the default
// Python __import__.
IntPtr
builtins
=
Runtime
.
GetBuiltins
(
)
;
py_import
=
Runtime
.
PyObject_GetAttr
(
builtins
,
PyIdentifier
.
__import__
)
;
PythonException
.
ThrowIfIsNull
(
py_import
)
;
hook
=
new
MethodWrapper
(
typeof
(
ImportHook
)
,
"__import__"
,
"TernaryFunc"
)
;
int
res
=
Runtime
.
PyObject_SetAttr
(
builtins
,
PyIdentifier
.
__import__
,
hook
.
ptr
)
;
PythonException
.
ThrowIfIsNotZero
(
res
)
;
Runtime
.
XDecref
(
builtins
)
;
}
/// <summary>
/// Restore the __import__ hook.
/// </summary>
static
void
RestoreImport
(
)
{
IntPtr
builtins
=
Runtime
.
GetBuiltins
(
)
;
int
res
=
Runtime
.
PyObject_SetAttr
(
builtins
,
PyIdentifier
.
__import__
,
py_import
)
;
PythonException
.
ThrowIfIsNotZero
(
res
)
;
Runtime
.
XDecref
(
py_import
)
;
py_import
=
IntPtr
.
Zero
;
hook
.
Release
(
)
;
hook
=
null
;
Runtime
.
XDecref
(
builtins
)
;
}
/// <summary>
/// Initialization performed on startup of the Python runtime.
/// </summary>
internal
static
void
Initialize
(
)
{
InitImport
(
)
;
// Initialize the clr module and tell Python about it.
root
=
new
CLRModule
(
)
;
// create a python module with the same methods as the clr module-like object
InitializeModuleDef
(
)
;
py_clr_module
=
Runtime
.
PyModule_Create2
(
module_def
,
3
)
;
// both dicts are borrowed references
IntPtr
mod_dict
=
Runtime
.
PyModule_GetDict
(
py_clr_module
)
;
IntPtr
clr_dict
=
Runtime
.
_PyObject_GetDictPtr
(
root
.
pyHandle
)
;
// PyObject**
clr_dict
=
(
IntPtr
)
Marshal
.
PtrToStructure
(
clr_dict
,
typeof
(
IntPtr
)
)
;
Runtime
.
PyDict_Update
(
mod_dict
,
clr_dict
)
;
IntPtr
dict
=
Runtime
.
PyImport_GetModuleDict
(
)
;
Runtime
.
PyDict_SetItemString
(
dict
,
"CLR"
,
py_clr_module
)
;
Runtime
.
PyDict_SetItemString
(
dict
,
"clr"
,
py_clr_module
)
;
}
/// <summary>
/// Cleanup resources upon shutdown of the Python runtime.
/// </summary>
internal
static
void
Shutdown
(
)
{
if
(
Runtime
.
Py_IsInitialized
(
)
==
0
)
{
return
;
}
RestoreImport
(
)
;
bool
shouldFreeDef
=
Runtime
.
Refcount
(
py_clr_module
)
==
1
;
Runtime
.
XDecref
(
py_clr_module
)
;
py_clr_module
=
IntPtr
.
Zero
;
if
(
shouldFreeDef
)
{
ReleaseModuleDef
(
)
;
}
Runtime
.
XDecref
(
root
.
pyHandle
)
;
root
=
null
;
CLRModule
.
Reset
(
)
;
}
internal
static
void
SaveRuntimeData
(
RuntimeDataStorage
storage
)
{
// Increment the reference counts here so that the objects don't
// get freed in Shutdown.
Runtime
.
XIncref
(
py_clr_module
)
;
Runtime
.
XIncref
(
root
.
pyHandle
)
;
storage
.
AddValue
(
"py_clr_module"
,
py_clr_module
)
;
storage
.
AddValue
(
"root"
,
root
.
pyHandle
)
;
}
internal
static
void
RestoreRuntimeData
(
RuntimeDataStorage
storage
)
{
InitImport
(
)
;
storage
.
GetValue
(
"py_clr_module"
,
out
py_clr_module
)
;
var
rootHandle
=
storage
.
GetValue
<
IntPtr
>
(
"root"
)
;
root
=
(
CLRModule
)
ManagedType
.
GetManagedObject
(
rootHandle
)
;
}
/// <summary>
/// Return the clr python module (new reference)
/// </summary>
public
static
IntPtr
GetCLRModule
(
IntPtr
?
fromList
=
null
)
{
root
.
InitializePreload
(
)
;
// update the module dictionary with the contents of the root dictionary
root
.
LoadNames
(
)
;
IntPtr
py_mod_dict
=
Runtime
.
PyModule_GetDict
(
py_clr_module
)
;
IntPtr
clr_dict
=
Runtime
.
_PyObject_GetDictPtr
(
root
.
pyHandle
)
;
// PyObject**
clr_dict
=
(
IntPtr
)
Marshal
.
PtrToStructure
(
clr_dict
,
typeof
(
IntPtr
)
)
;
Runtime
.
PyDict_Update
(
py_mod_dict
,
clr_dict
)
;
// find any items from the from list and get them from the root if they're not
// already in the module dictionary
if
(
fromList
!=
null
&&
fromList
!=
IntPtr
.
Zero
)
{
if
(
Runtime
.
PyTuple_Check
(
fromList
.
GetValueOrDefault
(
)
)
)
{
Runtime
.
XIncref
(
py_mod_dict
)
;
using
(
var
mod_dict
=
new
PyDict
(
py_mod_dict
)
)
{
Runtime
.
XIncref
(
fromList
.
GetValueOrDefault
(
)
)
;
using
(
var
from
=
new
PyTuple
(
fromList
.
GetValueOrDefault
(
)
)
)
{
foreach
(
PyObject
item
in
from
)
{
if
(
mod_dict
.
HasKey
(
item
)
)
{
continue
;
}
var
s
=
item
.
AsManagedObject
(
typeof
(
string
)
)
as
string
;
if
(
s
==
null
)
{
continue
;
}
ManagedType
attr
=
root
.
GetAttribute
(
s
,
true
)
;
if
(
attr
==
null
)
{
continue
;
}
Runtime
.
XIncref
(
attr
.
pyHandle
)
;
using
(
var
obj
=
new
PyObject
(
attr
.
pyHandle
)
)
{
mod_dict
.
SetItem
(
s
,
obj
)
;
}
}
}
}
}
}
Runtime
.
XIncref
(
py_clr_module
)
;
return
py_clr_module
;
}
/// <summary>
/// The actual import hook that ties Python to the managed world.
/// </summary>
public
static
IntPtr
__import__
(
IntPtr
self
,
IntPtr
args
,
IntPtr
kw
)
{
// Replacement for the builtin __import__. The original import
// hook is saved as this.py_import. This version handles CLR
// import and defers to the normal builtin for everything else.
var
num_args
=
Runtime
.
PyTuple_Size
(
args
)
;
if
(
num_args
<
1
)
{
return
Exceptions
.
RaiseTypeError
(
"__import__() takes at least 1 argument (0 given)"
)
;
}
// borrowed reference
IntPtr
py_mod_name
=
Runtime
.
PyTuple_GetItem
(
args
,
0
)
;
if
(
py_mod_name
==
IntPtr
.
Zero
||
!
Runtime
.
IsStringType
(
py_mod_name
)
)
{
return
Exceptions
.
RaiseTypeError
(
"string expected"
)
;
}
// Check whether the import is of the form 'from x import y'.
// This determines whether we return the head or tail module.
IntPtr
fromList
=
IntPtr
.
Zero
;
var
fromlist
=
false
;
if
(
num_args
>=
4
)
{
fromList
=
Runtime
.
PyTuple_GetItem
(
args
,
3
)
;
if
(
fromList
!=
IntPtr
.
Zero
&&
Runtime
.
PyObject_IsTrue
(
fromList
)
==
1
)
{
fromlist
=
true
;
}
}
string
mod_name
=
Runtime
.
GetManagedString
(
py_mod_name
)
;
// Check these BEFORE the built-in import runs; may as well
// do the Incref()ed return here, since we've already found
// the module.
if
(
mod_name
==
"clr"
)
{
IntPtr
clr_module
=
GetCLRModule
(
fromList
)
;
if
(
clr_module
!=
IntPtr
.
Zero
)
{
IntPtr
sys_modules
=
Runtime
.
PyImport_GetModuleDict
(
)
;
if
(
sys_modules
!=
IntPtr
.
Zero
)
{
Runtime
.
PyDict_SetItemString
(
sys_modules
,
"clr"
,
clr_module
)
;
}
}
return
clr_module
;
}
string
realname
=
mod_name
;
string
clr_prefix
=
null
;
// 2010-08-15: Always seemed smart to let python try first...
// This shaves off a few tenths of a second on test_module.py
// and works around a quirk where 'sys' is found by the
// LoadImplicit() deprecation logic.
// Turns out that the AssemblyManager.ResolveHandler() checks to see if any
// Assembly's FullName.ToLower().StartsWith(name.ToLower()), which makes very
// little sense to me.
IntPtr
res
=
Runtime
.
PyObject_Call
(
py_import
,
args
,
kw
)
;
if
(
res
!=
IntPtr
.
Zero
)
{
// There was no error.
if
(
fromlist
&&
IsLoadAll
(
fromList
)
)
{
var
mod
=
ManagedType
.
GetManagedObject
(
res
)
as
ModuleObject
;
mod
?
.
LoadNames
(
)
;
}
return
res
;
}
// There was an error
if
(
!
Exceptions
.
ExceptionMatches
(
Exceptions
.
ImportError
)
)
{
// and it was NOT an ImportError; bail out here.
return
IntPtr
.
Zero
;
}
if
(
mod_name
==
string
.
Empty
)
{
// Most likely a missing relative import.
// For example site-packages\bs4\builder\__init__.py uses it to check if a package exists:
// from . import _html5lib
// We don't support them anyway
return
IntPtr
.
Zero
;
}
// Save the exception
var
originalException
=
new
PythonException
(
)
;
// Otherwise, just clear the it.
Exceptions
.
Clear
(
)
;
string
[
]
names
=
realname
.
Split
(
'.'
)
;
// See if sys.modules for this interpreter already has the
// requested module. If so, just return the existing module.
IntPtr
modules
=
Runtime
.
PyImport_GetModuleDict
(
)
;
IntPtr
module
=
Runtime
.
PyDict_GetItem
(
modules
,
py_mod_name
)
;
if
(
module
!=
IntPtr
.
Zero
)
{
if
(
fromlist
)
{
if
(
IsLoadAll
(
fromList
)
)
{
var
mod
=
ManagedType
.
GetManagedObject
(
module
)
as
ModuleObject
;
mod
?
.
LoadNames
(
)
;
}
Runtime
.
XIncref
(
module
)
;
return
module
;
}
if
(
clr_prefix
!=
null
)
{
return
GetCLRModule
(
fromList
)
;
}
module
=
Runtime
.
PyDict_GetItemString
(
modules
,
names
[
0
]
)
;
Runtime
.
XIncref
(
module
)
;
return
module
;
}
Exceptions
.
Clear
(
)
;
// Traverse the qualified module name to get the named module
// and place references in sys.modules as we go. Note that if
// we are running in interactive mode we pre-load the names in
// each module, which is often useful for introspection. If we
// are not interactive, we stick to just-in-time creation of
// objects at lookup time, which is much more efficient.
// NEW: The clr got a new module variable preload. You can
// enable preloading in a non-interactive python processing by
// setting clr.preload = True
ModuleObject
head
=
mod_name
==
realname
?
null
:
root
;
ModuleObject
tail
=
root
;
root
.
InitializePreload
(
)
;
foreach
(
string
name
in
names
)
{
ManagedType
mt
=
tail
.
GetAttribute
(
name
,
true
)
;
if
(
!
(
mt
is
ModuleObject
)
)
{
originalException
.
Restore
(
)
;
return
IntPtr
.
Zero
;
}
if
(
head
==
null
)
{
head
=
(
ModuleObject
)
mt
;
}
tail
=
(
ModuleObject
)
mt
;
if
(
CLRModule
.
preload
)
{
tail
.
LoadNames
(
)
;
}
// Add the module to sys.modules
Runtime
.
PyDict_SetItemString
(
modules
,
tail
.
moduleName
,
tail
.
pyHandle
)
;
// If imported from CLR add clr.<modulename> to sys.modules as well
if
(
clr_prefix
!=
null
)
{
Runtime
.
PyDict_SetItemString
(
modules
,
clr_prefix
+
tail
.
moduleName
,
tail
.
pyHandle
)
;
}
}
{
var
mod
=
fromlist
?
tail
:
head
;
if
(
fromlist
&&
IsLoadAll
(
fromList
)
)
{
mod
.
LoadNames
(
)
;
}
Runtime
.
XIncref
(
mod
.
pyHandle
)
;
return
mod
.
pyHandle
;
}
}
private
static
bool
IsLoadAll
(
IntPtr
fromList
)
{
if
(
CLRModule
.
preload
)
{
return
false
;
}
if
(
Runtime
.
PySequence_Size
(
fromList
)
!=
1
)
{
return
false
;
}
IntPtr
fp
=
Runtime
.
PySequence_GetItem
(
fromList
,
0
)
;
bool
res
=
Runtime
.
GetManagedString
(
fp
)
==
"*"
;
Runtime
.
XDecref
(
fp
)
;
return
res
;
}
}
}
Back
|
FazBrowse Home
|
New Git URL