开发者

emit code crashes at runtime but not in debug, why

开发者 https://www.devze.com 2023-03-21 07:06 出处:网络
I have some code, that build up a proxy from a type. It work perfekt. Then I have add in the setter emit code, that it has to push a isDirty bit, when it is call. This fail, why?

I have some code, that build up a proxy from a type. It work perfekt. Then I have add in the setter emit code, that it has to push a isDirty bit, when it is call. This fail, why?

If I run the code without the isDirty bit, it works. If I run the code with the isDirty bit, it works in debug, but is start the disassembly window up in visual studio. If I run the code with the isDirty (without-debug) the program crash (not responding) but when I hit cancel, it starts working and show all de rigth data.

        PropertyBuilder property = proxy.DefineProperty(propertyInfo.Name, propertyInfo.Attributes, propertyInfo.PropertyType, null);
        MethodAttributes attributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Virtual;
        MethodBuilder setMethod = proxy.DefineMethod("set_" + propertyInfo.Name, attributes, typeof(void), new Type[] { propertyInfo.PropertyType });

        ILGenerator setIL = setMethod.GetILGenerator();
        setIL.Emit(OpCodes.Ldarg_0); // load this on the stack - where this is the type we are creating
        setIL.Emit(OpCodes.Ldarg_1); // load first parameter on the stack
        setIL.Emit(OpCodes.Call, propertyInfo.GetSetMethod());

        {
        //error here: when this is uncomment, it fails 
        //    // set the isDirty bit
        //    setIL.Emit(OpCodes.Ldarg_0); // load this on the stack
        //    setIL.Emit(OpCodes.Ldc_I4_1, 1); // push a number on the stack 
        //    setIL.Emit(OpCodes.Stfld, isDirtyField); /开发者_开发技巧/ save the value on the stack in field
        }

        setIL.Emit(OpCodes.Ret);

        property.SetSetMethod(setMethod);

I have a hard time, seeing why this fails? Need some help from the experts :)

// dennis


I'm not sure if this is your only issue, but you are using the wrong Emit overload when emitting your Ldc_I4_1 opcode. You should do either:

setIL.Emit(OpCodes.Ldc_I4_1)

or

setIL.Emit(OpCodes.Ldc_I4, 1)

The first option will result in a slightly smaller IL method body since it uses a specialized opcode, whereas the second one is not specific to the number being loaded.

0

精彩评论

暂无评论...
验证码 换一张
取 消