【发布时间】:2011-07-17 19:21:42
【问题描述】:
我正在尝试创建一个脚本系统,该系统使用 C# 的 CSharpCodeProvider 在运行时构建 C# 代码。这是我正在开发的一个简单的游戏引擎,用 XNA 4.0 编写。 目标是让用户能够通过 C# 修改游戏元素,而无需访问游戏引擎的具体细节(渲染代码、物理代码、网络等)。脚本在运行时由引擎编译成 DLL。目前我已经建立了引擎和已编译脚本 DLL 之间的通信。 (我创建了一个 Player.cs 脚本,编译后它能够从脚本 DLL 调用我的引擎的“Engine.Print("Foobar"); 方法)引擎也能够使用脚本的方法(引擎搜索所有新的类在编译后在脚本中定义,并在编译后调用它们的“OnCompile()”方法。
问题始于脚本间通信:我有 2 个脚本,Inventory 和 Player:
Inventory.cs:
public class Inventory
{
int foobar;
public Inventory()
{
foobar = 42;
}
public static void OnCompile()
{
// This method exists in the Engine DLL, linked to this script
Engine.Print("OnCompile Inventory");
}
}
播放器.cs:
using Scripts.Inventory;
public class Player
{
Inventory inventory;
public Player()
{
//inventory = new Inventory();
Engine.Print("Player created");
}
public static void OnCompile()
{
Engine.Print("OnCompile Player");
Player test = new Player();
}
}
此代码功能,调试输出打印:
编译清单
OnCompile 播放器
玩家创建
但是,一旦我取消注释inventory = new Inventory();在 Player 构造函数中 调试输出如下:
编译清单
OnCompile 播放器
未处理的异常:System.Reflection.TargetInvocationException:调用的目标已引发异常。 ---> System.IO.FileNotFoundException:无法加载文件或程序集“Inventory.cs,版本=0.0.0.0,文化=中性,PublicKeyToken=null”或其依赖项之一。该系统找不到指定的文件。 在 Scripts.Player.Player..ctor() 在 Scripts.Player.Player.OnCompile()
我已确保我的 Player.cs.dll 具有对 Inventory.cs.dll 的引用。我的编译代码如下:
public static bool Compile(string fileName, bool forceRecompile = false)
{
// Check to see if this assembly already exists.
// If it does, then just return a reference to it, unless
// it is told to forceRecompile, in which case
// it will delete the old, and continue compiling
if (File.Exists("./" + fileName + ".dll"))
{
if (forceRecompile)
{
File.Delete(fileName + ".dll");
}
else
{
return true;
}
}
// Generate a name space name. this means removing the initial ./
// of the path, and replacing all subsequent /'s with .'s
// Also removing the .cs at the end
// i.e: ./Scripts/Player.cs becomes
// Scripts.Player
string namespaceName = "";
if (fileName.LastIndexOf('.') != -1)
{
fileName = fileName.Remove(fileName.LastIndexOf('.'));
}
namespaceName = fileName.Replace('/', '.');
namespaceName = namespaceName.Substring(2);
// Add references, starting with ScriptBase.dll.
// ScriptBase.dll is a helper library that provides
// access to debug functions such as Console.Write
List<string> references = new List<string>()
{
"./ScriptBase.dll",
"System.dll" // TODO: remove later
};
// Open the script file wit ha StreamReader
StreamReader fileStream;
string scriptSource = "";
fileStream = File.OpenText("./" + fileName + ".cs");
// Preprocess the script. This is important, as it resolves
// using statements, so that if a script references another
// script, it will have the dependency registered before
// compiling.
do
{
string line = fileStream.ReadLine();
string[] words = line.Split(' ');
// Found a using statement:
if (words[0] == "using")
{
// Get the namepsace name:
string library = words[1];
library = library.Remove(library.Length - 1); // get rid of semicolon
// Convert back to a path
library = library.Replace('.', '/');
// See if the assembly exists, or we are forcing the recompilation
if (!File.Exists("./" + library + ".cs.dll") || forceRecompile)
{
// We need to compile it now.
// See if the script file exists...
if (File.Exists("./" + library + ".cs"))
{
// if it does, compile that, if it doesn't then we bail
if (!Compile("./" + library + ".cs", forceRecompile))
{
return false;
}
}
else
{
return false;
}
}
// Now that it's compiled, and we need it link it with our reference list...
references.Add("./" + library + ".cs.dll");
}
// Piece it back together as one string, line by line.
scriptSource = scriptSource + line + "\n";
} while (!fileStream.EndOfStream);
fileStream.Close();
// Automagically add our namepsace to the script, so the scriptor doesn't have to, also automatically
// include ScriptBase
// This is where Engine class is found for Print() debug method
string source = "using ScriptBase; namespace " + namespaceName + "{" + scriptSource + "}";
// Set up the compiler:
Dictionary<string, string> providerOptions = new Dictionary<string, string>
{
{ "CompilerVersion", "v3.5" }
};
CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);
// Create compilation params... Here we link our references, and append ".cs.dll" to our file name
// So now for example, ./Scripts/Player.cs compiles to ./Script/Player.cs.dll
CompilerParameters compilerParams = new CompilerParameters(references.ToArray(), fileName + ".cs.dll")
{
GenerateInMemory = true,
GenerateExecutable = false, // compile as DLL
};
// Compile and check errors
CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);
if (results.Errors.Count != 0)
{
foreach (CompilerError error in results.Errors)
{
// Write out any errors found:
Console.WriteLine("Syntax Error in " + error.FileName + " (" + error.Line + "): " + error.ErrorText);
}
return false;
}
// Return our Script struct, which keeps all the information together,
// and registers it so that Script.GetCompiledScript("./Scripts/Player.cs.dll");
// returns the compiled script, or null if it's never been compiled
Assembly.LoadFrom(fileName + ".cs.dll");
foreach (Type type in results.CompiledAssembly.GetTypes())
{
new ScriptClass(fileName + ".cs.dll", type);
}
return true;
}
}
我已经单步执行了代码,Inventory.cs 总是按预期在 Player.cs 之前编译,并且在编译之前正确地将 Inventory.cs.dll 添加到 Player.cs 的引用列表中。
我一定是遗漏了一些东西,简单地链接参考列表中的 DLL 似乎还不够,错误提到文件 Inventory.cs 未找到。在哪里指定搜索源 .cs 的路径? (.cs.dll 编译后的脚本总是和 .cs 源脚本在同一路径下)
【问题讨论】: