通过 Reflection.Emit 生成代理仅在使用调试启动时有效

发布于 2024-11-04 23:33:28 字数 5900 浏览 0 评论 0原文

大学时的一个任务是使用 Reflection.Emit 实现一个简单的代理生成器/拦截器机制。 我想出了以下程序。

它似乎在调试模式 [F5](调试 -> 开始调试)下在 Visual Studio 中工作得很好,但在不调试的情况下启动时大多数时候会崩溃[Ctrl + F5](调试->开始而不调试)。

这两种模式有什么区别? (我指的是调试<>发布模式)。 该问题出现在多台计算机/设置上(Win XP SP3 32 位和 64 位、Windows 7 32 位)。

点击获取pastebin。

// The proxy generator; I assume that the error is buried along the lines emitting the IL code
public static class ProxyGenerator
{
    public static T Create<T>(object obj, IInterception interception)
    {
        Type type = obj.GetType();

        TypeBuilder proxy = DefineProxy(type);

        FieldBuilder wrappedField = DefinePrivateField(proxy, "wrappedObject", type);
        FieldBuilder interceptionField = DefinePrivateField(proxy, "interception", interception.GetType());

        DefineConstructor(proxy, wrappedField, interceptionField);
        DefineInterfaceMethods(type, proxy, wrappedField, interceptionField);

        return (T) Activator.CreateInstance(proxy.CreateType(), obj, interception);
    }

    private static TypeBuilder DefineProxy(Type type)
    {
        var assemblyName = new AssemblyName {Name = "GeneratedProxyAssembly"};
        AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
            assemblyName, AssemblyBuilderAccess.Run);

        ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("GeneratedProxyModule");

        return moduleBuilder.DefineType(
            type.Name + "Proxy",
            type.Attributes,
            typeof (object),
            type.GetInterfaces());
    }

    private static FieldBuilder DefinePrivateField(TypeBuilder typeBuilder, string fieldName, Type fieldType)
    {
        return typeBuilder.DefineField(fieldName, fieldType, FieldAttributes.Private);
    }

    private static void DefineConstructor(TypeBuilder typeBuilder, params FieldBuilder[] parameters)
    {
        ConstructorBuilder ctor = typeBuilder.DefineConstructor(
            MethodAttributes.Public, CallingConventions.Standard, parameters.Select(f => f.FieldType).ToArray());

        // Emit constructor
        ILGenerator g = ctor.GetILGenerator();

        // Load "this" pointer and call base constructor
        g.Emit(OpCodes.Ldarg_0);
        g.Emit(OpCodes.Call, typeof(object).GetConstructor(new Type[0]));

        // Store parameters in private fields
        for (int i = 0; i < parameters.Length; i++)
        {
            // Load "this" pointer and parameter and store paramater in private field
            g.Emit(OpCodes.Ldarg_0);
            g.Emit(OpCodes.Ldarg, i + 1);
            g.Emit(OpCodes.Stfld, parameters[i]);
        }

        // Return
        g.Emit(OpCodes.Ret);
    }

    private static void DefineInterfaceMethods(Type type, TypeBuilder proxy, FieldInfo wrappedField, FieldInfo interceptionField)
    {
        // Loop through all interface methods
        foreach (MethodInfo interfaceMethod in type.GetInterfaces().SelectMany(i => i.GetMethods()))
        {
            MethodInfo method = type.GetMethod(interfaceMethod.Name);

            MethodBuilder methodBuilder = proxy.DefineMethod(
                method.Name,
                method.Attributes,
                method.ReturnType,
                method.GetParameters().Select(p => p.ParameterType).ToArray());

            // Emit method
            ILGenerator g = methodBuilder.GetILGenerator();

            // Intercept before
            EmitMethodCallOnMember(g, interceptionField, "Before", false);

            // Delegate method call
            EmitMethodCallOnMember(g, wrappedField, method.Name, true);

            // Intercept after
            EmitMethodCallOnMember(g, interceptionField, "After", false);

            // Return
            g.Emit(OpCodes.Ret);
        }
    }

    private static void EmitMethodCallOnMember(ILGenerator g, FieldInfo field, string methodName, bool delegateParameters)
    {
        // Load "this" pointer to get address of field
        g.Emit(OpCodes.Ldarg_0);
        g.Emit(OpCodes.Ldflda, field);

        MethodInfo method = field.FieldType.GetMethod(methodName);
        if (delegateParameters)
        {
            // Load method parameters
            for (int i = 0; i < method.GetParameters().Length; i++)
            {
                g.Emit(OpCodes.Ldarg, i + 1);
            }
        }

        // Emit call
        g.Emit(OpCodes.Call, method);
    }
}

