none
Create method with System.Reflection.Emit RRS feed

  • Question

  • Hi,

    I want to create and save an assembly using reflection.emit. I can create and save the assembly, but my sample method throws an error. Somehow I guess that I have a flaw in the .Emit-Methods writing the IML-Code for the method. The method simply takes two integers and returns the sum of both. Can somehone correct this?:

    Here is my code:

      Sub Main()
    
        Console.WriteLine("Creating new type")
        Console.ReadKey()
    
        Dim ad As AppDomain = System.Threading.Thread.GetDomain
        Dim name As New AssemblyName
        name.Name = "MyAssembly"
        Dim aBuilder As AssemblyBuilder = ad.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave)
        Dim mBuilder As ModuleBuilder = aBuilder.DefineDynamicModule("MyModule", name.Name & ".dll")
        Dim tBuilder As TypeBuilder = mBuilder.DefineType("MathOps", TypeAttributes.Public)
    
        Dim retType As Type = GetType(System.Int32)
        Dim parms As Type() = {GetType(System.Int32), GetType(Int32)}
    
        Dim mB As MethodBuilder = tBuilder.DefineMethod("ReturnSum", MethodAttributes.Public, retType, parms)
        Dim iG As ILGenerator = mB.GetILGenerator
    
        With iG
          .Emit(OpCodes.Nop)
          .Emit(OpCodes.Ldarg_1)
          .Emit(OpCodes.Ldarg_2)
          .Emit(OpCodes.Add_Ovf)
          .Emit(OpCodes.Stloc_0)
          .Emit(OpCodes.Br_S)
          .Emit(OpCodes.Ldloc_0)
          .Emit(OpCodes.Ret)
        End With
    
        tBuilder.CreateType()
    
        aBuilder.Save(name.Name & ".dll")
      End Sub
    

    Thanks a lot!

    Friday, March 4, 2011 11:31 AM

Answers

  • "throws an error."

    What error?

    "  .Emit(OpCodes.Br_S)"

    This is a branch instruction, it needs a label, where is it?

    • Marked as answer by Torsten Tiedt Friday, March 4, 2011 3:31 PM
    Friday, March 4, 2011 11:50 AM
    Moderator

All replies

  • "throws an error."

    What error?

    "  .Emit(OpCodes.Br_S)"

    This is a branch instruction, it needs a label, where is it?

    • Marked as answer by Torsten Tiedt Friday, March 4, 2011 3:31 PM
    Friday, March 4, 2011 11:50 AM
    Moderator
  • Here it is:

    gen.Emit(

     

    OpCodes.Br_S, label7)

    gen.MarkLabel(label7)

    Thx!

    Friday, March 4, 2011 3:31 PM