Introduction
IronPython is a scripting language. It is am implementation of the python program language.Written in C#,it is tightly integrated with the .NET Framework.
This small article will demonstrate step by step as to how we can call IronPython 2.6 function from C#4.0 using the dynamic keyword
Using the code
Step 1: Download the latest version of Iron Python from Code Plex
Step 2: Install the software.
Step 3: For this demo we are using first.py python file located inside the Tutorial Folder
The file has two methods
a) Add
b) Factorial.
For this demo purpose, let us only invoke the Add method that performs addition of two numbers being supplied as parameters to the method.
Step 4: We are using a console application for the demo purpose. The very first thing we need to do is to add the dlls as shown under
Step 5: The function invocation happens in just three steps as shown below
class Program
{
static void Main(string[] args)
{
var ironPythonRuntime = Python.CreateRuntime();
try
{
dynamic loadIPython = ironPythonRuntime.UseFile("first.py");
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);
}
}
The very first line
var ironPythonRuntime = Python.CreateRuntime();
loads the Iron Python libraries along with the DLR code needed to execute the python script.
Second line
dynamic loadIPython = ironPythonRuntime.UseFile("first.py");
loads the python script into memory. The significance of the dynamic variable(loadIPython) here is being the fact that Python calls are resolve at runtime.
The last line i.e.
Console.WriteLine(
string.Format("Addition result from IronPython method for {0}
and {1} is {2}", 100,200,
loadIPython.add(100, 200)) );
Is simply to invoke the Python method and to display the result.
Step 6: And here is the output
References
Iron Python
Conclusion:
In this short tutorial we have seen how to invoke IronPython methods from C# 4.0.
Comments on the topic are highly appreciated for the improvement of the topic.
Thanks for reading the article.