2

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() };
        ...
  }
svick
  • 236,525
  • 50
  • 385
  • 514
Ko.Y
  • 325
  • 1
  • 2
  • 7

1 Answers1

6

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.

thehennyy
  • 4,020
  • 1
  • 22
  • 31
  • Runtime error:Operation may damage run-time stability. – Ko.Y May 17 '17 at 09:07
  • 1
    @Kenny This answer is correct. The first argument is `typeof(int).MakeByRefType()` and is located at the index zero, thus should be loaded with `ldarg.0`. That works for me. If you want multiple references, emit the code in a loop. – IS4 May 18 '17 at 20:47
  • Kinda sad you can't do typeof(ref T), though I suppose enforcing proper stack scoping for it would've been a chore. – hoodaticus Jun 15 '17 at 18:24