Files
iFactory.Cutting.Unity/Assets/BITKit/Core/Sharp/BITSharp.cs

85 lines
2.9 KiB
C#
Raw Normal View History

2024-01-23 02:56:26 +08:00
using System;
using System.CodeDom.Compiler;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Microsoft.CSharp;
namespace BITKit
{
public class BITSharp
{
public static readonly List<string> ReferencedAssemblies = new();
private static readonly ConcurrentDictionary<string, Type> Dictionary = new();
private static Assembly[] assemblies;
public static bool TryGetTypeFromFullName(string fullClassName,out Type type)
{
type = GetTypeFromFullName(fullClassName);
return type is not null ? true : false;
}
public static Type GetTypeFromFullName(string fullClassName)
{
return Dictionary.GetOrAdd(fullClassName, SearchType);
}
private static Type SearchType(string fullName)
{
assemblies = assemblies??AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in assemblies)
{
var type = assembly.GetType(fullName,false);
if (type is not null)
{
return type;
}
else
{
continue;
}
}
return null;
}
#if UNITY_64
public static Assembly Compile(params string[] codes)
{
var codeProvider = new CSharpCodeProvider();
var parameters = new CompilerParameters
{
GenerateInMemory = true,
CompilerOptions = "/unsafe"
};
parameters.ReferencedAssemblies.Add("System.dll");
foreach (var x in ReferencedAssemblies)
{
parameters.ReferencedAssemblies.Add(x);
}
var results = codeProvider.CompileAssemblyFromSource(parameters, codes);
if (results.Errors.Count <= 0)
{
BIT4Log.Log<BITSharp>($"编译成功:{results.CompiledAssembly.FullName}");
return results.CompiledAssembly;
}
foreach (CompilerError error in results.Errors)
{
var sb = new StringBuilder();
sb.AppendLine(error.FileName);
sb.AppendLine($"Error ({error.ErrorNumber}): {error.ErrorText}");
sb.AppendLine($"Line: {error.Line}, Column: {error.Column}");
sb.AppendLine($"Is Warning: {error.IsWarning}");
BIT4Log.LogException(new Exception(sb.ToString()));
}
throw new Exception("编译失败");
// object o = results.CompiledAssembly.CreateInstance("RuntimeCompiledNamespace.RuntimeCompiledClass");
// MethodInfo mi = o.GetType().GetMethod("RuntimeCompiledMethod");
// mi.Invoke(o, null);
}
#endif
}
}