How to retrieve structure members of a struct type variable in C, passed from ruby script?

StackOverflow https://stackoverflow.com/questions/7440466

  •  20-01-2021
  •  | 
  •  

Question

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

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top