如何在 C 中检索从 ruby 脚本传递的结构类型变量的结构成员?
我已经实现了 Ruby C 扩展(即从 ruby 脚本调用 C 函数) 以下是文件“cFile.c”中用 c 实现的函数
#include<stdio.h>
static VALUE cFunction(VALUE self, VALUE src)
{
if(TYPE(str) == T_STRUCT)
{
printf(" variable str is of STRUCT type \n");
}
// here how can i get the members of structure variable "str"
return Qnil;
}
void Init_MyRuby()
{
VALUE MRuby = rb_define_module("MyRuby");
rb_define_singleton_method(MRuby, "cFunction", cFunction, 1);
}
以下是通过传递结构类型变量调用 functon() 方法的 ruby 脚本代码。 client.rb:
require 'cFile'
customer = Struct.new( "Customer", :name, :address, :zip )
joe = customer.new( "JoeSmith", "123 Maple, Anytown NC", 12345 )
MyRuby::cFunction(joe)
任何人都可以建议我如何在 cFunction() 中获取结构成员(即名称、地址等)吗? 提前致谢
I have implemented Ruby C extension(i.e. Invoking C function from ruby script)
Following is the function implemented in c from file "cFile.c"
#include<stdio.h>
static VALUE cFunction(VALUE self, VALUE src)
{
if(TYPE(str) == T_STRUCT)
{
printf(" variable str is of STRUCT type \n");
}
// here how can i get the members of structure variable "str"
return Qnil;
}
void Init_MyRuby()
{
VALUE MRuby = rb_define_module("MyRuby");
rb_define_singleton_method(MRuby, "cFunction", cFunction, 1);
}
Following is the code of ruby script that invokes functon() method by passing struct type variable. client.rb:
require 'cFile'
customer = Struct.new( "Customer", :name, :address, :zip )
joe = customer.new( "JoeSmith", "123 Maple, Anytown NC", 12345 )
MyRuby::cFunction(joe)
can any one suggest me how to get struct members(i.e. name, address etc) in cFunction()?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是有效的(非鲁棒性):
为了获得更好的性能,您应该在 C 代码中定义结构类型并
然后通过
Data_Wrap_Struct
将其扩展为 Ruby 对象,如中所述镐,第 17 章
This works (non-robust):
For better performance you should rather define the struct type in your C code and
then extend it to a Ruby object via
Data_Wrap_Struct
as outlined inPickaxe, chapter 17