Skip to main content
GameDev.net gamedev.net
🔒 Locked

[.net] Easy Scripting in .NET

Started by Shinkage Aug 16, 2004 at 3:04 PM 72 replies 57.1k views
Original Post
Shinkage
Shinkage
For all those who haven't experimented with it, the Microsoft.CSharp namespace in the .NET BCL provides access to a fully functioning C# compiler. Using this it only takes a few simple steps to add powerful scripting support to any project. For those interested, I'll demonstrate the simplest way to get such a system up and running with only a few lines of code. First we'll want access to the namespaces where all this functionality resides.

using Microsoft.CSharp;
using System.CodeDom;
using System.CodeDom.Compiler;
Next up we need to create the objects that will actually do the work of compiling our scripts for us.

CSharpCodeProvider	codeProvider = new CSharpCodeProvider();
ICodeCompiler		codeCompiler = codeProvider->CreateCompiler();
With that ready, the compilation parameters need to be set up so the compile knows exactly what we want made. Most of these options are pretty straightforward and obvious. Pay close attention to the ReferencedAssemblies property of the compiler parameters however. This is where we tell the compiler which assemblies we want our script to have access to. For example, if the script is going to be doing any works with forms, it'll need to reference "System.Windows.Forms.dll."

CompilerParameters	params = new CompilerParameters();
params.GenerateExecutable = false;
params.GenerateInMemory = true;
params.IncludeDebugInformation = false;
params.TreatWarningsAsErrors = false;
params.ReferencedAssemblies.Add( "System.dll" );
params.ReferencedAssemblies.Add( "System.Windows.Forms.dll" );
CompilerResults		results = codeCompiler.CompileAssemblyFromFile( params, "MyScript.cs" );
At this point if the compiler met with any errors they can be found in the results.Errors member. Otherwise, we now have a new assembly loaded into memory and ready for use. Using the System.Reflection namespace, any types or methods declared in the source file can be discovered and used. Let's assume that the source file looks like the following:

// MyScript.cs

using System;
using System.Windows.Forms;

class Script
{
	public static void Main()
	{
		MessageBox.Show( "This is a script!" );
	}
}
Given that source after compilation by the preceding steps, the following will be sufficient to call the static Main method.

results.CompiledAssembly.GetType( "Script").GetMethod( "Main" ).Invoke( null, null );
Of course that only covers the basics, but there you have it.
Washu
Washu
An excellent example.

For those who are going to implement such a setup however, I would sugest using another AppDomain and giving it restricted security settings, so that it's harder for malicious scripts to be used.
In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.
strahan
strahan
I heard that managed DirectX also supports scripting.

Which would be better to use for a game?

Thanks.
VizOne
VizOne
The managed DX scripting example uses exactly this technique.