// Some infrastructure
public interface IInterception
{
    void Before();
    void After();
}

public class LogInterception : IInterception
{
    public void Before()
    {
        Console.WriteLine("Before ... ");
    }

    public void After()
    {
        Console.WriteLine("... After");
    }
}

public interface ITest
{
    string DoSomething(string s1, string s2);
}

public class Test : ITest
{
    public string DoSomething(string s1, string s2)
    {
        Console.WriteLine("... doing something ...");
        return s1 + s2;
    }
}

 // The test program, expected output is down below

internal class Program
{
    internal static void Main(string[] args)
    {
        var test = new Test();
        var proxy = ProxyGenerator.Create<ITest>(test, new LogInterception());

        Console.WriteLine(test.DoSomething("Hello", " World"));
        Console.WriteLine("----------------------------------------");
        Console.WriteLine(proxy.DoSomething("Hello", " World"));

        Console.ReadKey();
    }
}

另一个问题:缩小此类问题范围的最佳方法是什么? 我尝试将生成的程序集保存到磁盘并在 Reflector 中打开生成的 dll,但它似乎是空的。

如上所述,当在调试模式下启动时,程序似乎可以工作并打印以下输出。

... doing something ...
Hello World
----------------------------------------
Before ...
... doing something ...
... After
Hello World

感谢您抽出时间。

A task at university was to implement a simple proxy generator / interceptor mechanism using Reflection.Emit.
I came up with the following program.

It seems to work just fine inside Visual Studio in debug mode [F5] (Debug -> Start Debugging) but crashes most of the time when started without debugging [Ctrl + F5] (Debug -> Start Without Debugging).

What is the difference between these two modes? (I do not refer to Debug <> Release mode).
The issue occurs on multiple machines/setups (Win XP SP3 32bit and 64bit, Windows 7 32bit).

Click for pastebin.

// The proxy generator; I assume that the error is buried along the lines emitting the IL code
public static class ProxyGenerator
{
    public static T Create<T>(object obj, IInterception interception)
    {
        Type type = obj.GetType();

        TypeBuilder proxy = DefineProxy(type);

        FieldBuilder wrappedField = DefinePrivateField(proxy, "wrappedObject", type);
        FieldBuilder interceptionField = DefinePrivateField(proxy, "interception", interception.GetType());

        DefineConstructor(proxy, wrappedField, interceptionField);
        DefineInterfaceMethods(type, proxy, wrappedField, interceptionField);

        return (T) Activator.CreateInstance(proxy.CreateType(), obj, interception);
    }

    private static TypeBuilder DefineProxy(Type type)
    {
        var assemblyName = new AssemblyName {Name = "GeneratedProxyAssembly"};
        AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
            assemblyName, AssemblyBuilderAccess.Run);

        ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("GeneratedProxyModule");

