Skip to content

Commit

Permalink
Merge pull request #479 from KomiksPL/alpha-development
Browse files Browse the repository at this point in the history
Added new patch for easier casting in IL2CPP
  • Loading branch information
HerpDerpinstine committed Jun 12, 2024
2 parents c8baa13 + b3ec3da commit 833d21f
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion Dependencies/SupportModules/Il2Cpp/Main.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,15 @@
using Il2CppInterop.Runtime.Startup;
using MelonLoader.Support.Preferences;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using HarmonyLib;
using MelonLoader.CoreClrUtils;
using UnityEngine;
using Il2CppInterop.Common;
using Il2CppInterop.Runtime.InteropTypes;
using Microsoft.Extensions.Logging;

namespace MelonLoader.Support
Expand Down Expand Up @@ -47,11 +51,40 @@ private static ISupportModule_To Initialize(ISupportModule_From interface_from)
Interop = new InteropInterface();
Interface.SetInteropSupportInterface(Interop);
//HarmonyLib.Public.Patching.PatchManager.ResolvePatcher += HarmonyMethodPatcher.TryResolve;
Core.HarmonyInstance.Patch(HarmonyLib.AccessTools.TypeByName("System.Runtime.CompilerServices.CastHelpers").GetMethod("ChkCast_Helper", HarmonyLib.AccessTools.all), HarmonyLib.AccessTools.Method(typeof(Main), nameof(ChkCast_HelperPatch)).ToNewHarmonyMethod());
runtime.Start();

return new SupportModule_To();
}


private static Dictionary<IntPtr, Type> AllTypes = AccessTools.AllTypes().ToDictionary(type => type.TypeHandle.Value, type => type);
private static MethodInfo TryCast = typeof(Il2CppObjectBase).GetMethod("TryCast");
private static Type TryGetTypeFromIntPtr(IntPtr intPtr)
{
if (!AllTypes.TryGetValue(intPtr, out var type))
{
AllTypes = AccessTools.AllTypes().ToDictionary(type1 => type1.TypeHandle.Value, type1 => type1);
AllTypes.TryGetValue(intPtr, out var typeP);
type = typeP;
}
return type;
}
private static bool ChkCast_HelperPatch(IntPtr toTypeHnd, object obj, ref object __result)
{
var type = TryGetTypeFromIntPtr(toTypeHnd);
if (type == null)
return true;
if (!(typeof(Il2CppObjectBase).IsAssignableFrom(type) && obj is Il2CppObjectBase))
return true;
var invoke = TryCast.MakeGenericMethod(type).Invoke(obj, Array.Empty<object>());
if (invoke != null)
{
obj = invoke;
__result = invoke;
return false;
}
return true;
}
private static Assembly Il2Cppmscorlib = null;
private static Type streamType = null;
private static void ConsoleCleaner()
Expand Down

0 comments on commit 833d21f

Please sign in to comment.