I have an array (can be more than just one array) in C. I need to build an interface so that ruby can modify/read the array values. I am building ruby modules in C so they later are used in ruby.
C file:
#include <ruby.h>
VALUE ParentModule;
uint8 variable = 7;
uint8 array[2];
VALUE get_variable(VALUE self)
{
return INT2NUM(variable);
}
VALUE set_variable(VALUE self, VALUE x)
{
variable = NUM2UINT(x);
return Qnil;
}
void Init_extension(void)
{
ParentModule = rb_define_module("ParentModule");
rb_define_method(ParentModule, "variable", get_variable, 0);
rb_define_method(ParentModule, "variable=", set_variable, 1);
}
Ruby file:
class Thing
def initialize
extend ParentModule
end
end
c = Thing.new
c.variable #=> will return the value 7
c.variable= 10 #=> will write 10 to variable in the C section.
c.variable #=> returns 10
So all this works great, but now I need to be able to do the same with an array. What I tried:
C file:
VALUE get_array_0(VALUE self)
{
return INT2NUM(array[0]);
}
VALUE set_array_0(VALUE self, VALUE x)
{
array[0] = NUM2UINT(x);
return Qnil;
}
/* this line is inside Init_extension function */
rb_define_method(ParentModule, "array[0]", get_array_0, 0);
What I am trying to do is name the set/get method to give an impression in ruby that I am "using" an array when is just really an interface to interact with the array that exists in C. The C file compiles fine but when I try to call the method from Ruby, it complains saying that "array" is not a method
Ruby:
c = Thing.new
c.array[0] #=> NoMethodError (undefined method `array' for #<Thing:0x00000234523>)
What would be the best way to achieve this? (It must work for 2D arrays as well)
NOTE: Please edit my question if you find any information redundant.
c.send("array[0]")? I think Ruby is trying to allc.arrayand you have the C function asarray[0]. Might want to make a different name in C?rb_define_method(ParentModule, "array0", get_array_0, 0);c.send. I don't think the problem is the name, I think Ruby sees the [] after array and might be trying to treat it as an array/hash element. But that is just my guess.sendsuggestion was just a hail mary.array[0]isn't a valid method name anyways.