        return moduleBuilder.DefineType(
            type.Name + "Proxy",
            type.Attributes,
            typeof (object),
            type.GetInterfaces());
    }

    private static FieldBuilder DefinePrivateField(TypeBuilder typeBuilder, string fieldName, Type fieldType)
    {
        return typeBuilder.DefineField(fieldName, fieldType, FieldAttributes.Private);
    }

    private static void DefineConstructor(TypeBuilder typeBuilder, params FieldBuilder[] parameters)
    {
        ConstructorBuilder ctor = typeBuilder.DefineConstructor(
            MethodAttributes.Public, CallingConventions.Standard, parameters.Select(f => f.FieldType).ToArray());

        // Emit constructor
        ILGenerator g = ctor.GetILGenerator();

        // Load "this" pointer and call base constructor
        g.Emit(OpCodes.Ldarg_0);
        g.Emit(OpCodes.Call, typeof(object).GetConstructor(new Type[0]));

        // Store parameters in private fields
        for (int i = 0; i < parameters.Length; i++)
        {
            // Load "this" pointer and parameter and store paramater in private field
            g.Emit(OpCodes.Ldarg_0);
            g.Emit(OpCodes.Ldarg, i + 1);
            g.Emit(OpCodes.Stfld, parameters[i]);
        }

        // Return
        g.Emit(OpCodes.Ret);
    }

    private static void DefineInterfaceMethods(Type type, TypeBuilder proxy, FieldInfo wrappedField, FieldInfo interceptionField)
    {
        // Loop through all interface methods
        foreach (MethodInfo interfaceMethod in type.GetInterfaces().SelectMany(i => i.GetMethods()))
        {
            MethodInfo method = type.GetMethod(interfaceMethod.Name);

            MethodBuilder methodBuilder = proxy.DefineMethod(
                method.Name,
                method.Attributes,
                method.ReturnType,
                method.GetParameters().Select(p => p.ParameterType).ToArray());

            // Emit method
            ILGenerator g = methodBuilder.GetILGenerator();

            // Intercept before
            EmitMethodCallOnMember(g, interceptionField, "Before", false);

            // Delegate method call
            EmitMethodCallOnMember(g, wrappedField, method.Name, true);

            // Intercept after
            EmitMethodCallOnMember(g, interceptionField, "After", false);

            // Return
            g.Emit(OpCodes.Ret);
        }
    }

    private static void EmitMethodCallOnMember(ILGenerator g, FieldInfo field, string methodName, bool delegateParameters)
    {
        // Load "this" pointer to get address of field
        g.Emit(OpCodes.Ldarg_0);
        g.Emit(OpCodes.Ldflda, field);

        MethodInfo method = field.FieldType.GetMethod(methodName);
        if (delegateParameters)
        {
            // Load method parameters
            for (int i = 0; i < method.GetParameters().Length; i++)
            {
                g.Emit(OpCodes.Ldarg, i + 1);
            }
        }

        // Emit call
        g.Emit(OpCodes.Call, method);
    }
}

// Some infrastructure
public interface IInterception
{
    void Before();
    void After();
}

public class LogInterception : IInterception
{
    public void Before()
    {
        Console.WriteLine("Before ... ");
    }

    public void After()
    {
        Console.WriteLine("... After");
    }
}

public interface ITest
{
    string DoSomething(string s1, string s2);
}

public class Test : ITest
{
    public string DoSomething(string s1, string s2)
    {
        Console.WriteLine("... doing something ...");
        return s1 + s2;
    }
}

 // The test program, expected output is down below

internal class Program
{
    internal static void Main(string[] args)
    {
        var test = new Test();
        var proxy = ProxyGenerator.Create<ITest>(test, new LogInterception());

        Console.WriteLine(test.DoSomething("Hello", " World"));
        Console.WriteLine("----------------------------------------");
        Console.WriteLine(proxy.DoSomething("Hello", " World"));

        Console.ReadKey();
    }
}

Another question: What's the best way to narrow down such issues?
I tried to save the generated assembly to disk and open the resulting dll in Reflector but it appeared to be empty.

As mentioned above, when started in debug mode the program seems to work and prints the following output.

... doing something ...
Hello World
----------------------------------------
Before ...
... doing something ...
... After
Hello World

Thanks for your time.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绿萝 2024-11-11 23:33:28

尝试在项目设置选项卡上显式设置x86模式。

仅当在x64中运行程序时,我才遇到致命异常AnyCpu 模式。

啊,我明白了。将 Ldflda 替换为 Ldfld。即使没有调试器它也能正常工作(我刚刚运行了.exe)。
Ldflda 用于使用 refout 关键字作为参数传递到方法中的字段。

Try to explicitly set x86 mode on project settings tab.

I got the fatal exception only when run program in x64 or AnyCpu mode.

Ah, I've got it. Replace Ldflda with Ldfld. It works fine even without debugger (I just ran .exe).
Ldflda is for fields you pass into method as parameters with ref or out keyword.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文