“Operation could destablize the runtime” and DynamicMethod with value types

余生颓废 提交于 2020-01-03 09:52:12

问题


I'm trying to generalize the following IL (from Reflector):

.method private hidebysig instance void SetValue(valuetype Test.TestFixture/ValueSource& thing, string 'value') cil managed
{
    .maxstack 8
    L_0000: nop 
    L_0001: ldarg.1 
    L_0002: ldarg.2 
    L_0003: call instance void Test.TestFixture/ValueSource::set_Value(string)
    L_0008: nop 
    L_0009: ret 
}

However, when I try and reproduce this IL with DynamicMethod:

        [Test]
    public void Test_with_DynamicMethod()
    {
        var sourceType = typeof(ValueSource);
        PropertyInfo property = sourceType.GetProperty("Value");

        var setter = property.GetSetMethod(true);
        var method = new DynamicMethod("Set" + property.Name, null, new[] { sourceType.MakeByRefType(), typeof(string) }, true);
        var gen = method.GetILGenerator();

        gen.Emit(OpCodes.Ldarg_1); // Load input to stack
        gen.Emit(OpCodes.Ldarg_2); // Load value to stack
        gen.Emit(OpCodes.Call, setter); // Call the setter method
        gen.Emit(OpCodes.Ret);

        var result = (SetValueDelegate)method.CreateDelegate(typeof(SetValueDelegate));

        var source = new ValueSource();

        result(ref source, "hello");

        source.Value.ShouldEqual("hello");
    }

    public delegate void SetValueDelegate(ref ValueSource source, string value);

I get an exception of "Operation could destabilize the runtime". The IL seems identical to me, any ideas? ValueSource is a value type, which is why I'm doing a ref parameter here.

EDIT

Here's the ValueSource type:

public struct ValueSource
{
   public string Value { get; set; }
}

回答1:


Change the args to 0/1 (not 1/2):

    gen.Emit(OpCodes.Ldarg_0); // Load input to stack
    gen.Emit(OpCodes.Ldarg_1); // Load value to stack

because the dynamic method it seems to be created as static, not instance (your original method is instance) - hence the args are off by one.

(sorry for the original wrong answer - you can leave the other bit of code as true)



来源:https://stackoverflow.com/questions/1277779/operation-could-destablize-the-runtime-and-dynamicmethod-with-value-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!