Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added new patch for easier casting in IL2CPP #479

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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