@@ -93,7 +93,6 @@ internal static Version PyVersion
9393 }
9494 }
9595
96-
9796 /// <summary>
9897 /// Initialize the runtime...
9998 /// </summary>
@@ -113,7 +112,10 @@ internal static void Initialize(bool initSigs = false, ShutdownMode mode = Shutd
113112 }
114113 ShutdownMode = mode ;
115114
116- if ( Py_IsInitialized ( ) == 0 )
115+ bool interpreterAlreadyInitialized = TryUsingDll (
116+ ( ) => Py_IsInitialized ( ) != 0
117+ ) ;
118+ if ( ! interpreterAlreadyInitialized )
117119 {
118120 Py_InitializeEx ( initSigs ? 1 : 0 ) ;
119121 if ( PyEval_ThreadsInitialized ( ) == 0 )
@@ -787,6 +789,34 @@ internal static unsafe long Refcount(IntPtr op)
787789 return * p ;
788790 }
789791
792+ /// <summary>
793+ /// Call specified function, and handle PythonDLL-related failures.
794+ /// </summary>
795+ internal static T TryUsingDll< T > ( Func < T > op )
796+ {
797+ try
798+ {
799+ return op ( ) ;
800+ }
801+ catch ( TypeInitializationException loadFailure )
802+ {
803+ var delegatesLoadFailure = loadFailure ;
804+ // failure to load Delegates type might have been the cause
805+ // of failure to load some higher-level type
806+ while ( delegatesLoadFailure . InnerException is TypeInitializationException nested)
807+ {
808+ delegatesLoadFailure = nested ;
809+ }
810+
811+ if ( delegatesLoadFailure . InnerException is BadPythonDllException badDll)
812+ {
813+ throw badDll ;
814+ }
815+
816+ throw ;
817+ }
818+ }
819+
790820 /// <summary>
791821 /// Export of Macro Py_XIncRef. Use XIncref instead.
792822 /// Limit this function usage for Testing and Py_Debug builds
@@ -2270,10 +2300,6 @@ internal static void SetNoSiteFlag()
22702300 if ( _PythonDll != "__Internal" )
22712301 {
22722302 dllLocal = loader . Load ( _PythonDll ) ;
2273- if ( dllLocal == IntPtr . Zero )
2274- {
2275- throw new Exception ( $ "Cannot load { _PythonDll } ") ;
2276- }
22772303 }
22782304 try
22792305 {
@@ -2617,8 +2643,8 @@ static Delegates()
26172643 }
26182644 catch ( MissingMethodException e ) when ( libraryHandle == IntPtr . Zero )
26192645 {
2620- throw new MissingMethodException (
2621- "Did you forget to set Runtime.PythonDLL? " +
2646+ throw new BadPythonDllException (
2647+ "Runtime.PythonDLL was not set or does not point to a supported Python runtime DLL. " +
26222648 " See https://github.com/pythonnet/pythonnet#embedding-python-in-net" ,
26232649 e ) ;
26242650 }
@@ -2889,6 +2915,12 @@ static Delegates()
28892915 }
28902916 }
28912917
2918+ internal class BadPythonDllException : MissingMethodException
2919+ {
2920+ public BadPythonDllException ( string message, Exception innerException)
2921+ : base ( message , innerException ) { }
2922+ }
2923+
28922924
28932925 public enum ShutdownMode
28942926 {
0 commit comments