diff --git a/src/AppKit/NSApplication.cs b/src/AppKit/NSApplication.cs index e379330b8e0c..9e51298de8c1 100644 --- a/src/AppKit/NSApplication.cs +++ b/src/AppKit/NSApplication.cs @@ -70,10 +70,23 @@ public static void Init () // But can affect child xbuild processes, so unset Environment.SetEnvironmentVariable ("MONO_CFG_DIR", ""); + // custom initialization might have happened before native NSApplication code was full ready to be queried + // as such it's possible that `class_ptr` might be empty and that will make things fails later + // reference: https://github.com/xamarin/xamarin-macios/issues/7932 + if (class_ptr == IntPtr.Zero) + ResetHandle (); + // TODO: // Install hook to register dynamically loaded assemblies } + // separate method so it can be invoked without `Init` (if needed) + static void ResetHandle () + { + // `class_ptr` is `readonly` so one can't simply do `class_ptr = Class.GetHandle ("NSApplication");` + typeof (NSApplication).GetField ("class_ptr", BindingFlags.Static | BindingFlags.NonPublic).SetValue (null, Class.GetHandle ("NSApplication")); + } + public static void InitDrawingBridge () { FieldInfo UseCocoaDrawableField = Type.GetType ("System.Drawing.GDIPlus, System.Drawing").GetField ("UseCocoaDrawable", BindingFlags.Static | BindingFlags.Public);