Skip to main content
gamedev.net
🔒 Locked

Basic C# scripting engine

Started by davidjustus Feb 21, 2006 at 11:37 AM 0 replies 1.2k views
Original Post
davidjustus
davidjustus
When i was working on this i noticed their was little information on the web in regards to creating a C# scripting engine. So i thought i would share some code i trew togther from some webblogs and personal experince that enabled a basic C# scripting engine. This code isnt that complex. What it does is uses the ICodeCompiler class in the .net framework to compile a script, give it all the assemblies in your currnet app and then run a function. You are even able to pass objects to the function in the scripting engine, allowing you to access hardcoded objects and classes.

using Microsoft.CSharp;
using System.CodeDom.Compiler;

/// <summary>
/// Loads a script file and exicutes it.
/// </summary>
/// <param name="sourcefile">the file to load the script from</param>
private Object sobj;
public void load(string sourcefile)
{

	CSharpCodeProvider codeProvider = new CSharpCodeProvider();
	ICodeCompiler compiler = codeProvider.CreateCompiler();
	CompilerParameters parameters = new CompilerParameters();
	parameters.GenerateExecutable = false;
	parameters.GenerateInMemory = true;
	parameters.OutputAssembly = "CS-Script-Tmp-Junk";
	parameters.MainClass = "Script.Main";
	parameters.IncludeDebugInformation = false;
         //Add all the assemblies in the currnet application to the script.
	foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) 
	{
		parameters.ReferencedAssemblies.Add(asm.Location);
	}
			
        //Read a file
	string source;
	StreamReader re = File.OpenText(sourcefile);
	source = re.ReadToEnd();
	re.Close();

        //Compile the script
	CompilerResults results = compiler.CompileAssemblyFromSource(parameters, source);
	if (results.Errors.Count > 0) 
	{
		string errors = "Compilation failed:\n";
		foreach (CompilerError err in results.Errors) 
		{
			errors += err.ToString() + "\n";
		}
		MessageBox.Show(errors, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

	}
	object o = results.CompiledAssembly.CreateInstance("Script");
			
        sobj = o;
}
/// <summary>
/// Call a function from within the script
/// </summary>
/// <param name="function">the name of the function</param>
/// <param name="parm">an array of parameters</param>
public void Invoke(string function, object[] parm)
{
	//if not compiled
        if(sobj == null)
	{
		return;
	}
        //try to run the function
	try 
	{
		Type type = sobj.GetType();
		MethodInfo m = type.GetMethod(function);
		m.Invoke(sobj,parm);
	}
	catch{
				
		return;
	}

}
Its not the best but its a start for anyone like me who needs a basic C# scripting engine. Dave.
Dave.

Topic Locked

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

Sign in to reply to this topic.