I’ve come across a rather interesting feature of IronPython and the DLR (forgive me if this is old news :P ) which I never previously knew about and would make an interesting addition to my planned Facebook XMPP client; the ability to execute embedded IronPython from any .NET language (even IronPython itself).

using System;
using System.Collections.Generic;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

namespace ConsoleApplication3
{
	class Program
	{
		static void Main(string[] args)
		{
			Dictionary<int, int> bar = new Dictionary<int, int>();

			ScriptEngine engine = Python.CreateEngine();
			ScriptScope scope = engine.CreateScope();
			scope.SetVariable("bar", bar);

			string script = @"

from System import Console

foo = 'Hello from IronPython!'
Console.Title = foo

for i in range(0, 10):
	bar.Add(i, i**2)";

			engine.Execute(script, scope);
			Console.WriteLine(scope.GetVariable("foo"));

			foreach (KeyValuePair<int, int> kvp in bar)
			{
				Console.WriteLine("{0}^2 = {1}", kvp.Key, kvp.Value);
			}

			Console.ReadKey();
		}
	}
}

This is a great way to allow custom user defined scripts to alter a program without changing the actual code base. The embedded Python has complete access to the .NET library, likewise the calling C# has complete access to the embedded script.

I can’t see much practical use for this in a chat client, but I’m working on it :P

Leave a Reply

You must be logged in to post a comment.