技术开发 频道

初试IronPython与.NET的集成

    PyFacade的代码如下。
using System; using System.Collections.Generic; using IronPython.Hosting; namespace Cavingdeep.Python { public class PyFacade<T> { public const string ResultVariableName = "_result_"; private PythonEngine engine = new PythonEngine(); private string pythonFile; private Result<T> result = new Result<T>(); private IDictionary<string,object> args = new Dictionary<string,object>(); public string PythonFile { get {return this.pythonFile;} set {this.pythonFile = value;} } public T Result { get {return this.result.Value;} } public IDictionary<string,object> Arguments { get {return this.args;} } public void Execute() { engine.Globals[ResultVariableName] = this.result; foreach (KeyValuePair<string,object> arg in this.args) { engine.Globals[arg.Key] = arg.Value; } engine.ExecuteFile(this.pythonFile); } } }
    Result的代码如下。
using System; namespace Cavingdeep.Python { public class Result<T> { public T Value; } }
    mayorThenTen.py的代码如下,这是这个示例中用到的IronPython文件。
def mayorThenTen(a, b): return [(x, y) for x in a for y in b if x + y > 5] if globals().has_key('_result_'): _result_.Value = mayorThenTen(listA, listB)
    这里的这个PyFacade是个比较通用的与IronPython交互的接口类,在真正的应用中建议用强类型模式(强类型设计实践)加以封装以得到type safety等好处。

    关于PyFacade是如何与IronPython文件交互一题,简单地说就是通过那个_result_变量,它会在IronPython文件中被赋值,这个值是外界可见的,也就是说IronPython文件的执行与当前程序是在一个AppDomain中的。有关这类知识感兴趣的读者可以去研究一下动态编译、加载与程序域(AppDomain)等知识。
0
相关文章