using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace BPASmartClient.Compiler
{
///
/// C#编译器
///
public class CSharpConfig
{
#region 单例模式
public static CSharpConfig Instance = null;
public static CSharpConfig GetInstance()
{
if (Instance == null)
{
Instance = new CSharpConfig();
}
return Instance;
}
#endregion
public CSharpConfig()
{
}
public object RunCSharp(string code,object[] objValue,string error = "")
{
object strretu = string.Empty;
try
{
string funName = "main";
StringBuilder builder = new StringBuilder();
builder.Append("namespace YF \n{\n class CSharpConfigRun\n");
builder.Append(" {\n");
builder.Append(code);
builder.Append(" }\n}\n");
SyntaxTree tree = CSharpSyntaxTree.ParseText(builder.ToString());
var compilation =
CSharpCompilation.Create("YF")
.AddReferences(
MetadataReference.CreateFromFile(
typeof(object).Assembly.Location)
)
.AddSyntaxTrees(tree)
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
EmitResult emitResult;
byte[] dllBytes;
using (var stream = new MemoryStream())
{
emitResult = compilation.Emit(stream);
dllBytes = stream.ToArray();
}
if (emitResult.Success)
{
// Assembly assembly = Assembly.LoadFrom("d:\\test.dll");
Assembly assembly = Assembly.Load(dllBytes);
var obj = assembly.CreateInstance("YF.CSharpConfigRun");
var method = obj.GetType().GetMethod("main",new Type[] { typeof(string) });
strretu = method.Invoke(obj,objValue);
}
//var providerOptions = new Dictionary();
//providerOptions.Add("CompilerVersion","v4.0");
//CSharpCodeProvider compiler = new CSharpCodeProvider(providerOptions);
//string output = Path.GetTempFileName();
//var cp = new CompilerParameters() { GenerateInMemory = true,OutputAssembly = output };
//cp.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
//cp.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
//cp.ReferencedAssemblies.Add("System.Core.dll");
//cp.ReferencedAssemblies.Add("Newtonsoft.Json.dll"); //添加引用
//cp.ReferencedAssemblies.Add("System.dll");
//cp.GenerateExecutable = false;
//cp.EmbeddedResources.Clear();
//cp.LinkedResources.Clear();
//cp.Win32Resource = null;
//cp.TreatWarningsAsErrors = false;
//cp.WarningLevel = 4;
//cp.TempFiles.KeepFiles = false;
//CompilerResults cr = compiler.CompileAssemblyFromSource(cp,builder.ToString());
// 1.ICodeComplier
// CSharpCodeProvider complier = new CSharpCodeProvider();
// // 2.CompilerParameters
// CompilerParameters cp = new CompilerParameters();
// cp.ReferencedAssemblies.Add("System.dll"); //添加引用
//// cp.ReferencedAssemblies.Add("Newtonsoft.Json.dll"); //添加引用
// cp.GenerateExecutable = false;
// cp.GenerateInMemory = true;
// // 3.CompilerResults
// CompilerResults cr = complier.CompileAssemblyFromSource(cp,builder.ToString());
//if (cr.Errors.HasErrors)
//{
// foreach (CompilerError err in cr.Errors)
// {
// error += err.ErrorText + "\r\n";
// }
//}
//else
//{
// // 通过反射,调用HelloWorld的实例
// Assembly objAssembly = cr.CompiledAssembly;
// object objClass = objAssembly.CreateInstance("CSharpConfigRun");
// MethodInfo objFun = objClass.GetType().GetMethod(funName);
// strretu = objFun.Invoke(objClass,objValue);
//}
}
catch (Exception ex)
{
error += ex.Message;
}
return strretu;
}
}
}