2010-04-06 29 views
2

我在C#應用程序中嵌入了一個IronPython引擎。我想向解釋器公開一些自定義命令(方法)。我該怎麼做呢?如何將重載方法暴露給嵌入式IronPython解釋器?

目前,我有這樣的事情:

public delegate void MyMethodDel(string printText); 

Main(string[] args) 
{ 
    ScriptEngine engine = Python.CreateEngine(); 
    ScriptScope scope = engine.CreateScope(); 

    MyMethodDel del = new MyMethodDel(MyPrintMethod); 
    scope.SetVariable("myprintcommand", del); 

    while(true) 
    { 
     Console.Write(">>>"); 
     string line = Console.ReadLine(); 

     ScriptSource script = engine.CreateScriptSourceFromString(line, SourceCodeKind.SingleStatement); 
     CompiledCode code = script.Compile(); 
     script.Execute(scope); 
    } 
} 

void MyPrintMethod(string text) 
{ 
    Console.WriteLine(text); 
} 

我可以用這個像這樣:

>>>myprintcommand("Hello World!") 
Hello World! 
>>> 

這工作得很好。我想知道,如果這是做我想達到的正確方式/最佳做法?

我該如何暴露相同方法的重載。例如,如果我想公開像myprintcommand(字符串格式,object [] args)的方法。

通過我目前的做法,關鍵字「myprintcommand」只能映射到一個代表。因此,如果我想將重載的「myprintcommand」公開給解釋器,我將不得不更改命令/方法的名稱。有沒有其他的方式來實現我想要的?

回答

2

您可能必須爲此編寫自己的邏輯。例如:

public delegate void MyMethodDel(params object[] args); 

void MyPrintMethod(params object[] args) 
{ 
    switch (args.Length) 
    { 
    case 1: 
     Console.WriteLine((string)args[0]); 
     break; 
    ... 
    default: 
     throw new InvalidArgumentCountException(); 
    } 
} 

這可能會也可能不會;我不知道他們是如何處理'params'屬性的。

1

有一個更簡單的方法來做到這一點。您可以將C#程序集加載到引擎運行時,而不是使用腳本作用域使成員可以訪問IronPython。

engine.Runtime.LoadAssembly(typeof(MyClass).Assembly); 

這將預加載包含類MyClass的程序集。例如,假設MyPrintMethodMyClass的靜態成員,那麼您可以從IronPython解釋器進行以下調用。

from MyNamespace import MyClass 
MyClass.MyPrintMethod('some text to print') 
MyClass.MyPrintMethod('some text to print to overloaded method which takes a bool flag', True)