8

(首先,这是一篇很长的帖子,但别担心:我已经实现了所有这些,我只是在问你的意见,或者可能的替代方案。)

我在执行以下操作时遇到了麻烦;我很感激一些帮助:

  1. 我得到一个Typeas 参数。
  2. 我使用反射定义了一个子类。请注意,我不打算修改原始类型,而是创建一个新类型。
  3. 我为原始类的每个字段创建一个属性,如下所示:

    public class OriginalClass {
        private int x;
    }
    
    
    public class Subclass : OriginalClass {
        private int x;
    
        public int X {
            get { return x; }
            set { x = value; }
        }
    
    }
    
  4. 对于超类的每个方法,我都会在子类中创建一个类似的方法。方法的主体必须相同,只是我将指令替换为ldfld xcallvirt this.get_X也就是说,我调用 get 访问器,而不是直接从字段中读取。

我在第 4 步遇到问题。我知道您不应该像这样操作代码,但我真的需要这样做。

这是我尝试过的:

尝试 #1:使用 Mono.Cecil。这将允许我将方法的主体解析为人类可读的Instructions,并轻松替换指令。但是,原始类型不在 .dll 文件中,所以我找不到使用 Mono.Cecil 加载它的方法。将类型写入 .dll,然后加载它,然后修改它并将新类型写入磁盘(我认为这是使用 Mono.Cecil 创建类型的方式),然后加载它似乎是一个巨大的开销。

尝试#2:使用 Mono.Reflection。这也将允许我将正文解析为Instructions,但我不支持替换指令。我使用 Mono.Reflection 实现了一个非常丑陋且效率低下的解决方案,但它还不支持包含 try-catch 语句的方法(尽管我想我可以实现这个)并且我担心可能存在其他场景它不起作用,因为我ILGenerator以一种不寻常的方式使用它。此外,它非常难看;)。这是我所做的:

private void TransformMethod(MethodInfo methodInfo) {

    // Create a method with the same signature.
    ParameterInfo[] paramList = methodInfo.GetParameters();
    Type[] args = new Type[paramList.Length];
    for (int i = 0; i < args.Length; i++) {
        args[i] = paramList[i].ParameterType;
    }
    MethodBuilder methodBuilder = typeBuilder.DefineMethod(
        methodInfo.Name, methodInfo.Attributes, methodInfo.ReturnType, args);
    ILGenerator ilGen = methodBuilder.GetILGenerator();

    // Declare the same local variables as in the original method.
    IList<LocalVariableInfo> locals = methodInfo.GetMethodBody().LocalVariables;
    foreach (LocalVariableInfo local in locals) {
        ilGen.DeclareLocal(local.LocalType);
    }

    // Get readable instructions.
    IList<Instruction> instructions = methodInfo.GetInstructions();

    // I first need to define labels for every instruction in case I
    // later find a jump to that instruction. Once the instruction has
    // been emitted I cannot label it, so I'll need to do it in advance.
    // Since I'm doing a first pass on the method's body anyway, I could
    // instead just create labels where they are truly needed, but for
    // now I'm using this quick fix.
    Dictionary<int, Label> labels = new Dictionary<int, Label>();
    foreach (Instruction instr in instructions) {
        labels[instr.Offset] = ilGen.DefineLabel();
    }

    foreach (Instruction instr in instructions) {

        // Mark this instruction with a label, in case there's a branch
        // instruction that jumps here.
        ilGen.MarkLabel(labels[instr.Offset]);

        // If this is the instruction that I want to replace (ldfld x)...
        if (instr.OpCode == OpCodes.Ldfld) {
            // ...get the get accessor for the accessed field (get_X())
            // (I have the accessors in a dictionary; this isn't relevant),
            MethodInfo safeReadAccessor = dataMembersSafeAccessors[((FieldInfo) instr.Operand).Name][0];
            // ...instead of emitting the original instruction (ldfld x),
            // emit a call to the get accessor,
            ilGen.Emit(OpCodes.Callvirt, safeReadAccessor);

        // Else (it's any other instruction), reemit the instruction, unaltered.
        } else {
            Reemit(instr, ilGen, labels);
        }

    }

}

这是可怕的,可怕的Reemit方法:

