2009-06-04

IronPython and C#, Hosting/Embedding, Part I

As IronPython improves, the way to embed it in other applications is changed too. It is constantly becoming easier and more general. When the C# 4.0 is released, it will be even more easier and useful.

I have written a simple hosting example for the current stable version. I have used IronPython 2.0.1, Visual Studio 2005 SP1, and .NET Framework 2.0 SP2. This example has not been tested with IronPython 2.6 Beta 1 nor IronPython 2.6 for .NET 4.0 Beta 1.

The example code can be seen as follows:

1  namespace IronPythonHostingExample
2  {
3      using System;
4      using IronPython.Hosting;
5      using Microsoft.Scripting.Hosting;
6
7      public class IronPythonStatementHostingExample
8      {
9          public static void ShowDemo()
10         {
11             ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(null);
12             ScriptRuntime runtime = new ScriptRuntime(setup);
13             ScriptEngine engine = Python.GetEngine(runtime);
14             ScriptScope scope = engine.CreateScope();
15             ScriptSource source;
16             string sourceCode = string.Empty;
17             sourceCode += "def factorial(n):" + Environment.NewLine;
18             sourceCode += "    f = 1" + Environment.NewLine;
19             sourceCode += "    i = 1" + Environment.NewLine;
20             sourceCode += "    if (i > n):" + Environment.NewLine;
21             sourceCode += "        return -1" + Environment.NewLine;
22             sourceCode += "    while (i < n):" + Environment.NewLine;
23             sourceCode += "        f = f * i" + Environment.NewLine;
24             sourceCode += "        i = i + 1" + Environment.NewLine;
25             sourceCode += "    return f" + Environment.NewLine;
26             sourceCode += "def add_two_numbers(n1, n2):" + Environment.NewLine;
27             sourceCode += "    return n1+n2" + Environment.NewLine;
28             sourceCode += "for i in range(5):" + Environment.NewLine;
29             sourceCode += "    print i" + Environment.NewLine;
30             sourceCode += "print factorial(5)" + Environment.NewLine;
31             sourceCode += "print factorial(-4)" + Environment.NewLine;
32             sourceCode += "print add_two_numbers(1, 2)" + Environment.NewLine;
33             source = scope.Engine.CreateScriptSourceFromString(sourceCode, Microsoft.Scripting.SourceCodeKind.Statements);
34             source.Execute(scope);
35         }
36     }
37 }



To compile it as a project, you need the following DLLs to be added to your project:
The DLL files can be found in the directory
"C:\Program Files\IronPython 2.0.1".

2 comments: