1
1
using System ;
2
2
using System . ComponentModel ;
3
+ using System . Diagnostics ;
4
+ using System . Linq ;
3
5
using System . Runtime . InteropServices ;
4
6
5
7
namespace Python . Runtime . Platform
@@ -195,6 +197,15 @@ public IntPtr Load(string dllToLoad)
195
197
196
198
public IntPtr GetFunction ( IntPtr hModule , string procedureName )
197
199
{
200
+ if ( hModule == IntPtr . Zero )
201
+ {
202
+ foreach ( var module in GetAllModules ( ) )
203
+ {
204
+ var func = GetProcAddress ( module , procedureName ) ;
205
+ if ( func != IntPtr . Zero ) return func ;
206
+ }
207
+ }
208
+
198
209
var res = WindowsLoader . GetProcAddress ( hModule , procedureName ) ;
199
210
if ( res == IntPtr . Zero )
200
211
throw new MissingMethodException ( $ "Failed to load symbol { procedureName } ", new Win32Exception ( ) ) ;
@@ -203,6 +214,24 @@ public IntPtr GetFunction(IntPtr hModule, string procedureName)
203
214
204
215
public void Free ( IntPtr hModule ) => WindowsLoader . FreeLibrary ( hModule ) ;
205
216
217
+ static IntPtr [ ] GetAllModules ( )
218
+ {
219
+ var self = Process . GetCurrentProcess ( ) . Handle ;
220
+
221
+ uint bytes = 0 ;
222
+ var result = new IntPtr [ 0 ] ;
223
+ if ( ! EnumProcessModules ( self , result , bytes , out var needsBytes ) )
224
+ throw new Win32Exception ( ) ;
225
+ while ( bytes < needsBytes )
226
+ {
227
+ bytes = needsBytes ;
228
+ result = new IntPtr [ bytes / IntPtr . Size ] ;
229
+ if ( ! EnumProcessModules ( self , result , bytes , out needsBytes ) )
230
+ throw new Win32Exception ( ) ;
231
+ }
232
+ return result . Take ( ( int ) ( needsBytes / IntPtr . Size ) ) . ToArray ( ) ;
233
+ }
234
+
206
235
[ DllImport ( NativeDll , SetLastError = true ) ]
207
236
static extern IntPtr LoadLibrary ( string dllToLoad ) ;
208
237
@@ -211,5 +240,8 @@ public IntPtr GetFunction(IntPtr hModule, string procedureName)
211
240
212
241
[ DllImport ( NativeDll ) ]
213
242
static extern bool FreeLibrary ( IntPtr hModule ) ;
243
+
244
+ [ DllImport ( "Psapi.dll" , SetLastError = true ) ]
245
+ static extern bool EnumProcessModules ( IntPtr hProcess , [ In , Out ] IntPtr [ ] lphModule , uint lphModuleByteCount , out uint byteCountNeeded ) ;
214
246
}
215
247
}
0 commit comments