我想在 .Net Framework 4 中用动态方法替换一个方法,然后我在动态替换 C# 方法的内容中找到了一个非常有用的答案?,但我无法直接从 DynamicMethod 获取 MethodHandle:
我们无法返回 MethodHandle,因为我们无法通过 GC 跟踪它,因此此方法不受限制
在这篇文章CLR 注入:运行时方法替换器中,
private static IntPtr GetDynamicMethodRuntimeHandle(MethodBase method)
{
if (method is DynamicMethod)
{
FieldInfo fieldInfo = typeof(DynamicMethod).GetField("m_method",
BindingFlags.NonPublic|BindingFlags.Instance);
return ((RuntimeMethodHandle)fieldInfo.GetValue(method)).Value;
}
return method.MethodHandle.Value;
}
m_method
找不到。
然后我注意到了m_methodHandle
,但不知道它什么时候会被初始化。
internal unsafe RuntimeMethodHandle GetMethodDescriptor() {
if (m_methodHandle == null) {
lock (this) {
if (m_methodHandle == null) {
if (m_DynamicILInfo != null)
m_DynamicILInfo.GetCallableMethod(m_module, this);
else {
if (m_ilGenerator == null || m_ilGenerator.ILOffset == 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadEmptyMethodBody", Name));
m_ilGenerator.GetCallableMethod(m_module, this);
}
}
}
}
return new RuntimeMethodHandle(m_methodHandle);
}
根据另一个问题Resolving the tokens found in the IL from a dynamic method,DynamicResolver
有一个ResolveToken
返回methodHandle
地址的方法。所以我在答案中使用了一些代码:
var resolver = typeof(DynamicMethod)
.GetField("m_resolver", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(dynamicMethod);
if (resolver == null)
throw new ArgumentException("The dynamic method's IL has not been finalized.");
但是...DynamicResolver
只会在方法中被初始化,在DynamicILGenerator.GetCallableMethod
方法中被调用DynamicMethod.GetMethodDescriptor
,所以resolver
当我得到它时必须为空。
这是我的动态方法:
private static MethodInfo build(MethodInfo originMethod)
{
var parameters = originMethod.GetParameters();
var parameterTypes = parameters.Length == 0 ?
null :
parameters
.Select(param => param.ParameterType)
.ToArray();
DynamicMethod method = new DynamicMethod(
originMethod.Name,
originMethod.ReturnType,
parameterTypes,
originMethod.Module);
ILGenerator il = method.GetILGenerator();
il.Emit(OpCodes.Ldstr, "Injected");
var console_writeline = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) });
il.Emit(OpCodes.Call, console_writeline);
il.Emit(OpCodes.Ret);
return method;
}
JIT我学的很少,所以不是很懂。
有人可以帮忙吗?
--------------------------------已编辑----------------- ---------
@Latency 的答案很好:
RuntimeMethodHandle GetMethodRuntimeHandle(MethodBase method)
{
if (!(method is DynamicMethod))
return method.MethodHandle;
RuntimeMethodHandle handle;
if (Environment.Version.Major == 4)
{
var getMethodDescriptorInfo = typeof(DynamicMethod).GetMethod("GetMethodDescriptor", BindingFlags.NonPublic | BindingFlags.Instance);
handle = (RuntimeMethodHandle)getMethodDescriptorInfo.Invoke(method, null);
}
else
{
var fieldInfo = typeof(DynamicMethod).GetField("m_method", BindingFlags.NonPublic | BindingFlags.Instance);
handle = (RuntimeMethodHandle)fieldInfo.GetValue(method);
}
return handle;
}
过了这么久,我不记得在获取 RuntimeMethodHandle 并拒绝动态方法之后接下来会发生什么,但我希望这可以帮助其他人。