Accessing hash key values in ruby from c extension

Hello There

I have a hash map as an attr_accessor in a class A. I want to access the
key/value pair of this hash map from C extension.

#In Ruby
class A
Anchor =
{
anchorA: 0,
anchorB: 1,
anchorC: 2
}

attr_accessor *Anchor.keys

def initialize ()
  ...
end

end

Can someone please guide me to get the key/value pairs in C extension?

Subject: Accessing hash key values in ruby from c extension
Date: ven 07 mar 14 03:55:55 +0100

Quoting Vitesh J. ([email protected]):

}

attr_accessor *Anchor.keys

def initialize ()
  ...
end

end

Can someone please guide me to get the key/value pairs in C
extension?

You use functions rb_hash_foreach, rb_hash_aref and friends. I believe
the best thing to do to learn how to use this function is to look at
the many examples in the MRI source code - especially in the
extensions:

cd

find ext/ -name ‘*.c’ -exec grep -H rb_hash_ {} ;

Carlo

thanks Carlo,

I have browsed through the code in ext directory as you guided but I
have not found the case where class contains a hash map and is declared
as attr_accessor.

I am using the following

#In Ruby
class AA
Anchor =
{
anchorAA: 0,
anchorAB: 1,
anchorAC: 2
}

attr_accessor *Anchor.keys

def initialize ()
  ...
end

end

#In Ruby
class BB
Anchor =
{
anchorBA: 0,
anchorBB: 1,
anchorBC: 2
}

attr_accessor *Anchor.keys

def initialize ()
  ...
end

end

/On C side*/
VALUE func (VALUE self, VALUE obj)
{
/SAY if self corresponds to object of class AA/
VALUE test = rb_iv_get(self, “@Anchor”);
ID id = rb_intern(“anchorAA”);
VALUE test1 = rb_hash_aref(test, ID2SYM(id));

}

Is the above correct Carlo?

On Mar 7, 2014, at 11:44, Vitesh J. [email protected] wrote:

 anchorAA:   0,
 anchorAB:   1,
 anchorAC:   2

}

That’s not an attr_accessor, that’s a const.

attr_accessor *Anchor.keys

I have no idea what that is supposed to do or how it is supposed to
work. You need to make your code work in pure ruby before you bother
trying to make it work in C.

Finally, please read all of README.EXT in the ruby source.

Subject: Re: Accessing hash key values in ruby from c extension
Date: ven 07 mar 14 08:44:59 +0100

Quoting Vitesh J. ([email protected]):

Is the above correct Carlo?
@Anchor” means nothing. Anchor is a class constant, not an instance
variable.

The function to access class constants from C is rb_const_get. Search
for examples in the same way.

I personally never needed to access ruby class constants from C. I try
to make as neat a separation between the two worlds as possible. I use
C only when I need raw speed, or when I have to access C libraries.

If I were you, I’d pass all info I need to transfer from Ruby to C as
separate parameters. It is nifty to be ruby=ish under C, but it
obfuscates things a lot.

Carlo