Skip to content

Commit

Permalink
Improve stability on AppDomain reloads.
Browse files Browse the repository at this point in the history
  • Loading branch information
kring committed Dec 13, 2024
1 parent 6a86882 commit d3ede61
Show file tree
Hide file tree
Showing 4 changed files with 141 additions and 106 deletions.
38 changes: 29 additions & 9 deletions Reinterop~/CSharpObjectHandleUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,15 @@ public static IntPtr CopyHandle(IntPtr handle)
return handle;
// Allocate a new GCHandle pointing to the same object.
GCHandle gcHandle = GCHandle.FromIntPtr(handle);
return GCHandle.ToIntPtr(GCHandle.Alloc(gcHandle.Target));
try
{
GCHandle gcHandle = GCHandle.FromIntPtr(handle);
return GCHandle.ToIntPtr(GCHandle.Alloc(gcHandle.Target));
}
catch (Exception)
{
return IntPtr.Zero;
}
}
public static void FreeHandle(IntPtr handle)
Expand All @@ -50,14 +57,13 @@ public static void FreeHandle(IntPtr handle)
{
GCHandle.FromIntPtr(handle).Free();
}
catch (ArgumentException e)
catch (Exception)
{
// The "GCHandle value belongs to a different domain" exception tends
// to happen on AppDomain reload, which is common in Unity.
// Catch the exception to prevent it propagating through our native
// code and blowing things up.
// See: https://github.com/CesiumGS/cesium-unity/issues/18
System.Console.WriteLine(e.ToString());
}
}
Expand All @@ -66,18 +72,32 @@ public static object GetObjectFromHandle(IntPtr handle)
if (handle == IntPtr.Zero)
return null;
return GCHandle.FromIntPtr(handle).Target;
try
{
return GCHandle.FromIntPtr(handle).Target;
}
catch (Exception)
{
return null;
}
}
public static object GetObjectAndFreeHandle(IntPtr handle)
{
if (handle == IntPtr.Zero)
return null;
GCHandle gcHandle = GCHandle.FromIntPtr(handle);
object result = gcHandle.Target;
gcHandle.Free();
return result;
try
{
GCHandle gcHandle = GCHandle.FromIntPtr(handle);
object result = gcHandle.Target;
gcHandle.Free();
return result;
}
catch (Exception)
{
return null;
}
}
public static void ResetHandleObject(IntPtr handle, object newValue)
Expand Down
Loading

0 comments on commit d3ede61

Please sign in to comment.