Export (0) Print
Expand All

MethodBuilder.CreateMethodBody Method

Creates the body of the method using a supplied byte array of Microsoft Intermediate Language (MSIL) instructions.

[Visual Basic]
Public Sub CreateMethodBody( _
   ByVal il() As Byte, _
   ByVal count As Integer _
)
[C#]
public void CreateMethodBody(
 byte[] il,
 int count
);
[C++]
public: void CreateMethodBody(
 unsigned char il __gc[],
 int count
);
[JScript]
public function CreateMethodBody(
   il : Byte[],
 count : int
);

Parameters

il
An array containing valid MSIL instructions. If this parameter is a null reference (Nothing in Visual Basic), the method's body is cleared.
count
The number of valid bytes in the MSIL array. This value is ignored if MSIL is a null reference (Nothing in Visual Basic).

Exceptions

Exception Type Condition
ArgumentOutOfRangeException The count is not within the range of indexes of the supplied MSIL instruction array and il is not a null reference (Nothing in Visual Basic).
InvalidOperationException The containing type was previously created using CreateType.

-or-

This method was called previously on this MethodBuilder with a non- a null reference (Nothing in Visual Basic) il argument.

Remarks

This method creates the method's body from il, an array containing MSIL instructions as opcodes. The number of bytes of valid MSIL is given by count.

Note   This is currently not fully supported. The user cannot supply the location of token fix ups and exception handlers.

Example

[Visual Basic, C#, C++] In the example provided below, a simple dynamic method that adds two integers is generated via opcode using CreateMethodBody.

[Visual Basic] 
Imports System
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Emit

 _

Class MethodBodyDemo
   
   ' This class will demonstrate how to create a method body using 
   ' the MethodBuilder.CreateMethodBody(byte[], int) method.

   Public Shared Function BuildDynType() As Type
      
      Dim addType As Type = Nothing
      
      Dim currentDom As AppDomain = Thread.GetDomain()
      
      Dim myAsmName As New AssemblyName()
      myAsmName.Name = "MyDynamicAssembly"
      
      Dim myAsmBldr As AssemblyBuilder = currentDom.DefineDynamicAssembly(myAsmName, _
                         AssemblyBuilderAccess.RunAndSave)
      
      ' The dynamic assembly space has been created.  Next, create a module
      ' within it.  The type Point will be reflected into this module.
      Dim myModuleBldr As ModuleBuilder = myAsmBldr.DefineDynamicModule("MyModule")
      
      Dim myTypeBldr As TypeBuilder = myModuleBldr.DefineType("Adder")
      
      Dim myMthdBldr As MethodBuilder = myTypeBldr.DefineMethod("DoAdd", _
                    MethodAttributes.Public Or MethodAttributes.Static, _
                        GetType(Integer), _
                    New Type() {GetType(Integer), GetType(Integer)})

      ' Build the array of Bytes holding the MSIL instructions.

      Dim ILcodes() As Byte = {&H2, &H3, &H58, &H2A}

      ' 02h is the opcode for ldarg.0 
      ' 03h is the opcode for ldarg.1 
      ' 58h is the opcode for add     
      ' 2Ah is the opcode for ret     
      
      myMthdBldr.CreateMethodBody(ILcodes, ILcodes.Length)
      
      addType = myTypeBldr.CreateType()
      
      Return addType

   End Function 'BuildDynType
   
   
   Public Shared Sub Main()
      
      Dim myType As Type = BuildDynType()
      Console.WriteLine("---")
      Console.Write("Enter the first integer to add: ")
      Dim aVal As Integer = Convert.ToInt32(Console.ReadLine())
      
      Console.Write("Enter the second integer to add: ")
      Dim bVal As Integer = Convert.ToInt32(Console.ReadLine())
      
      Dim adderInst As Object = Activator.CreateInstance(myType, New Object() {})
      
      Console.WriteLine("The value of adding {0} to {1} is: {2}.", _
             aVal, bVal, _
             myType.InvokeMember("DoAdd", _
                          BindingFlags.InvokeMethod, _
                          Nothing, _
                          adderInst, _
                          New Object() {aVal, bVal}))

   End Sub 'Main

End Class 'MethodBodyDemo



[C#] 

using System;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;

class MethodBodyDemo {
// This class will demonstrate how to create a method body using 
// the MethodBuilder.CreateMethodBody(byte[], int) method.

   public static Type BuildDynType() {
    
      Type addType = null;

        AppDomain currentDom = Thread.GetDomain();

        AssemblyName myAsmName = new AssemblyName();
    myAsmName.Name = "MyDynamicAssembly";

        AssemblyBuilder myAsmBldr = currentDom.DefineDynamicAssembly(
                           myAsmName,
                           AssemblyBuilderAccess.RunAndSave);

        // The dynamic assembly space has been created.  Next, create a module
        // within it.  The type Point will be reflected into this module.

    ModuleBuilder myModuleBldr = myAsmBldr.DefineDynamicModule("MyModule");
      
    TypeBuilder myTypeBldr =  myModuleBldr.DefineType("Adder");

        MethodBuilder myMthdBldr = myTypeBldr.DefineMethod("DoAdd",
                                MethodAttributes.Public |
                                MethodAttributes.Static,
                                typeof(int),
                                new Type[] 
                                {typeof(int), typeof(int)});
        // Build the array of Bytes holding the MSIL instructions.

        byte[] ILcodes = new byte[] {
          0x02,   /* 02h is the opcode for ldarg.0 */
      0x03,   /* 03h is the opcode for ldarg.1 */
      0x58,   /* 58h is the opcode for add     */
      0x2A    /* 2Ah is the opcode for ret     */
    };
    
    myMthdBldr.CreateMethodBody(ILcodes, ILcodes.Length);

        addType = myTypeBldr.CreateType();

    return addType;
   }

   public static void Main() {

    Type myType = BuildDynType(); 
        Console.WriteLine("---");
    Console.Write("Enter the first integer to add: "); 
        int aVal = Convert.ToInt32(Console.ReadLine());
     
         Console.Write("Enter the second integer to add: ");
         int bVal = Convert.ToInt32(Console.ReadLine());
   
         object adderInst = Activator.CreateInstance(myType, new object[0]); 

    Console.WriteLine("The value of adding {0} to {1} is: {2}.",
               aVal, bVal,    
                    myType.InvokeMember("DoAdd",
                             BindingFlags.InvokeMethod,
                             null,
                             adderInst,
                             new object[] {aVal, bVal})); 
   }

}


[C++] 

#using <mscorlib.dll>

using namespace System;
using namespace System::Threading;
using namespace System::Reflection;
using namespace System::Reflection::Emit;

class MethodBodyDemo {
   // This class will demonstrate how to create a method body using
   // the MethodBuilder::CreateMethodBody(Byte[], int) method.

public:
   static Type* BuildDynType() {

      Type* addType = 0;

      AppDomain*  currentDom = Thread::GetDomain();

      AssemblyName* myAsmName = new AssemblyName();
      myAsmName->Name = S"MyDynamicAssembly";

      AssemblyBuilder*  myAsmBldr = currentDom->DefineDynamicAssembly(myAsmName,
         AssemblyBuilderAccess::RunAndSave);

      // The dynamic assembly space has been created.  Next, create a module
      // within it.  The type Point will be reflected into this module.

      ModuleBuilder*  myModuleBldr = myAsmBldr->DefineDynamicModule(S"MyModule");

      TypeBuilder*  myTypeBldr =  myModuleBldr->DefineType(S"Adder");

      Type* temp0 [] = {__typeof(int), __typeof(int)};
      MethodBuilder*  myMthdBldr = myTypeBldr->DefineMethod(
         S"DoAdd",
         static_cast<MethodAttributes>(MethodAttributes::Public | MethodAttributes::Static),
         __typeof(int),
         temp0);
      // Build the array of Bytes holding the MSIL instructions.

      Byte temp1 [] = {
         0x02,   /* 02h is the opcode for ldarg.0 */
         0x03,   /* 03h is the opcode for ldarg.1 */
         0x58,   /* 58h is the opcode for add     */
         0x2A    /* 2Ah is the opcode for ret     */
      };
      Byte ILcodes [] = temp1;

      myMthdBldr->CreateMethodBody(ILcodes, ILcodes->Length);

      addType = myTypeBldr->CreateType();

      return addType;
   }
};

int main() {

   Type*  myType = MethodBodyDemo::BuildDynType();
   Console::WriteLine(S"---");
   Console::Write(S"Enter the first integer to add: ");
   int aVal = Convert::ToInt32(Console::ReadLine());

   Console::Write(S"Enter the second integer to add: ");
   int bVal = Convert::ToInt32(Console::ReadLine());

   Object* adderInst = Activator::CreateInstance(myType, new Object*[0]);

   Object* temp1 [] = {__box(aVal), __box(bVal)};
   Console::WriteLine(S"The value of adding {0} to {1} is: {2}.", __box(aVal), __box(bVal),
      myType->InvokeMember(S"DoAdd", BindingFlags::InvokeMethod, 0, adderInst, temp1));
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

See Also

MethodBuilder Class | MethodBuilder Members | System.Reflection.Emit Namespace

Show:
© 2014 Microsoft