[Ruby/C] How to get and set attributes from C

Hey-ho !

I’m trying to access and edit attributes from a Ruby class with my C
module.
I believe the C functions existing for that purpose are rb_ivar_get and
rb_ivar_set.

The thing is : it doesn’t allow me to share anything between Ruby and C.
I mean that it does create something : if I set something with
rb_ivar_set, I will be able to get it from another C function.
But I can’t use them to access a Ruby attribute which has been set on
the Ruby side. Neither can the Ruby side access the attributes I created
from the C side.

How come ?

Here’s a sample of code to show you how I’m using the methods :

Ruby Sided Code :
class MyRubyClass
def initialize
@myStr = “Some gorgeous string”
end

def Execute
puts "Awesomeness ahead -> " + self.GetMyStr
end
end

C Sided Code :
#define VAR_NAME @myStr
// I tried with VAR_NAME = myStr and VAR_NAME = @@myStr

VALUE GetMyStr(VALUE self)
{
VALUE attr = rb_ivar_get(self, rb_intern(VAR_NAME));

if (attr == Qnil)
return (rb_str_new2("/!\ Oh fuck value was nil !"));
return (attr);
}

int main()
{
rb_init();
rb_init_loadpath();
rb_require("./test.rb");

VALUE klass = rb_funcall(rb_cObject, rb_intern(“const_get”), 1,
rb_str_new2(“MyRubyClass”));

// I made the next line simpler, GetMyStr is casted to the good type.
rb_define_method(klass, “GetMyStr”, GetMyStr, 0);

VALUE anInstance = rb_class_new_instance(0, 0,
rb_intern(“MyRubyClass”));

rb_funcall(anInstance, rb_intern(“Execute”), 0);

rb_ivar_set(anInstance, rb_intern(VAR_NAME), rb_str_new2(“Aaaw
yeah”));

rb_funcall(anInstance, rb_intern(“Execute”), 0);

rb_finalize();
return (0);
}

So, about this code.
Now, this will work, except that it will first print “Oh fuck value was
nil”, and then “Aaaw yeah”.
And of course, @myStr was never used and still has the same value.

Why is that ?

NONO change something …
rb_class_new_instance need a VALUE object, not an ID so

VALUE anInstance = rb_class_new_instance(0, 0,klass);

and that intern must be in “” i think so:

rb_ivar_set(anInstance, rb_intern("@myStr"), rb_str_new2(“Aaaw
yeah”));

or
#define VAR_NAME “@myStr

and sometimes better to capsle the method in define method into
RUBY_METHOD_FUNC( )