IronPython 與C#互動

來源:互聯網
上載者:User

一、介紹

Python是一種物件導向、直譯式電腦程式設計語言,也是一種功能強大而完善的通用型語言,已經具有十多年的發展曆史,成熟且穩定。這種語言具有非常簡捷而清晰的文法特點,適合完成各種高層任務,幾乎可以在所有的作業系統中運行。目前,基於這種語言的相關技術正在飛速的發展,使用者數量急劇擴大,相關的資源非常多。 IronPython是由Jim Hugunin在微軟領導開發的一個.NET平台上的Python實現,包括了完整的編譯器、執行引擎與運行時支援,能夠與.NET已有的庫無縫整合到一起。微軟對於.NET framework的IronPython和動態語言非常關注,已經在各種項目中提供了對IronPython的支援。IronPython已經很好的整合到了.NET framework中,Python語言中的字串對應於.NET的字串對象,並且Python語言中對應的方法,在IronPython中也都提供了。其它資料類型也是一樣。

作者

參考:

瞭解DLR: http://rednaxelafx.javaeye.com/blog/241430 

jim的部落格:http://blogs.msdn.com/hugunin/default.aspx

http://developer.51cto.com/art/200910/156377.htm

http://www.msuniversity.edu.cn/m_LearnCenterInfo/Detail.aspx?id=102

 二、基礎知識

1、安裝

因為我目前使用的是vs2008所以到http://ironpython.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=12482下載2.6正式版,我下的是IronPython-2.6.msi ,直接安裝就行了。預設的安裝路徑應該是C:\Program Files\IronPython 2.6

2、引入相應的dll

建立一個控制台應用程式,然後到C:\Program Files\IronPython 2.6中引用IronPython.dll,Microsoft.Scripting.Core.dll,Microsoft.Scripting.dll三個dll。

3、應用

C:\Program Files\IronPython 2.6\Tutorial\Tutorial.htm是IronPython的應用指導,寫的很仔細。ipy.exe是IronPython 的運行控制台,如果你想學習IronPython 的文法可以使用這個工具。IronPython 的文法這裡就不詳細介紹了,如果想進一步學習,可以下載IronPython in Action。

三、IronPython 與C#互動

1、C#使用IronPython 代碼

我們希望在C#中直接運行IronPython 中的代碼,比方說1+2的結果值

 

代碼

ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
var strExpression = "1+2";
var sourceCode = engine.CreateScriptSourceFromString(strExpression);
var actual = sourceCode.Execute<int>();
Console.WriteLine(actual);

 

 

 執行結果:

3

ScriptEngine和ScriptScope是在.net中使用IronPython 指令碼的兩個基礎類,ScriptSource是運行IronPython 的基礎類,這裡邊sourceCode就是一個ScriptSource。

有時我們希望給IronPython 代碼中傳入一個變數值

 

代碼

ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
var strExpression = "\"Hello:\" + str";
var sourceCode = engine.CreateScriptSourceFromString(strExpression);
scope.SetVariable("str", "Python");
var actual = sourceCode.Execute<string>(scope);
scope.RemoveVariable("str");
Console.WriteLine(actual);

 

執行結果:

Hello:Python

2、C#調用IronPython 函數

調用IronPython 中的MyFunction函數

 

代碼

var strExpression = @"
def MyFunction(n):
    return 2*n 
                ";
            var sourceCode = engine.CreateScriptSourceFromString(strExpression).Compile().Execute(scope);

            var func = engine.GetVariable<Func<int, int>>(scope, "MyFunction");

            Console.WriteLine(func(3));

 

這裡需要注意def MyFunction(n):前不能有空格,return 2*n 必須有空格

 3、IronPython 調用C#函數

在IronPython 中調用C#中已經存在的函數

 

 

代碼

static void Main(string[] args)
        {
            ScriptEngine engine = Python.CreateEngine();
            ScriptScope scope = engine.CreateScope();
            var strExpression = "CMethod('Python')";
            var sourceCode = engine.CreateScriptSourceFromString(strExpression);
            scope.SetVariable("CMethod", (Func<string, string>)TMethod);
            var actual = sourceCode.Execute<string>(scope);
            scope.RemoveVariable("CMethod");
            Console.WriteLine(actual);
        }
        public static string TMethod(string info)
        {
            return "Hello:" + info;
        }

 

 如果需要使用某個對象中的某個函數

 

代碼

 Test test = new Test();
            var strExpression = @"
test.Hello()
";
            var sourceCode = engine.CreateScriptSourceFromString(strExpression);
            scope.SetVariable("test", test);
            var actual = sourceCode.Execute<string>(scope);
            Console.WriteLine(actual);

 

  

如果需要在IronPython 執行個體化使用某個對象,就稍微複雜點,這裡我們建立了一個IronPythonTest程式集,我們希望在IronPython代碼中使用IronPythonTest程式集中的Test類,代碼如下:

 

代碼

var strExpression = @"
import clr, sys
clr.AddReference('IronPythonTest')
from IronPythonTest import *
test=Test()
test.Hello()
            ";
            var sourceCode = engine.CreateScriptSourceFromString(strExpression);
            var actual = sourceCode.Execute<string>(scope);
            Console.WriteLine(actual);

 

Test代碼:

namespace IronPythonTest
{
    public class Test
    {
        public string Hello()
        {
            return "Hello World";
        }
    }
}

  

clr.AddReference('IronPythonTest')是用來添加程式集的

from IronPythonTest import *是用來添加命名空間的

參考:

http://www.236z.com/html/30/6/9/2009/11/10/67471.html

IronPython和C#執行速度對比

 

 

相關文章

聯繫我們

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