11using System ;
22using System . ComponentModel ;
3+ using System . Diagnostics ;
4+ using System . Linq ;
35using System . Runtime . InteropServices ;
46
57namespace Python . Runtime . Platform
@@ -195,6 +197,15 @@ public IntPtr Load(string dllToLoad)
195197
196198 public IntPtr GetFunction ( IntPtr hModule , string procedureName )
197199 {
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+
198209 var res = WindowsLoader . GetProcAddress ( hModule , procedureName ) ;
199210 if ( res == IntPtr . Zero )
200211 throw new MissingMethodException ( $ "Failed to load symbol { procedureName } ", new Win32Exception ( ) ) ;
@@ -203,6 +214,24 @@ public IntPtr GetFunction(IntPtr hModule, string procedureName)
203214
204215 public void Free ( IntPtr hModule ) => WindowsLoader . FreeLibrary ( hModule ) ;
205216
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+
206235 [ DllImport ( NativeDll , SetLastError = true ) ]
207236 static extern IntPtr LoadLibrary ( string dllToLoad ) ;
208237
@@ -211,5 +240,8 @@ public IntPtr GetFunction(IntPtr hModule, string procedureName)
211240
212241 [ DllImport ( NativeDll ) ]
213242 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 ) ;
214246 }
215247}
0 commit comments