利用DynamicILInfo類動態產生方法

來源:互聯網
上載者:User

標籤:style   blog   http   ar   io   color   os   使用   sp   

  ILGenerator與DynamicILInfo類是不同的。它直接使用位元組數組設定IL代碼,異常和本地的簽名。那麼,我們怎樣才能獲得這些位元組數組從ILGenerator 與DynamicILInfo類是不同的。它直接使用位元組數組設定IL代碼,異常和本地的簽名。那麼,我們怎樣才能獲得這些位元組數組,請看下面的代碼:

     

using System;using System.Reflection;using System.Reflection.Emit;class Demo{    static void Main()    {        DynamicMethod dm = new DynamicMethod("HelloWorld", typeof(void), Type.EmptyTypes, typeof(Demo), false);        DynamicILInfo il = dm.GetDynamicILInfo();        SignatureHelper sigHelper = SignatureHelper.GetLocalVarSigHelper();        il.SetLocalSignature(sigHelper.GetSignature());        byte[] code = { 0x00, 0x72, 0x01, 0x00, 0x00, 0x70, 0x28, 0x04, 0x00, 0x00, 0x0a, 0x00, 0x2a };        int token0 = il.GetTokenFor("Hello world");        int token1 = il.GetTokenFor(typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }).MethodHandle);        PutInteger4(token0, 0x0002, code);        PutInteger4(token1, 0x0007, code);        il.SetCode(code, 8);        dm.Invoke(null, null);
   Console.Read(); }
static void PutInteger4(int value, int startPos, byte[] array) { array[startPos++] = (byte)value; array[startPos++] = (byte)(value >> 8); array[startPos++] = (byte)(value >> 16); array[startPos++] = (byte)(value >> 24); }}

以下是Microsoft enginee 的解釋:

If the dynamic method we are going to create is based on a static method in some existing assembly, we can view the IL code (bytes) of the static method via ildasm or by using MethodBody.GetILByteArray. We can then build the byte array for SetCode from there. For all tokens used in the original static method, be sure to replace them (bold, as shown above and below in this example) with those generated from GetTokenFor. 

.method public hidebysig static void HelloWorld() cil managed
// SIG: 00 00 01
{
  // Method begins at RVA 0x2050
  // Code size 13 (0xd)
  .maxstack 8
  IL_0000: /* 00 |             */ nop
  IL_0001: /* 72 | (70)000001 */ ldstr "Hello world"
  IL_0006: /* 28 | (0A)000004 */ call void [mscorlib]System.Console::WriteLine(string)
  IL_000b: /* 00 |             */ nop
  IL_000c: /* 2A |             */ ret
}

To build the byte array for SetException, I‘d suggest taking a couple of minutes to read ECMA spec partiton II (25.4.6) first. The Flags/TryOffset/TryLength/HandlerOffset/HandlerLength ... can be retrieved from MethodBody.ExceptionHandlingClauses programatically. Be aware the exception type token (ClassToken) has to be obtained from GetTokenFor as well. Do you know Ildasm can show the raw exception information? I did not know this until I learned about it recently from Peli.:) Uncheck View->Expand try/catch and check show bytes; we will see something like the following at the bottom of the method IL:

  // Exception count 1
  .try IL_002e to IL_0051 finally handler IL_0051 to IL_0065
  // HEX: 02 00 00 00 2E 00 00 00 23 00 00 00 51 00 00 00 14 00 00 00 00 00 00 00
}

Class SignatureHelper offers a convenient way to construct the local variable signature, if each local variable type is known. We can just make calls of SignatureHelper.AddArgument.

Are there any scenarios in your mind where using DynamicILInfo could be better than using DynamicILGenerator? How‘d you like to construct those byte arrays? I am thinking about writing and sharing a tool, which, based on an existing method, generates C# code to define the equivalent dynamic method (using DynamicILInfo) (if this turns out to be a popular scenario).

利用DynamicILInfo類動態產生方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.