Skip to content

Commit

Permalink
Merge pull request #11 from kylewill0725/injecting_fields_regression_fix
Browse files Browse the repository at this point in the history
Fixed regression in injecting fields
  • Loading branch information
ghorsington authored Jul 30, 2020
2 parents c8ca34c + 7dc0b39 commit 9cf2f76
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Harmony/Internal/Patching/HarmonyManipulator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,7 @@ private static void EmitCallParameter(ILEmitter il, MethodBase original, MethodI
}
else
{
fieldInfo = AccessTools.DeclaredField(original.DeclaringType, fieldName);
fieldInfo = AccessTools.Field(original.DeclaringType, fieldName);
if (fieldInfo == null)
throw new ArgumentException(
$"No such field defined in class {original.DeclaringType.FullName}", fieldName);
Expand Down
33 changes: 33 additions & 0 deletions HarmonyTests/Patching/Arguments.cs
Original file line number Diff line number Diff line change
Expand Up @@ -132,5 +132,38 @@ public void TestMethod8Prefix()
Assert.AreEqual(10, result.a);
Assert.AreEqual(20, result.b);
}


[Test]
public void Test_InjectingBaseClassField()
{
var testInstance = new InjectFieldSubClass();
testInstance.Method("foo");
Assert.AreEqual("foo", testInstance.TestValue);

var originalClass = testInstance.GetType();
Assert.IsNotNull(originalClass);
var originalMethod = originalClass.GetMethod("Method");
Assert.IsNotNull(originalMethod);

var patchClass = typeof(InjectFieldSubClass_Patch);
var postfix = patchClass.GetMethod("Postfix");
Assert.IsNotNull(postfix);

var instance = new Harmony("test");
Assert.IsNotNull(instance);

instance.Patch(originalMethod, postfix: new HarmonyMethod(postfix));

var patcher = new PatchProcessor(instance, originalMethod);
Assert.IsNotNull(patcher);
_ = patcher.AddPostfix(postfix);
Assert.IsNotNull(patcher);

_ = patcher.Patch();

testInstance.Method("bar");
Assert.AreEqual("patched", testInstance.TestValue);
}
}
}
31 changes: 31 additions & 0 deletions HarmonyTests/Patching/Assets/PatchClasses.cs
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,37 @@ public static void Prefix2(bool __runOriginal)
}
}

public class InjectFieldBase
{
internal string testField;
}

public class InjectFieldSubClass : InjectFieldBase
{
public string TestValue => testField;

public void Method(string val)
{
try
{
testField = val;
}
catch (Exception)
{
throw;
}
}
}

[HarmonyPatch(typeof(InjectFieldSubClass), nameof(InjectFieldSubClass.Method))]
public class InjectFieldSubClass_Patch
{
public static void Postfix(ref string ___testField)
{
___testField = "patched";
}
}

// disabled - see test case
/*
public class ClassExceptionFilter
Expand Down

0 comments on commit 9cf2f76

Please sign in to comment.