IronPython和C# - 脚本访问C#对象

时间:2009-04-10 01:17:57

标签: c# ironpython

请考虑以下代码:

ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(null);
ScriptRuntime runtime = new ScriptRuntime(setup);
ScriptEngine engine = Python.GetEngine(runtime);
ScriptScope scope = engine.CreateScope();

scope.SetVariable("message", "Hello, world!");
string script = @"print message";
ScriptSource source = scope.Engine.CreateScriptSourceFromString(script, SourceCodeKind.Statements);
source.Execute();

此代码产生以下异常:

  

Microsoft.Scripting.Runtime.UnboundNameException   未处理的消息=“名称   'message'未定义“

我错过了什么?

2 个答案:

答案 0 :(得分:7)

它应该是“source.Execute(scope);”而不是“source.Execute();”

答案 1 :(得分:3)