2013-01-03 70 views
5

到目前爲止,我有一個簡單的類,它包裝了一個python引擎(IronPython)供我使用。雖然代碼看起來很大,但它非常簡單,所以我在這裏複製它以更清楚地解決我的問題。在C#中使用IronPython運行特定的Python函數

下面的代碼:

public class PythonInstance 
{ 
    ScriptEngine engine; 
    ScriptScope scope; 
    ScriptSource source; 

    public PythonInstance() 
    { 
     engine = Python.CreateEngine(); 
     scope = engine.CreateScope(); 
    } 

    public void LoadCode(string code) 
    { 
     source = engine.CreateScriptSourceFromString(code, Microsoft.Scripting.SourceCodeKind.Statements); 
     source.Compile(); 
    } 

    public void SetVariable(string key, dynamic variable) 
    { 
     scope.SetVariable(key, variable); 
    } 

    public void RunCode() 
    { 
     source.Execute(scope); 
    } 

    public void CallFunction(string function) 
    { 
     //?????? no idea what to call here 
    } 

} 

所以,它的偉大工程,但只允許我在一次執行所有Python腳本...但我想這樣做是爲了能夠調用特定功能來自pythos腳本。

所以,我的問題:如何在加載的腳本中調用特定的函數?

我試圖找到一些信息或教程,但不幸找不到任何東西。

+1

你有沒有看着http://stackoverflow.com/questions/13231913/how-do-i-call-a-specific -method-from-a-python-script-in-c和http://stackoverflow.com/questions/7053172/how-can-i-call-ironpython-code-from-ac-sharp-app? –

+0

@Simon第一個是,第二個沒有。感謝您的鏈接,我現在會閱讀它。 – NewProger

回答

8

感謝評論中的建議,我能夠弄清楚如何使用它。這是我現在有:

public class PythonInstance 
{ 
    private ScriptEngine engine; 
    private ScriptScope scope; 
    private ScriptSource source; 
    private CompiledCode compiled; 
    private object pythonClass; 

    public PythonInstance(string code, string className = "PyClass") 
    { 
     //creating engine and stuff 
     engine = Python.CreateEngine(); 
     scope = engine.CreateScope(); 

     //loading and compiling code 
     source = engine.CreateScriptSourceFromString(code, Microsoft.Scripting.SourceCodeKind.Statements); 
     compiled = source.Compile(); 

     //now executing this code (the code should contain a class) 
     compiled.Execute(scope); 

     //now creating an object that could be used to access the stuff inside a python script 
     pythonClass = engine.Operations.Invoke(scope.GetVariable(className)); 
    } 

    public void SetVariable(string variable, dynamic value) 
    { 
     scope.SetVariable(variable, value); 
    } 

    public dynamic GetVariable(string variable) 
    { 
     return scope.GetVariable(variable); 
    } 

    public void CallMethod(string method, params dynamic[] arguments) 
    { 
     engine.Operations.InvokeMember(pythonClass, method, arguments); 
    } 

    public dynamic CallFunction(string method, params dynamic[] arguments) 
    { 
     return engine.Operations.InvokeMember(pythonClass, method, arguments); 
    } 

} 

爲了測試它:

 PythonInstance py = new PythonInstance(@" 
class PyClass: 
    def __init__(self): 
     pass 

    def somemethod(self): 
     print 'in some method' 

    def isodd(self, n): 
     return 1 == n % 2 
"); 
     py.CallMethod("somemethod"); 
     Console.WriteLine(py.CallFunction("isodd", 6)); 
相關問題