C#如何从DynamicMethod获取RuntimeMethodHandle?

时间:2017-08-31 03:02:47

标签: c# dynamicmethod

我想在.Net Framework 4中用动态方法替换方法,然后我在Dynamically replace the contents of a C# method?中找到了一个非常有用的答案,但我无法直接从DynamicMethod获取MethodHandle:

  

我们无法返回MethodHandle,因为我们无法通过GC跟踪它,因此此方法不受限制

在本文CLR Injection: Runtime Method Replacer中,

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 methodDynamicResolverResolveToken方法返回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在获取时必须为null。

这是我的动态方法:

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之后的下一步,并拒绝动态方法,但我希望这可以帮助其他人。

1 个答案:

答案 0 :(得分:1)

哈哈@ lock(this)

.NET Framework在v3.5之后更改了其内存规格

您需要输入条件以针对框架版本进行测试。

通常,您希望通过执行以下操作来重载该方法:

private static RuntimeMethodHandle GetDynamicMethodRuntimeHandle(DynamicMethod method) => method.MethodHandle;

但是,动态方法不支持此操作。

获取基本定义似乎可行。

GetDynamicMethodRuntimeHandle(DynamicMethod method) => GetDynamicMethodRuntimeHandle(method.GetBaseDefinition());

private static RuntimeMethodHandle GetDynamicMethodRuntimeHandle(MethodBase method) {
  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;
}

可以简化为:

private static IntPtr GetDynamicMethodRuntimeHandle(MethodBase method) {
  if (!(method is DynamicMethod))
    return method.MethodHandle.Value;
  var fieldInfo = typeof(DynamicMethod).GetField("m_method", BindingFlags.NonPublic | BindingFlags.Instance);
  return fieldInfo != null ? ((RuntimeMethodHandle) fieldInfo.GetValue(method)).Value : method.MethodHandle.Value;
}