private void Reemit(Instruction instr, ILGenerator ilGen, Dictionary<int, Label> labels) {

    // If the instruction doesn't have an operand, emit the opcode and return.
    if (instr.Operand == null) {
        ilGen.Emit(instr.OpCode);
        return;
    }

    // Else (it has an operand)...

    // If it's a branch instruction, retrieve the corresponding label (to
    // which we want to jump), emit the instruction and return.
    if (instr.OpCode.FlowControl == FlowControl.Branch) {
        ilGen.Emit(instr.OpCode, labels[Int32.Parse(instr.Operand.ToString())]);
        return;
    }

    // Otherwise, simply emit the instruction. I need to use the right
    // Emit call, so I need to cast the operand to its type.
    Type operandType = instr.Operand.GetType();
    if (typeof(byte).IsAssignableFrom(operandType))
        ilGen.Emit(instr.OpCode, (byte) instr.Operand);
    else if (typeof(double).IsAssignableFrom(operandType))
        ilGen.Emit(instr.OpCode, (double) instr.Operand);
    else if (typeof(float).IsAssignableFrom(operandType))
        ilGen.Emit(instr.OpCode, (float) instr.Operand);
    else if (typeof(int).IsAssignableFrom(operandType))
        ilGen.Emit(instr.OpCode, (int) instr.Operand);
    ... // you get the idea. This is a pretty long method, all like this.
}

分支指令是一种特殊情况,因为instr.Operandis SByte,但Emit需要类型为 的操作数Label。因此需要Dictionary labels.

如您所见,这非常可怕。更重要的是,它并非在所有情况下都有效,例如包含 try- catch语句的方法BeginExceptionBlock,因为我没有使用. 这变得越来越复杂。我想我可以做到:有一个列表应该包含执行此操作的必要信息。但无论如何我都不喜欢这个解决方案,所以我会把它保存为最后的解决方案。BeginCatchBlockILGeneratorMethodBodyExceptionHandlingClause

尝试#3:直接复制返回的字节数组MethodBody.GetILAsByteArray(),因为我只想将一条指令替换为另一条相同大小的单条指令,该指令产生完全相同的结果:它在堆栈等。所以不会有任何标签移动,一切都应该完全一样。我已经这样做了,替换了数组的特定字节,然后调用MethodBuilder.CreateMethodBody(byte[], int),但我仍然得到同样的异常错误,我仍然需要声明局部变量,否则我会得到一个错误......即使我只是复制方法的主体,不要改变任何东西。所以这更有效,但我仍然需要处理异常等。

叹。

这是尝试#3的实现,以防有人感兴趣:

private void TransformMethod(MethodInfo methodInfo, Dictionary<string, MethodInfo[]> dataMembersSafeAccessors, ModuleBuilder moduleBuilder) {

    ParameterInfo[] paramList = methodInfo.GetParameters();
    Type[] args = new Type[paramList.Length];
    for (int i = 0; i < args.Length; i++) {
        args[i] = paramList[i].ParameterType;
    }
    MethodBuilder methodBuilder = typeBuilder.DefineMethod(
        methodInfo.Name, methodInfo.Attributes, methodInfo.ReturnType, args);

    ILGenerator ilGen = methodBuilder.GetILGenerator();

    IList<LocalVariableInfo> locals = methodInfo.GetMethodBody().LocalVariables;
    foreach (LocalVariableInfo local in locals) {
        ilGen.DeclareLocal(local.LocalType);
    }

    byte[] rawInstructions = methodInfo.GetMethodBody().GetILAsByteArray();
    IList<Instruction> instructions = methodInfo.GetInstructions();

    int k = 0;
    foreach (Instruction instr in instructions) {

        if (instr.OpCode == OpCodes.Ldfld) {

            MethodInfo safeReadAccessor = dataMembersSafeAccessors[((FieldInfo) instr.Operand).Name][0];

            // Copy the opcode: Callvirt.
            byte[] bytes = toByteArray(OpCodes.Callvirt.Value);
            for (int m = 0; m < OpCodes.Callvirt.Size; m++) {
                rawInstructions[k++] = bytes[put.Length - 1 - m];
            }

            // Copy the operand: the accessor's metadata token.
            bytes = toByteArray(moduleBuilder.GetMethodToken(safeReadAccessor).Token);
            for (int m = instr.Size - OpCodes.Ldfld.Size - 1; m >= 0; m--) {
                rawInstructions[k++] = bytes[m];
            }

        // Skip this instruction (do not replace it).
        } else {
            k += instr.Size;
        }

    }

    methodBuilder.CreateMethodBody(rawInstructions, rawInstructions.Length);

}


private static byte[] toByteArray(int intValue) {
    byte[] intBytes = BitConverter.GetBytes(intValue);
    if (BitConverter.IsLittleEndian)
        Array.Reverse(intBytes);
    return intBytes;
}



private static byte[] toByteArray(short shortValue) {
    byte[] intBytes = BitConverter.GetBytes(shortValue);
    if (BitConverter.IsLittleEndian)
        Array.Reverse(intBytes);
    return intBytes;
}

