2015-06-24 59 views
1

我需要升級從C#調用IronPython的代碼,並且想升級到IronPython 2.7.5。問題在於其中一個API已經發生了變化,並且我對原始代碼不夠熟悉,無法修復它。我寫了一個展示該問題的控制檯程序需要幫助將IronPython 2.0.2升級到2.7.5,從C#調用

我公司主營:

class Program 
{ 
    static void Main() 
    { 
     var pythonTest = new PythonTest(); 
     pythonTest.LoadScript(); 
     Console.WriteLine("Area = {0}", pythonTest.Evaluate()); 
    } 
} 

我的測試類:

public class PythonTest 
{ 
    private readonly ScriptEngine _engine; 
    private readonly ScriptScope _scope; 
    private ScriptSource _source; 
    private PythonFunction _currentFunction; 
    private readonly Dictionary<string, PythonFunction> _functions = new Dictionary<string, PythonFunction>(); 
    private readonly double _scriptInput; 

    public PythonTest() 
    { 
     _scriptInput = 5; 
     _engine = Python.CreateEngine(); 
     _scope = _engine.CreateScope(); 
    } 

    public void LoadScript() 
    { 
     const string filename = @"../../Scripts/testscript.py"; 
     _source = _engine.CreateScriptSourceFromFile(filename); 
     _source.Execute(_scope); 

     string firstFunction = ""; 
     foreach (KeyValuePair<string, object> pair in _scope.GetItems()) 
     { 
      var pairValue = pair.Value as PythonFunction; 
      if (pairValue != null) 
      { 
       _functions.Add(pair.Key, pairValue); 

       if (_functions.Count == 1) 
       { 
        firstFunction = _functions.Keys.First(); 
       } 
      } 
     } 
     _currentFunction = _functions[firstFunction]; 
    } 

    public string Evaluate() 
    { 
     if (_currentFunction == null) 
      return null; 

     var parameters = new ArrayList {_scriptInput}; 

     LanguageContext cxt = Microsoft.Scripting.Hosting.Providers.HostingHelpers.GetLanguageContext(_engine); 
     var context = new CodeContext(new Scope(), cxt); 
     object result = _currentFunction.__call__(context, parameters.ToArray()); 
     return result.ToString(); 
    } 
} 

我的測試腳本:

from math import * 
def AREA(h): 
    return (h * h) 

這所有的作品與舊的Python DLL。對於新的DLL,CodeContext的實例(在Evaluate方法中)是不正確的。新的API使用PythonDictionary:

 public CodeContext(PythonDictionary dict, ModuleContext moduleContext); 

我不知道如何修改代碼來解決這個問題。任何幫助,將不勝感激。

回答

0

您的LanguageContextPythonContext,因此可以投射。然後,您可以將其與PythonDictionary一起使用,以創建ModuleContext。然後你可以使用它和PythonDictionary一起創建你的CodeContext

PythonContext cxt = (PythonContext)Microsoft.Scripting.Hosting.Providers.HostingHelpers.GetLanguageContext(_engine); 
PythonDictionary dict = new PythonDictionary(); 
ModuleContext modctx = new ModuleContext(dict, cxt); 
var context = new CodeContext(dict, modctx); 
+1

看起來不錯。在我摸索的代碼中,我錯過了對PythonContext的轉換。當我明天回去工作時,我會對此進行測試。 !今晚睡得好! – spainchaud

+1

我剛完成測試並且此解決方案有效。謝謝。 – spainchaud