Skip to content

Commit

Permalink
improves Test_ByRefResultPrefix test and PatchTools.CreateMethod()
Browse files Browse the repository at this point in the history
  • Loading branch information
pardeike committed Dec 19, 2024
1 parent 97b4482 commit 75541fb
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 10 deletions.
35 changes: 32 additions & 3 deletions Harmony/Internal/PatchTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,43 @@ static Assembly GetExecutingAssemblyReplacement()
public static MethodInfo CreateMethod(string name, Type returnType, List<KeyValuePair<string, Type>> parameters, Action<ILGenerator> generator)
{
var parameterTypes = parameters.Select(p => p.Value).ToArray();

if (AccessTools.IsMonoRuntime && HarmonyLib.Tools.isWindows == false)
{
var assemblyName = new AssemblyName("TempAssembly");

#if NET2 || NET35
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
#else
var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
#endif

var moduleBuilder = assemblyBuilder.DefineDynamicModule("TempModule");
var typeBuilder = moduleBuilder.DefineType("TempType", TypeAttributes.Public);

var methodBuilder = typeBuilder.DefineMethod(name,
MethodAttributes.Public | MethodAttributes.Static,
returnType, parameterTypes);

for (var i = 0; i < parameters.Count; i++)
methodBuilder.DefineParameter(i + 1, ParameterAttributes.None, parameters[i].Key);

generator(methodBuilder.GetILGenerator());

#if NETSTANDARD2_0
var createdType = typeBuilder.CreateTypeInfo().AsType();
#else
var createdType = typeBuilder.CreateType();
#endif
return createdType.GetMethod(name, BindingFlags.Public | BindingFlags.Static);
}

var dynamicMethod = new DynamicMethodDefinition(name, returnType, parameterTypes);

for (var i = 0; i < parameters.Count; i++)
dynamicMethod.Definition.Parameters[i].Name = parameters[i].Key;

var il = dynamicMethod.GetILGenerator();
generator(il);

generator(dynamicMethod.GetILGenerator());
return dynamicMethod.Generate();
}

Expand Down
7 changes: 0 additions & 7 deletions HarmonyTests/Patching/DynamicMethodPatches.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,6 @@ public class DynamicMethodPatches : TestLogger
[Test]
public void Test_ByRefResultPrefix()
{
if (AccessTools.IsMonoRuntime && HarmonyLib.Tools.isWindows == false)
{
// no longer works with linux/mac and mono
// System.NotSupportedException : Custom attributes on a ParamInfo with member System.Reflection.Emit.DynamicMethod are not supported
return;
}

var originalClass = typeof(Assets.Class11);
Assert.NotNull(originalClass);

Expand Down

0 comments on commit 75541fb

Please sign in to comment.