如何将重载方法暴露给嵌入式IronPython解释器?

时间:2010-04-06 10:57:09

标签: c# ironpython

我在C#应用程序中嵌入了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(string format,object [] args)这样的方法。

按照我目前的方式,键“myprintcommand”只能映射到一个委托。因此,如果我想将重载的“myprintcommand”暴露给解释器,我将不得不更改命令/方法的名称。有没有其他方法可以达到我的目的?

2 个答案:

答案 0 :(得分: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 :(得分: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)