1

我已经实现了 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​​ 脚本代码。客户端.rb:

require 'cFile'
customer = Struct.new( "Customer", :name, :address, :zip )
joe = customer.new( "JoeSmith", "123 Maple, Anytown NC", 12345 )
MyRuby::cFunction(joe)

谁能建议我如何在 cFunction() 中获取结构成员(即名称、地址等)?提前致谢

4

1 回答 1

1

这有效(非稳健):

puts(STR2CSTR(rb_funcall(str, rb_intern("name"), 0)));
puts(STR2CSTR(rb_funcall(str, rb_intern("address"), 0)));
printf("%i\n", NUM2INT(rb_funcall(str, rb_intern("zip"), 0)));

为了获得更好的性能,您应该在 C 代码中定义结构类型,然后通过Pickaxe 第 17 章Data_Wrap_Struct中所述 将其扩展为 Ruby 对象

于 2011-09-16T11:16:46.497 回答