2011-05-12 3 views
8

IronPython을 C#으로 사용하려고하는데, 필자가 필요로하는 훌륭한 문서를 찾을 수없는 것 같습니다. 기본적으로 .py 파일에서 C# 프로그램으로 메서드를 호출하려고합니다. 내부가 방법에 접근하는 방법을 여기에서 확실하지 오전,IronPython을 C#으로 임베딩하기

var ipy = Python.CreateRuntime(); 
var test = ipy.UseFile("C:\\Users\\ktrg317\\Desktop\\Test.py"); 

그러나 :

나는 모듈을 열고 다음 있습니다. 내가 본 예제에서는 동적 키워드를 사용하지만, C# 3.0에서만 작동합니다.

감사합니다.

답변

9

Voidspace 사이트의 embedding을 참조하십시오.

예를 들어 The IronPython Calculator and the EvaluatorC# 프로그램에서 호출 된 간단한 파이썬 표현식 평가 기보다 작동합니다.

public string calculate(string input) 
{ 
    try 
    { 
     ScriptSource source = 
      engine.CreateScriptSourceFromString(input, 
       SourceCodeKind.Expression); 

     object result = source.Execute(scope); 
     return result.ToString(); 
    } 
    catch (Exception ex) 
    { 
     return "Error"; 
    } 
} 
6

다음과 같은 코드를 사용하여 시도 할 수

ScriptSource script; 
script = eng.CreateScriptSourceFromFile(path); 
CompiledCode code = script.Compile(); 
ScriptScope scope = engine.CreateScope(); 
code.Execute(scope); 

그것은 this 기사에서입니다.

또는 당신이 뭔가를 사용할 수있는 메소드를 호출하는 것을 선호하는 경우,

using (IronPython.Hosting.PythonEngine engine = new IronPython.Hosting.PythonEngine()) 
{ 
    engine.Execute(@" 
    def foo(a, b): 
    return a+b*2"); 

    // (1) Retrieve the function 
    IronPython.Runtime.Calls.ICallable foo = (IronPython.Runtime.Calls.ICallable)engine.Evaluate("foo"); 

    // (2) Apply function 
    object result = foo.Call(3, 25); 
} 

이 예는 here에서입니다.

관련 문제