从 C# 4.0 调用 Iron Python 函数的分步指南






2.28/5 (15投票s)
一个简短的演示,展示如何调用用 IronPython 2.6 编写的方法,并从 C# 环境动态调用该方法。
引言
IronPython 是一种脚本语言。它是 Python 编程语言的一种实现。用 C# 编写,它与 .NET Framework 紧密集成。
本文将逐步演示如何使用 dynamic 关键字从 C#4.0 调用 IronPython 2.6 函数。
使用代码
步骤 1:从 Code Plex 下载最新版本的 Iron Python
步骤 2:安装软件。
步骤 3:对于此演示,我们使用位于 Tutorial 文件夹内的 first.py Python 文件
该文件包含两种方法
a) 加法
b) 阶乘。
为了演示目的,我们只调用 Add 方法,该方法执行将作为参数传递给该方法的两个数的加法运算。
步骤 4:我们使用控制台应用程序进行演示。我们需要做的第一件事是添加如下所示的 dll
步骤 5: 函数调用只需三个步骤即可完成,如下所示
class Program { static void Main(string[] args) { //Step 1: //Creating a new script runtime var ironPythonRuntime = Python.CreateRuntime(); try { //Step 2: //Load the Iron Python file/script into the memory //Should be resolve at runtime dynamic loadIPython = ironPythonRuntime.UseFile("first.py"); //Step 3: //Invoke the method and print the result Console.WriteLine( string.Format("Addition result from IronPython method for {0} and {1} is {2}", 100,200, loadIPython.add(100, 200)) ); } catch (FileNotFoundException ex) { Console.WriteLine(ex.Message); } Console.ReadKey(true); } }
第一行
var ironPythonRuntime = Python.CreateRuntime();
加载 Iron Python 库以及执行 Python 脚本所需的 DLR 代码。
第二行
dynamic loadIPython = ironPythonRuntime.UseFile("first.py");
将 Python 脚本加载到内存中。dynamic 变量 (loadIPython) 的重要性在于 Python 调用在运行时解析。
最后一行,即
Console.WriteLine( string.Format("Addition result from IronPython method for {0} and {1} is {2}", 100,200, loadIPython.add(100, 200)) );
只是为了调用 Python 方法并显示结果。
步骤 6:这是输出
参考文献
Iron Python结论
在本简短教程中,我们了解了如何从 C# 4.0 调用 IronPython 方法。
非常感谢您对该主题的评论,以便改进该主题。
感谢阅读本文。