在C#中嵌入IronPython

我只是在研究使用IronPython和C#,似乎无法找到任何我需要的优秀文档。 基本上我试图将.py文件中的方法调用到C#程序中。

我有以下打开模块:

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

但是,我不确定如何访问其中的方法。 我见过的例子使用了动态关键字,但是,在工作中我只使用C#3.0。

谢谢。

请参阅Voidspace网站上的嵌入 。

这里有一个例子, IronPython Calculator和Evaluator工作在一个简单的python表达式求值器上,该求值器来自C#程序。

 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"; } } 

您可以尝试使用以下代码,

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

这是来自这篇文章。

或者,如果你想调用一个方法,你可以使用这样的东西,

 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); } 

这个例子来自这里 。