2010-04-06 4 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 (string format, object [] args)와 같은 메소드를 공개하고 싶다면.

현재 "myprintcommand"키는 하나의 대리자로 매핑 될 수 있습니다. 따라서 오버로드 된 "myprint 명령"을 인터프리터에 표시하려면 명령/메서드의 이름을 변경해야합니다. 내가 원하는 것을 성취 할 수있는 다른 방법이 있습니까?

답변

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

더 쉬운 방법이 있습니다. 스크립트 범위를 사용하여 IronPython에 액세스 할 수 있도록하는 대신 C# 어셈블리를 엔진 런타임에로드 할 수 있습니다.

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

이렇게하면 클래스 MyClass을 포함하는 어셈블리를 미리로드합니다. 예를 들어, MyPrintMethod이 정적 멤버 MyClass이라고 가정하면 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) 
관련 문제