In my current programming project, I’ve embedded IronPython in a C# program. I thought I would share the basics of embedding a scripting engine. I imagine the process would be the same for any language that uses the DLR (Dynamic Language Runtime), like IronRuby. Here is a sample using IronPython 2.0 Beta 5.
using System;using IronPython.Hosting;using Microsoft.Scripting;using Microsoft.Scripting.Hosting;public class Program
{ // Delegate matching the signature of the factorial functiondelegate int FactorialDelegate(int n);
static void Main(string[] args)
{ // Our factorial functionstring[] lines = {"def factorial(n):",
" for i in range(1, n):", " n = n * i", " return n"};string code = String.Join("\r", lines);
// Instantiate the IronPython environmentScriptEngine engine = Python.CreateEngine();
// Create a scope/module to work inScriptScope scope = engine.CreateScope();
// A little preparationScriptSource source = engine.CreateScriptSourceFromString(code, SourceCodeKind.Statements);
// Compile the codeCompiledCode compiled = source.Compile();
// Execute the code in the scopecompiled.Execute(scope);
//Now the factorial function exists in the IronPython environment. Let's use it. // Set x = 5 scope.SetVariable("x", 5); // print factorial(x) ScriptSource print = engine.CreateScriptSourceFromString("print factorial(x)", SourceCodeKind.SingleStatement); print.Execute(scope); //outputs 120 // Get the result from IronPythonint result1 = scope.Execute<int>("factorial(6)");
Console.WriteLine(result1); //outputs 720 // We can also call the function directly from C# FactorialDelegate factorial = scope.GetVariable<FactorialDelegate>("factorial"); int result2 = factorial(7); Console.WriteLine(result2); //outputs 5040Console.Read();
}
}