(我知道它不漂亮。对不起。我很快把它放在一起看看它是否有用。)

我不抱太大希望,但有人能提出比这更好的建议吗?

很抱歉这篇文章太长了,谢谢。


更新#1: Aggh ...我刚刚在msdn文档中阅读了这个:

[CreateMethodBody 方法] 目前不完全支持。用户无法提供令牌修复和异常处理程序的位置。

在尝试任何事情之前,我真的应该阅读文档。总有一天我会学...

这意味着选项 #3 不支持 try-catch 语句,这对我来说毫无用处。我真的必须使用可怕的#2吗?:/ 帮助!:P


更新#2:我已经成功实现了尝试#2,支持异常。这很丑陋,但它有效。当我稍微改进代码时,我会在这里发布。这不是优先事项,因此可能需要几周后。只是让你知道,以防有人对此感兴趣。

感谢您的建议。

4

6 回答 6

1

我正在尝试做一件非常相似的事情。我已经尝试过你的#1 方法,我同意,这会产生巨大的开销(虽然我没有准确测量它)。

有一个DynamicMethod类 - 根据 MSDN - “定义并表示可以编译、执行和丢弃的动态方法。丢弃的方法可用于垃圾回收。”

性能方面听起来不错。

使用ILReader库,我可以将普通MethodInfo转换为DynamicMethod当您查看ILReader库的 DyanmicMethodHelper 类的 ConvertFrom 方法时,您可以找到我们需要的代码:

byte[] code = body.GetILAsByteArray();
ILReader reader = new ILReader(method);
ILInfoGetTokenVisitor visitor = new ILInfoGetTokenVisitor(ilInfo, code);
reader.Accept(visitor);

ilInfo.SetCode(code, body.MaxStackSize);

从理论上讲,这让我们修改现有方法的代码并将其作为动态方法运行。

我现在唯一的问题是 Mono.Cecil 不允许我们保存方法的字节码(至少我找不到方法)。当您下载 Mono.Cecil 源代码时,它有一个 CodeWriter 类来完成任务,但它不是公开的。

这种方法的另一个问题是 MethodInfo -> DynamicMethod 转换仅适用于带有ILReader的静态方法。但这可以解决。

调用的性能取决于我使用的方法。在调用短方法 10'000'000 次后,我得到了以下结果:

  • Reflection.Invoke - 14 秒
  • DynamicMethod.Invoke - 26 秒
  • DynamicMethod 与代表 - 9 秒

接下来我要尝试的是:

  1. 用 Cecil 加载原始方法
  2. 修改 Cecil 中的代码
  3. 从程序集中剥离未修改的代码
  4. 将程序集保存为 MemoryStream 而不是 File
  5. 使用反射加载新程序集(从内存中)
  6. 如果是一次性调用,则使用反射调用调用该方法
  7. 如果我想定期调用该方法,则生成 DynamicMethod 的委托并存储它们
  8. 尝试找出我是否可以从内存中卸载不需要的程序集(释放 MemoryStream 和运行时程序集表示)

听起来工作量很大,但可能行不通,我们会看到 :)

我希望它有帮助,让我知道你的想法。

于 2012-09-14T11:22:01.443 回答
0

您必须首先将基类中的属性定义为虚拟或抽象。此外,然后需要将字段修改为“受保护”而不是“私有”。

或者我在这里误解了什么?

于 2010-05-13T14:38:31.590 回答
0

使用 SetMethodBody 代替 CreateMethodBody 怎么样(这将是#3 的变体)?这是 .NET 4.5 中引入的一种新方法,似乎支持异常和修复。

于 2014-09-10T12:47:00.597 回答
0

你试过 PostSharp 吗?我认为它已经通过On Field Access Aspect提供了开箱即用的所有内容。

于 2010-05-10T15:00:39.457 回答
0

也许我理解错了,但如果你想扩展,拦截一个类的现有实例,你可以看看Castle Dynamic Proxy

于 2010-05-10T15:11:39.037 回答
-1

基本上,您是在复制原始类的程序文本,然后对其进行定期更改。您当前的方法是复制该类的目标代码并对其进行修补。我能理解为什么这看起来很丑。你的工作水平极低。

这似乎很容易通过源到源的程序转换来完成。这在源代码的 AST 上运行,而不是在源代码本身上运行以获得精度。有关此类工具,请参阅DMS Software Reengineering Toolkit。DMS 具有完整的 C# 4.0 解析器。

于 2010-05-16T13:25:11.187 回答