IronRuby,如何将参数变量从C#传递到Ruby?
首先,以下是我在SharpDevelop项目的bin/debug文件夹中设置的ruby文件的代码:IronRuby,如何将参数变量从C#传递到Ruby?,c#,ruby,argument-passing,ironruby,C#,Ruby,Argument Passing,Ironruby,首先,以下是我在SharpDevelop项目的bin/debug文件夹中设置的ruby文件的代码: class Run_Marshal def initialize(id, name) @list = [] @list[0] = Employee_Info.new(id, name) File.open("employee_sheet.es", "wb") {|f| Marshal::dump(@list, f)} end
class Run_Marshal
def initialize(id, name)
@list = []
@list[0] = Employee_Info.new(id, name)
File.open("employee_sheet.es", "wb") {|f| Marshal::dump(@list, f)}
end
end
class Employee_Info
attr_accessor :id
attr_accessor :name
def initialize(id, name)
@id = id
@name = name
end
end
上面的代码允许将Employee_Info对象序列化为文件。请注意,我已经安装了IronRuby
下面是我用来执行ruby代码的C代码。将参数从C#传递到我的新Ruby对象是很重要的
void Btn_exportClick(object sender, EventArgs e)
{
var engine = Ruby.CreateEngine();
engine.ExecuteFile("Ruby_Classes.rb");
dynamic ruby = engine.Runtime.Globals;
int id = 0;
string name = "John Coles";
dynamic foo = ruby.Run_Marshal.@new(id, name);
}
最后,这里是另一个ruby项目集在另一个不同ruby环境中的ruby代码
@my_foo = File.open("Data/employee_sheet.es", "rb") {|f| Marshal.load(f)}
@name = @my_foo[0].name
当然,我还确保Employee_Info类在其他环境中可用
class Employee_Info
attr_accessor :id
attr_accessor :name
def initialize(id, name)
@id = id
@name = name
end
end
代码在我的SharpDevelop项目中运行良好,并在bin/debug文件夹中输出一个序列化(封送)文件。然后,我将该序列化文件放入另一个ruby环境的另一个文件夹中
class Employee_Info
attr_accessor :id
attr_accessor :name
def initialize(id, name)
@id = id
@name = name
end
end
当我运行其他环境时,程序崩溃并产生以下错误:“ArgumentError Occursed.Undefined class/module System:”
我又做了一些测试,我意识到当我把上面的代码改成这个时(见带有三个“*”的行):
class Run_Marshal
def initialize(id, name)
@list = []
@list[0] = Employee_Info.new(0, "Beettlejuice") // ***
File.open("employee_sheet.es", "wb") {|f| Marshal::dump(@list, f)}
end
end
它现在可以毫无问题地打开序列化文件了。所以我怀疑问题是由于从C代码传递到ruby代码的参数造成的。我确实需要传递C变量来完成更复杂的任务,但到目前为止我还不知道如何让它工作。我希望你们能解释出问题所在。那么如何将参数变量从C传递到ruby?
谢谢!我无法解释如何以及为什么,但我通过以下方式解决了问题:
class Run_Marshal
def initialize(id, name)
@list = []
@list[0] = Employee_Info.new(id, name.to_s)
File.open("employee_sheet.es", "wb") {|f| Marshal::dump(@list, f)}
end
end
我在传递的字符串中添加了“s”。显然Ruby没有将参数识别为字符串