pardeike / Harmony

A library for patching, replacing and decorating .NET and Mono methods during runtime
https://www.patreon.com/pardeike
MIT License
5.15k stars 485 forks source link

RtDynamicMethod get MetadataToken throws InvalidOperationException #581

Closed yangboyd closed 6 months ago

yangboyd commented 6 months ago

In the patched method, MethodBase.GetCurrentMethod() returns System.Reflection.DynamicMethod.RtDynamicMethod, which throws InvalidOperationException in getting its property MetadataToken.

But in normal method, MethodBase.GetCurrentMethod() returns System.Reflection.RuntimeMethodInfo, which normally get its property MetadataToken.

yangboyd commented 6 months ago

ChatGPT The System.Reflection.DynamicMethod.RtDynamicMethod is an internal class in the .NET Framework that is not meant to be accessed directly by user code. It's used internally by the .NET runtime to implement dynamically generated methods.

When you attempt to access the MetadataToken property of a DynamicMethod instance, it internally tries to cast the method to an RtDynamicMethod, but since RtDynamicMethod is an internal class, this cast fails and results in an InvalidOperationException.

To get the metadata token of a dynamic method in C#, you can use the GetMethodBody().GetMethodToken().Token approach instead.

So we need handle the MetadataToken manually?

pardeike commented 6 months ago

This is the result of how Harmony works and is nothing that will be changed. So a WONTFIX