Here a code snippet how to setup a "sandbox"-AppDomain
public class ScriptRunner : MarshalByRefObject // make class remotable{	ICodeCompiler      compiler;	CompilerParameters param;	public static ScriptRunner CreateInSeparateDomain()	{		AppDomain dom = AppDomain.CreateDomain( "sandbox" );		return dom.CreateInstanceAndUnwrap( typeof( ScriptRunner ).Assembly.GetName().Name,			typeof( ScriptRunner ).FullName ) as ScriptRunner;	}	public ScriptRunner()	{		string parameters = "";		// C# compiler		compiler = new CSharpCodeProvider().CreateCompiler();		// parameters = "/debug+"; // uncomment for debugging		// uncomment for JScript.NET		//compiler = new JScriptCodeProvider().CreateCompiler();		//parameters ="/debug+ /versionsafe+ ";		param = new CompilerParameters();		param.CompilerOptions = parameters;		param.GenerateExecutable = false;		param.GenerateInMemory = true;		param.IncludeDebugInformation = true;		param.ReferencedAssemblies.Add( "Scripting.dll" ); // whatever you need here		// set policy		PolicyLevel level = PolicyLevel.CreateAppDomainLevel();		PermissionSet permissions = new PermissionSet( PermissionState.None );		// uncomment all permissions you need		// (never allow "Assertion"...)		// which flags are required minimally also depends		// on .NET runtime Version		SecurityPermissionFlag permissionFlags =	//                SecurityPermissionFlag.Assertion |	//                SecurityPermissionFlag.BindingRedirects |	//                SecurityPermissionFlag.ControlAppDomain |	//                SecurityPermissionFlag.ControlDomainPolicy |	//                SecurityPermissionFlag.ControlEvidence |	//                SecurityPermissionFlag.ControlPolicy |	//                SecurityPermissionFlag.ControlThread |	//                SecurityPermissionFlag.ControlPrincipal |	//                SecurityPermissionFlag.Infrastructure |	//                SecurityPermissionFlag.RemotingConfiguration |	//                SecurityPermissionFlag.SerializationFormatter |	//                SecurityPermissionFlag.Infrastructure |			SecurityPermissionFlag.SkipVerification |			SecurityPermissionFlag.UnmanagedCode|			SecurityPermissionFlag.Execution;		permissions.AddPermission( new SecurityPermission( permissionFlags ) );		// allow reflection		permissions.AddPermission( new ReflectionPermission( ReflectionPermissionFlag.AllFlags ) );		PolicyStatement policy = new PolicyStatement( permissions, PolicyStatementAttribute.Exclusive );		CodeGroup group = new UnionCodeGroup( new AllMembershipCondition(), policy );		level.RootCodeGroup = group;		AppDomain.CurrentDomain.SetAppDomainPolicy( level );	}    }    // add code for compiling and running scripts}


Regards
Andre
evolutional
evolutional
Very cool post. I've been wanting to look into C# scripting for a while but didn't know where to start. Rating++ for you, sir.
VizOne
VizOne
A note: it is important to create the compiler in the sandbox domain. Else the assembly created would automatically bleed into the main domain. This also means that you must set the permissions AFTER the compiler was created, as the compiler requires some special permissions.

Regards,
Andre
machine_gun_man
machine_gun_man
this is interesting...

I'm just wondering tho...

how might you use this within an html browser?

<html><head><title>c#</title></head><body><script language="c#">// MyScript.csusing System;using System.Windows.Forms;class Script{	public static void Main()	{		MessageBox.Show( "This is a script!" );	}}</script></body></html>


or

<html><head><title>c#</title></head><body><script language="c#" src="MyScript.cs"></script></body></html>


I find this cool as a matter of fact...
I might like to create an enhanced version of vbscript using visual basic .net that easily implements directx coponents.

of course you could achieve directx by using com in a script refering to directAnimation, but that part of directx is dead and why use the simple scripting languages when you can be proud of making your own? Who doesn't want to feel accomplished?
machine_gun_man
machine_gun_man
wait a sec...

your not talking a bout the scripting I was thinking of...

dang... that c# code is not meant for the "script" box I guess...

you could of course go make .net apps by means of asp pages, but it adds some overhead if youre trying to create one from scratch

ie: without visual studio.net

any possible way to have c# go into the script tag with simplicity... aka the standard html+script approach.

thanx...
Influenza
Influenza
C# scripts in web pages are parsed by the web server and execute through ASP.NET before the web page data is sent to the user. They don't act the same as &#106avascript blocks, which are interpreted and run on the user's web client. So no, you can't use C# inside a web page without using ASP.NET.<br/><br/>This is a very good introductory walktrough. I'd read about the CSharp namespace, but never looked into using it. I'd better look again!
Etnu
Etnu
Yeah, the sample that comes with the DX9c SDK shows how to use C# scripts within native C++ code by using an intermediate managed C++ layer. It works amazingly well.
---------------------------Hello, and Welcome to some arbitrary temporal location in the space-time continuum.
JesseT
JesseT
Quote:
Original post by deathtrap
So... exactly what are the uses of this? All i see is that you're compiling source code inside your source code.


