Search code examples
c#cilemitdynamicmethod

How to represent typeof(Int32&) type in DynamicMethod Emit


I have the following code:

    delegate void RefAction(ref Int32 i);// use ref keyword
    static RefAction CreateRefGenerator(){
        // How to represent typeof(Int32&)type in here??
        Type[] types ={ typeof(Int32)};
        var dm = new DynamicMethod("RefAction"+Guid.NewGuid().ToString(), null, types, true);
        var il = dm.GetILGenerator();
        il.Emit(OpCodes.Nop);
        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Ldc_I4_S,10);
        il.Emit(OpCodes.Stind_I4);
        il.Emit(OpCodes.Ret);

        return (RefAction)dm.CreateDelegate(typeof(RefAction));
    }

After running, get the following error:

Because its signature or security transparency is incompatible with the signature or security transparency of the delegate type.

The following normal work:

  static RefAction CreateRefGenerator(){
        Type[] types = { typeof(Int32).MakeByRefType() };
        ...
  }

Solution

  • You have to use the Type.MakeByRefType method to create your ref type.

    Returns a Type object that represents the current type when passed as a ref parameter


    Also there is probably an error in your il code: Afaik a dynamic method is always static, therefore the first explicit argument can be found at index zero and not one.