Calling IronRuby from C# with a delegate

不羁岁月 提交于 2019-11-30 15:55:17

问题


Is it possible to call an IronRuby method from C# with a delegate as parameter in such a way that yield would work?

The following gives me a wrong number of arguments (1 for 0) exception.

Action<string> action = Console.WriteLine;
var runtime = Ruby.CreateRuntime();
var engine = runtime.GetEngine("rb");
engine.Execute(@"
                 class YieldTest
                   def test
                     yield 'From IronRuby'
                   end
                 end
                ");
object test = engine.Runtime.Globals.GetVariable("YieldTest");
dynamic t = engine.Operations.CreateInstance(test);
t.test(action);

回答1:


I'm sure Ruby's block is not a c# delegate.
If you pass delegate to Ruby you should invoke it via delegate's Invoke method.
Here is sample code:

var rt = Ruby.CreateRuntime();
var eng = rt.GetEngine("rb");
eng.Execute(@"
            class Blocktest
              def test(block)
                block.Invoke('HELLO From IronRuby')
              end
            end
            ");
dynamic ruby = eng.Runtime.Globals;
dynamic t = ruby.Blocktest.@new();
t.test(new Action<string>(Console.WriteLine));

Can we convert c# delegate into ruby block... I don't know.




回答2:


Got an answer by IronRuby core team member Tomáš Matoušek on the IronRuby-core list that it's not possible. Yet.



来源:https://stackoverflow.com/questions/4189955/calling-ironruby-from-c-sharp-with-a-delegate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!