LOL
Saruman
Saruman
Quote:
Original post by deathtrap
So... exactly what are the uses of this? All i see is that you're compiling source code inside your source code.


ROFLMAO! :)
Nypyren
Nypyren
It's good to note that you can use a string in memory rather than a file on disk for your compile source.

FWIW - I'm using this type of scripting in a binary file editor. I allow the "scripts" to use the public classes/members of my own editor .exe by adding my .exe itself to the reference list.

I use the scripts mainly for loading/saving different file formats, but I'm thinking about letting them do some more advanced stuff adding on to the user interface.
dug
dug
Here is how to dynamically compile a boo script ( http://boo.codehaus.org/ ), you can sandbox the resulting assembly before running it too if need be.

// (compile with references to Boo.dll and Boo.Lang.Compiler.dll)using System;using System.IO;using System.Threading;using System.Reflection;using Boo.Lang.Compiler;using Boo.Lang.Compiler.IO;using Boo.Lang.Compiler.Pipelines;namespace BooRunner{    class App    {        [STAThread]        static int Main(string[] args)        {            string booscript = "print \"hello\"";                       return RunScript(booscript);        }               static int RunScript(string script)        {            BooCompiler compiler = new BooCompiler();            compiler.Parameters.Input.Add(new StringInput("<stdin>", script));            //or to run files:            //compiler.Parameters.Input.Add(new FileInput(Path.GetFullPath(filepath)));                       compiler.Parameters.Pipeline = new CompileToMemory();            //or to compile to a dll:            //compiler.Parameters.Pipeline = new CompileToFile();            //compiler.Parameters.OutputAssembly = "Script.dll";                       CompilerContext result = compiler.Run();                       if (result.Errors.Count > 0)            {                foreach (CompilerError error in result.Errors)                {                    Console.WriteLine(error.ToString(true));                }                return -1;            }            try            {                result.GeneratedAssemblyEntryPoint.Invoke(null, new object[1]);            }            catch (TargetInvocationException x)            {                Console.WriteLine(x.InnerException.ToString());                return -1;            }            return 0;                   }    }}
posti
posti
You can also embed mono in your project and use C# scripting via mono. Making your code little more platform independant.

http://www.mono-project.com/Embedding_Mono
http://www.go-mono.com/embedded-api.html

Probably possible to run mono on game consoles too. So if you plan on porting your game to consoles or other os than windows you should use it.
Rob Loach
Rob Loach
Washu wrote up an excellent article on Code Access Permissions which I suggest you should most definately read.

Also, a nice tutorial was just recently published here on Gamedev: Using Lua with C#. It goes over using the LuaInterface in .NET. Lua should be mentioned as it's been in the game industry for years.

I'd also like to make a self plug of my GakScript Scripting Engine which nicely wraps the CodeDom and adds multiple language plugin interfaces. Very easy to use and comes with a few simple examples of its use.

[Edited by - Rob Loach on June 4, 2006 5:11:48 PM]
Rob Loach [Website] [Projects] [
gwihlidal
gwihlidal
My book shows how to use the CodeDom compiler to automate an MVC object model; essentially allowing the ability to write scripts that automate your applications (macros, things like that).

You can also use CodeDom to spit out assemblies you can link to at a later date. For example, all my business objects are represented by XSD and WSDL files, and I wrote a custom compiler that takes my specs and builds business entity objects with them. This allows me to take specifications, build a schema, and auto generate all the code with the special constraints, assert checks, logging, etc..

~Graham
foubar
foubar
I was just wondering how i would link in the use of a static variable within the program.

For example...

public class Test
{ public static string[] TestStringArray; }

I would need this to access and modify client information based on location and other attributes from the origonal application, acessed by the script.
backtrace
backtrace
After some playing with this (very useful) code, I still haven't figured out how to specify arguments for the called function. All my attempts have lead me to NullReferenceExceptions. Any idea how I would do this? Using temporary files doesn't look like a good solution to me, but it's the only thing I've been able to come up with for now.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.