Csharp/C#教程:在C#中嵌入IronPython分享


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

这个例子来自这里 。

上述就是C#学习教程:在C#中嵌入IronPython分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1020721.html

(0)
上一篇 2022年1月5日
下一篇 2022年1月5日

精彩推荐