@@ -103,14 +103,44 @@ Execute `f()` on the main thread.
103103on_main_thread
104104
105105
106+ function find_lib_ptr ()
107+ # borrowed from PyCall.jl/src/startup.jl
108+ @static if Sys. iswindows ()
109+ EnumProcessModules (hProcess, lphModule, cb, lpcbNeeded) =
110+ ccall (:K32EnumProcessModules , stdcall, Bool,
111+ (Ptr{Cvoid}, Ptr{Ptr{Cvoid}}, UInt32, Ptr{UInt32}),
112+ hProcess, lphModule, cb, lpcbNeeded)
113+
114+ lpcbneeded = Ref {UInt32} ()
115+ proc_handle = ccall (:GetCurrentProcess , stdcall, Ptr{Cvoid}, ())
116+ handles = Vector {Ptr{Cvoid}} (undef, 20 )
117+ if EnumProcessModules (proc_handle, handles, sizeof (handles), lpcbneeded) == 0
118+ resize! (handles, div (lpcbneeded[],sizeof (Ptr{Cvoid})))
119+ if EnumProcessModules (proc_handle, handles, sizeof (handles), lpcbneeded) == 0
120+ error ()
121+ end
122+ end
123+ for handle in handles
124+ if ccall (:GetProcAddress , stdcall, Ptr{Cvoid},
125+ (Ptr{Cvoid}, Ptr{UInt8}), handle, " Py_GetVersion" ) != C_NULL
126+ return handle
127+ end
128+ end
129+ error (" could not find libpython handle" )
130+ else
131+ return unsafe_load (cglobal (:jl_exe_handle , Ptr{Cvoid}))
132+ end
133+ end
134+
135+
106136function init_context ()
107137
108138 CTX. is_embedded = hasproperty (Base. Main, :__PythonCall_embedded__ )
109139
110140 if CTX. is_embedded
111141 # In this case, getting a handle to libpython is easy
112- CTX. lib_ptr = C_NULL
113- init_pointers (true )
142+ CTX. lib_ptr = find_lib_ptr ()
143+ init_pointers ()
114144 # Check Python is initialized
115145 Py_IsInitialized () == 0 && error (" Python is not already initialized." )
116146 CTX. is_initialized = true
@@ -236,7 +266,7 @@ function init_context()
236266 end
237267
238268 # Get function pointers from the library
239- init_pointers (false )
269+ init_pointers ()
240270
241271 # Initialize the interpreter
242272 CTX. is_preinitialized = Py_IsInitialized () != 0
0 commit comments