title: How to create a Ruby interface to C array
body: <p>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.</p>
  
  <p>C file:</p>
  
  <pre><code>#include &lt;ruby.h&gt;
  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);
  }
  </code></pre>
  
  <p>Ruby file:</p>
  
  <pre><code>class Thing
    def initialize
      extend ParentModule
    end
  end
  c = Thing.new
  c.variable #=&gt; will return the value 7
  c.variable= 10 #=&gt; will write 10 to variable in the C section.
  c.variable #=&gt; returns 10
  </code></pre>
  
  <p>So all this works great, but now I need to be able to do the same with an array. What I tried:</p>
  
  <p>C file:</p>
  
  <pre><code>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);
  </code></pre>
  
  <p>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</p>
  
  <p>Ruby:</p>
  
  <pre><code>c = Thing.new
  c.array[0] #=&gt; NoMethodError (undefined method `array' for #&lt;Thing:0x00000234523&gt;)
  </code></pre>
  
  <p>What would be the best way to achieve this? (It must work for 2D arrays as well)</p>
  
  <p>NOTE: Please edit my question if you find any information redundant.</p>