终端一体化运控平台
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

138 lines
5.0 KiB

  1. using Microsoft.CodeAnalysis;
  2. using Microsoft.CodeAnalysis.CSharp;
  3. using Microsoft.CodeAnalysis.Emit;
  4. using Microsoft.CSharp;
  5. using System;
  6. using System.CodeDom.Compiler;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Reflection;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. namespace BPASmartClient.Compiler
  13. {
  14. /// <summary>
  15. /// C#编译器
  16. /// </summary>
  17. public class CSharpConfig
  18. {
  19. #region 单例模式
  20. public static CSharpConfig Instance = null;
  21. public static CSharpConfig GetInstance()
  22. {
  23. if (Instance == null)
  24. {
  25. Instance = new CSharpConfig();
  26. }
  27. return Instance;
  28. }
  29. #endregion
  30. public CSharpConfig()
  31. {
  32. }
  33. public object RunCSharp(string code,object[] objValue,string error = "")
  34. {
  35. object strretu = string.Empty;
  36. try
  37. {
  38. string funName = "main";
  39. StringBuilder builder = new StringBuilder();
  40. builder.Append("namespace YF \n{\n class CSharpConfigRun\n");
  41. builder.Append(" {\n");
  42. builder.Append(code);
  43. builder.Append(" }\n}\n");
  44. SyntaxTree tree = CSharpSyntaxTree.ParseText(builder.ToString());
  45. var compilation =
  46. CSharpCompilation.Create("YF")
  47. .AddReferences(
  48. MetadataReference.CreateFromFile(
  49. typeof(object).Assembly.Location)
  50. )
  51. .AddSyntaxTrees(tree)
  52. .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
  53. EmitResult emitResult;
  54. byte[] dllBytes;
  55. using (var stream = new MemoryStream())
  56. {
  57. emitResult = compilation.Emit(stream);
  58. dllBytes = stream.ToArray();
  59. }
  60. if (emitResult.Success)
  61. {
  62. // Assembly assembly = Assembly.LoadFrom("d:\\test.dll");
  63. Assembly assembly = Assembly.Load(dllBytes);
  64. var obj = assembly.CreateInstance("YF.CSharpConfigRun");
  65. var method = obj.GetType().GetMethod("main",new Type[] { typeof(string) });
  66. strretu = method.Invoke(obj,objValue);
  67. }
  68. //var providerOptions = new Dictionary<string,string>();
  69. //providerOptions.Add("CompilerVersion","v4.0");
  70. //CSharpCodeProvider compiler = new CSharpCodeProvider(providerOptions);
  71. //string output = Path.GetTempFileName();
  72. //var cp = new CompilerParameters() { GenerateInMemory = true,OutputAssembly = output };
  73. //cp.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
  74. //cp.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
  75. //cp.ReferencedAssemblies.Add("System.Core.dll");
  76. //cp.ReferencedAssemblies.Add("Newtonsoft.Json.dll"); //添加引用
  77. //cp.ReferencedAssemblies.Add("System.dll");
  78. //cp.GenerateExecutable = false;
  79. //cp.EmbeddedResources.Clear();
  80. //cp.LinkedResources.Clear();
  81. //cp.Win32Resource = null;
  82. //cp.TreatWarningsAsErrors = false;
  83. //cp.WarningLevel = 4;
  84. //cp.TempFiles.KeepFiles = false;
  85. //CompilerResults cr = compiler.CompileAssemblyFromSource(cp,builder.ToString());
  86. // 1.ICodeComplier
  87. // CSharpCodeProvider complier = new CSharpCodeProvider();
  88. // // 2.CompilerParameters
  89. // CompilerParameters cp = new CompilerParameters();
  90. // cp.ReferencedAssemblies.Add("System.dll"); //添加引用
  91. //// cp.ReferencedAssemblies.Add("Newtonsoft.Json.dll"); //添加引用
  92. // cp.GenerateExecutable = false;
  93. // cp.GenerateInMemory = true;
  94. // // 3.CompilerResults
  95. // CompilerResults cr = complier.CompileAssemblyFromSource(cp,builder.ToString());
  96. //if (cr.Errors.HasErrors)
  97. //{
  98. // foreach (CompilerError err in cr.Errors)
  99. // {
  100. // error += err.ErrorText + "\r\n";
  101. // }
  102. //}
  103. //else
  104. //{
  105. // // 通过反射,调用HelloWorld的实例
  106. // Assembly objAssembly = cr.CompiledAssembly;
  107. // object objClass = objAssembly.CreateInstance("CSharpConfigRun");
  108. // MethodInfo objFun = objClass.GetType().GetMethod(funName);
  109. // strretu = objFun.Invoke(objClass,objValue);
  110. //}
  111. }
  112. catch (Exception ex)
  113. {
  114. error += ex.Message;
  115. }
  116. return strretu;
  117. }
  118. }
  119. }