【问题标题】:Can't update variable values from IronRuby无法从 IronRuby 更新变量值
【发布时间】:2014-09-02 00:30:42
【问题描述】:

我一直在尝试将 Ruby 嵌入到我正在编写的 C# 程序中。 我可以执行脚本,但我遇到了互操作问题。 我似乎无法从 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(本地和 $global)中创建一个变量并将其读出,但它似乎永远不存在。

我有点卡住了,任何帮助都将不胜感激。

【问题讨论】:

    标签: c# ruby scripting ironruby


    【解决方案1】:
    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");
    

    这对我有用。

    【讨论】:

    • 这行得通。 IronRuby 可以使用更好的文档进行互操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-03
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    相关资源
    最近更新 更多