CIL的作用簡介

來源:互聯網
上載者:User

CIL是一種和平台無關的語言。不管使用任何支援.NET的語言,相關編譯器都產生CIL指令。例如下面的C#代碼構成一個簡單的計算機

//*.cs

using System;
namespace CilExample
{
    //應用程式入口
    public class CilApp
    {
        static void Main()
        {
            Calc calc = new Calc();
            int result = calc.Add(10,84);
            Console.WriteLine("10+84={0}",result);

            //按斷行符號結束程式
            Console.ReadLine();
        }
    }

    //C#計算機
    public class Calc
    {
        public int Add(int x, int y)
        {
            return x + y;
        }
    }
}
一旦編譯器(csc.exe)編譯這段代碼,就會得到一個單檔案*.exe程式集。這個程式集中包含一個資訊清單、CIL指令和描述Calc
與CilApp類的各方面資料。例如如果用ildasm.exe開啟該程式集,會發現Add()方法被CIL表示為:

.method public hidebysig instance int32 Add(int32 x,int32 y) cil managed
{
   
.maxstack 2
.locals int ([0] int32 cs$1$0000)
IL_0000:ldarg.1
IL_0001:ldarg.2
IL_0002:add
IL_0003:stloc:0
IL_0004:br.s   IL_0006
IL_0006:ldarg.0
IL_0007:ret
}

現在用VB.NET建立和上面一樣的程式
//*.vb
Imports System

Namespace CilExample
    Module CilApp
        Sub Main()
            Dim c As New Calc
            result = c.Add(10, 84)
            Console.WriteLine("10+84={0}", result)
            Console.ReadLine()
        End Sub
    End Module

    Class Calc
        Public Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
            Return x + y
        End Function
    End Class

End Namespace

 

如果查看他的CIL代碼你會發現非常相似,只有很少的差別

.method public hidebysig instance int32 Add(int32 x,int32 y) cil managed
{
   
.maxstack 2
.locals int ([0] int32 Add)
IL_0000:nop
IL_0001:ldarg.1
IL_0002:ldarg.2
IL_0003:add.ovf
IL_0004:stloc.0  
IL_0005:br.s     IL_0007
IL_0007:ldarg.0
IL_0008:ret
}

從這就可以看出CIL很明顯的好處:語言的整合性
每種支援.NET的編譯器產生的是幾乎完全相同的CIL指令,因此,所有語言都能很好的定義明確的二進位檔案相互互動
此外CIL是平台無關的。
暫時到這,後面會更加詳細的介紹CIL

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.