可以';t更新IronRuby中的变量值

本文关键字:IronRuby 变量值 更新 可以 | 更新日期: 2023-09-27 18:20:12

我一直在尝试将Ruby嵌入我正在编写的C#程序中。我可以执行脚本,但我在interop方面遇到了问题。我似乎无法从Ruby中提取变量。

让我们考虑以下内容:

String before = "hello world";
String after = "changed";
ScriptRuntime mRuntime = Ruby.CreateRuntime();
ScriptEngine mEngine = mRuntime.GetEngine("ruby");
ScriptScope scope = mEngine.CreateScope();
String code = "p msg'nmsg = '" + after + "'";
ScriptSource script = mEngine.CreateScriptSourceFromString(code, SourceCodeKind.Statements);
scope.SetVariable("msg", before);
script.Execute(scope);
String result = scope.GetVariable("msg");

(最初这是使用TryGetVariable实现的)

在我的单元测试中,我对result=="changed"设置了断言,但它带有默认值。我还尝试过在Ruby中创建一个变量(local和$global)并读取它,但它似乎永远不存在。

我有点困了,任何帮助都是徒劳的。

可以';t更新IronRuby中的变量值

String before = "hello world";
String after = "changed";
ScriptRuntime mRuntime = Ruby.CreateRuntime();
ScriptEngine mEngine = mRuntime.GetEngine("ruby");
ScriptScope scope = mEngine.CreateScope();
String code = "self.msg = '" + after + "'.to_clr_string";
ScriptSource script = mEngine.CreateScriptSourceFromString(code,  SourceCodeKind.Statements);
scope.SetVariable("msg", before);
script.Execute(scope);
String result = scope.GetVariable("msg");

这对我有用。