Communicate with dynamically executed C # code

Source: Internet
Author: User

1. Introduction

Being able to dynamically execute C # code is a cool feature. For example, we can enter a line of C # code in the console, and then the program automatically compiles and executes this line of code, display the result to us. This is almost the simplest C # code interpreter.

Dynamic execution of C # code is a very useful function. For example, we can write some code in a file and load it when the Assembly is executed. You do not need to abort the program to change the code, when the program loads the code again, the new Code is automatically executed.

Next, I will write a simple C # code interpreter, and then add the dynamic interaction mechanism between the dynamic code and the interpreter environment to the C # code interpreter, to demonstrate a very powerful application.

2. Simple C # code interpreter

How to dynamically execute C # code is clearly described in Jailu. Net's article "how to use C # To dynamically compile and execute code. Write a C # code interpreter as described in this article:

Using System;
Using System. Collections. Generic;
Using System. Reflection;
Using System. Globalization;
Using Microsoft. CSharp;
Using System. CodeDom;
Using System. CodeDom. Compiler;
Using System. Text;
Using System. IO;
Using System. Xml;

Namespace Test
{
Class Program
{
Static void Main (string [] args)
{
Console. Write ("> ");
String cmd;
Context cxt = new Context ();
While (cmd = Console. ReadLine (). Trim ())! = "Exit ")
{
If (! String. IsNullOrEmpty (cmd ))
{
Console. WriteLine ();
Cxt. Invoke (cmd );
}
Console. Write ("\ n> ");
}
}
}

Public class Context
{
Public CSharpCodeProvider CodeProvider {get; set ;}
Public IDictionary <String, Assembly> Assemblys {get; set ;}

Public Context ()
{
CodeProvider = new CSharpCodeProvider (new Dictionary <string, string> () {"CompilerVersion", "v3.5 "}});
Assemblys = new Dictionary <String, Assembly> ();
Assembly [] al = AppDomain. CurrentDomain. GetAssemblies ();
Foreach (Assembly a in al)
{
AddAssembly ();
}
AppDomain. CurrentDomain. AssemblyLoad + = new AssemblyLoadEventHandler (CurrentDomain_AssemblyLoad );
}

Private void AddAssembly (Assembly)
{
If (! = Null)
{
Assemblys. Add (a. FullName, );
}
}

Void CurrentDomain_AssemblyLoad (object sender, AssemblyLoadEventArgs args)
{
Assembly a = args. LoadedAssembly;
If (! Assemblys. ContainsKey (a. FullName ))
{
AddAssembly ();
}
}

Public CompilerParameters CreateCompilerParameters ()
{
CompilerParameters cp = new CompilerParameters ();
Cp. GenerateExecutable = false;
Cp. GenerateInMemory = true;
If (Assemblys! = Null)
{
Foreach (Assembly a in Assemblys. Values)
{
Cp. ReferencedAssemblies. Add (a. Location );
}
}
Return cp;
}

Public void Invoke (String cmd)
{
String inputaskstring = cmd. Trim ();
If (String. IsNullOrEmpty (input1_string) return;

String fullCmd = BuildFullCmd (input1_string );

CompilerResults cr = CodeProvider. CompileAssemblyFromSource (CreateCompilerParameters (), fullCmd );

If (cr. Errors. HasErrors)
{
Boolean recompileSwitch = true;

Foreach (CompilerError err in cr. Errors)
{
// CS0201: Only assignment, call, increment, decrement, and new object expressions can be
// Used as a statement
If (! Err. ErrorNumber. Equals ("CS0201 "))
{
RecompileSwitch = false;
Break;
}
}

// Re-compile
If (recompileSwitch)
{
String dynaName = "TempArg_Dynamic _" + DateTime. Now. Ticks. ToString ();
Inputdomainstring = String. Format ("var {0} =", dynaName) + inputdomainstring;
Inputpipeline string + = "; \ n System. Console. WriteLine (" + dynaName + ");";

FullCmd = BuildFullCmd (input1_string );
Cr = CodeProvider. CompileAssemblyFromSource (CreateCompilerParameters (), fullCmd );
}

If (cr. Errors. HasErrors)
{
Console. WriteLine ("Compilation error :");
Foreach (CompilerError err in cr. Errors)
{
Console. WriteLine (err. ErrorNumber );
Console. WriteLine (err. ErrorText );
}

Return;
}
}

Assembly assem = cr. CompiledAssembly;
Object dynamicObject = assem. CreateInstance ("Test. DynamicClass ");
Type t = assem. GetType ("Test. DynamicClass ");
MethodInfo minfo = t. GetMethod ("MethodInstance ");
Minfo. Invoke (dynamicObject, null );
}

Private String BuildFullCmd (String input1_string)
{
String fullCmd = String. Empty;

FullCmd + = @"
Namespace Test
{
Public class DynamicClass
{
Public void MethodInstance ()
{
"+ Input0000string + @";
}
}
}";
Return fullCmd;
}
}
}

After compilation and execution, a silly C # code parser can be used as a simple calculator:

3. Interaction between the interpreter and the interpreted code

If you store some variables in the interpreted code for future use, this interpreter is much more powerful. Assume that the names of these variables start with $, for example:

$ Myblogname = http://xiaotie.cnblogs.com"

It is defined in the interpreter environment (if the variable does not exist) or assigned to (if the variable already exists) a string variable named myblogname, pointing to the string "http://xiaotie.cnblogs.com ". However, System. Console. WriteLine ($ myblogname) retrieves and prints the string referenced by this variable.

To put it simply, let the interpreted code initialize and reference the variables in the interpreter.

How to implement it? This is the focus of this article.

First, define a SortedDictionary storage variable in the Context class and provide index access:

Public SortedDictionary <String, Object> Instances {get; set ;}
Public Object this [String instanceName]
{
Get
{
If (Instances. ContainsKey (instanceName ))
{
Return Instances [instanceName];
}
Else
{
Return null;
}
}
Set
{
If (Instances. ContainsKey (instanceName ))
{
Instances. Remove (instanceName );
}
Instances. Add (instanceName, value );
}
}

The BuildFullCmd method is changed:

 

Private String BuildFullCmd (String input1_string)
{
String fullCmd = String. Empty;

FullCmd + = @"
Using Test;

Public class DynamicClass
{
Private Context m_context;

Public void MethodInstance (Context context)
{
M_context = context;
"+ Input0000string + @";
}
}";
Return fullCmd;
}

In this way, Context objects can be referenced in dynamically generated objects.

For external variables not defined in input0000string, replace $ argname with a randomly generated internal variable at the first time. At the end of the Code, store the internal variable in Context.

Although the external variable $ argname can be referenced through (Context [argname]. GetType () (Context [argname]), the compiler reports an error when a value is referenced in this way. To solve this problem, a new class is required:

 

Public class ObjectHelper <T>
{
Private String m_objName;

Public Context {get; private set ;}

Public T Obj
{
Get
{
Object obj = Context [m_objName];
Return (T) obj;
}
Set {Context [m_objName] = value ;}
}

Public ObjectHelper (Context cxt, String objName)
{
M_objName = objName;
Context = cxt;
}
}

Replace $ argname, the external variable in input0000string, with (new bjectHelper <{m_context ["argname"]. getType ()}> (m_context, "argname ")). obj can be used to reference defined external variables in dynamic code.

The Preprocessing code for input0000string is as follows:

Regex re;

// Process uninitialized Environment Variables
Re = new Regex (@ "^ (\ $) (\ w) + ");
If (input1_string! = Null)
{
Match m = re. Match (input1_string );
If (m! = Null & m. Length> 1)
{
String outArgName = input1_string. Substring (m. Index, m. Length). Substring (1 );
If (this [outArgName] = null)
{
String innerArgName = "TempArg _" + outArgName;
Input‑string = "var" + input‑string. Replace ("$" + outArgName, innerArgName );
Inputdomainstring + = "; m_context [\" "+ outArgName +" \ "] =" + innerArgName + ";";
}
}
}

// Process other environment variables
Re = new Regex (@ "(\ $) (\ w) + ");
IDictionary <String, String> ArgsList = new Dictionary <String, String> ();
If (input1_string! = Null)
{
MatchCollection mc = re. Matches (input1_string );
If (mc! = Null)
{
Foreach (Match m in mc)
{
If (m. Length> 1)
{
String outArgName = input1_string. Substring (m. Index, m. Length). Substring (1 );
If (! ArgsList. ContainsKey (outArgName ))
{
Object obj = this [outArgName];
If (obj = null) throw new Exception ("environment variable does not exist" + outArgName );
String innerArgName = String. format (@ "(new ObjectHelper <{0}> (m_context," "{1 }"")). obj ", obj. getType (), outArgName );
ArgsList. Add (outArgName, innerArgName );
}
}
}
}

Foreach (String outArg in ArgsList. Keys)
{
Input‑string = input‑string. Replace ("$" + outArg, ArgsList [outArg]);
}
}

This is simplified, that is, the format of the external variable must be $ argname = value, where $ argname must be at the beginning of the line.

As a result, for $ myblogname = "http://xiaotie.cnblogs.com". Because the myblogname variable does not exist, it is parsed:
Var TempArg_myblogname = "http://xiaotie.cnblogs.com ";
M_context ["myblogname"] = TempArg_myblogname ;;

After definition, $ myblogname is resolved to (new ObjectHelper <System. String> (m_context, "myblogname"). Obj;

Check the actual execution:

Complete code is downloaded here.

4. A very powerful application-break into the. Net program and check its execution status.

OrcShell is improved by using the above method (for details about OrcShell, see the essay above: Implementing a simple CSharpShell -- OrcShell ). The new version of OrcShell is downloaded here (. Net 3.5 is required ). Basically, it is an available small. Net Framework Shell. You can dynamically view, create, and execute the. Net type. However, the automatic prompt and completion functions have not been completed yet, so it is inconvenient to use them.

The help command can view the list of commonly used commands:

Lsc lists the types and subordinate namespaces in the current namespace. Format: lsc [name]
Dirc and lsc
Cdc changes the current namespace. Format: cdc [. |... | name]
My view all variables. Format: my. You can use $ ArgName to reference variables.
Alias to view all aliases. Format: alias
Use to add a namespace. Format: use [namespace]
Unuse removes the namespace. Format: unuse [namespace]
Import the Assembly in two ways: "import-f [fullpath]", "import [partname]"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.