1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| // executable assumed to be "MyProg.exe"
using System.CodeDom ;
using System.CodeDom.Compiler ;
namespace MyNameSpace
{
public partial class MyForm : Form
...
private void button2_Click(object sender, EventArgs e)
{
string result = ExecuteUserCode("int i=100 ; int j=23 ; MyNameSpace.MyForm.UnTest() ; result=(i+j).ToString() ; ") ;
MessageBox.Show(result) ;
}
public static void UnTest() { MessageBox.Show("Test") ; }
delegate string ExecDelegate();
private static string ExecuteUserCode(string UserCode)
{
string CRLF = Environment.NewLine ;
string SourceHeader = "using System; " +CRLF+ // eventually add other reference
"class UserClass" +CRLF+
"{" +CRLF+
" static public string Exec()"+CRLF+
" {" +CRLF+
" string result=\"\" ;" ;
string SourceFooter = " return result ; " +CRLF+
" }" +CRLF+
"}" ;
string error="" ;
Assembly assembly = CompileSource(SourceHeader+UserCode+SourceFooter,out error);
string result="" ;
if (assembly==null) result=error ;
else
{
MethodInfo ExecMethod = assembly.GetType("UserClass").GetMethod("Exec");
result=((ExecDelegate)Delegate.CreateDelegate(typeof(ExecDelegate), ExecMethod))();
}
return result ;
}
private static Assembly CompileSource( string sourceCode,out string error )
{
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("System.dll");
cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");
cp.ReferencedAssemblies.Add("MyProg.exe"); // eventually add other reference
cp.GenerateExecutable = false;
CompilerResults cr = new Microsoft.CSharp.CSharpCodeProvider().CompileAssemblyFromSource(cp, sourceCode);
error="" ;
for (int i=0;i<cr.Errors.Count;i++)
error+=(i==0?"":Environment.NewLine)+"Line "+cr.Errors[i].Line.ToString()+" : "+cr.Errors[i].ErrorText;
return cr.Errors.Count==0?cr.CompiledAssembly:null;
} |
Partager