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 cFun开发者_运维问答ction(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
This works (non-robust):
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)));
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 in
Pickaxe, chapter 17
精彩评论