Blogger :
MSDN Blogs
All posts :
All posts by MSDN Blogs
Category :
SAPscript
Blogged date : 2008 Jun 24
Let me start with a (fair) assumption. You reached here by clicking on a link in a search results page. So, you already have a basic idea of what the DLR is and that it can be hosted in managed applications. This post addresses getting you started assuming no prior knowledge of the API that would let you do this.
Here's a step by step guide to write a simple DLR host
- Currently, the DLR is available as part of IronPython. So you can download the latest DLR binaries and/or binaries from here. (You can also get it from the IronRuby project)
- Extract the contents of the zip file to disk. The default dir will be 'IronPython-2.0B3'
- Fire up VS and create a new C# Console application.
- In VS, choose Project-><project name> Properties... menu item to bring up project properties.
- Use the 'Output path' option to set the the project's output path to the folder where you unzipped the binaries in step (2).
- Make sure the folder you set in (5) is the one that has the unzipped binaries like ipy.exe, Microsoft.Scripting.Core.dll etc
- Add a reference to the Scripting dlls. Using Project->Add reference menu to bring up the references dialog.Now use the 'Browse' tag to locate 'Microsoft.Scripting.Dll' and 'Microsoft.Scripting.Core.dll' in the folder you created in step (2)
- Create a simple python file. My test python file has just the following line - print "hello simple dlr host"
- Paste the following code in the Program.cs file created in step (3)
using Microsoft.Scripting.Hosting;
namespace SimpleDLRHost {
class Program {
static void Main(string[] args) {
ScriptRuntime runtime = ScriptRuntime.Create();
runtime.ExecuteFile(@"D:\test.py");
}
}
}
- Compile and run
- You should see the output from the python script in the output console of this project
By now, I am sure you are thrilled about being able to write simple programs that can host a scripting language like IronPython. This sample is the most simplest DLR host you could write and so doesn't do anything meaningful. The focus of this post is on setting up the environment correctly to use the API ( the classes and methods that are part of the Microsoft.Scripting.Hosting namespace)
Using the Hosting API, You do some very powerful things with the DLR and scripting languages. For example, you can do things like
- Use other languages like IronRuby, Managed JScript etc...
- Define a method in python and invoke from C#
- Declare a variable in C# and access it from the script (and vice versa)
- Add user scripting support to your applications.
The Hosting API spec has some samples that demonstrate some of the above items. I would also be putting up some more examples along these lines shortly here.
Further Reading