How to bind C/C++ structure to Ruby

Hello. I need an advice how can I bind C/C++ structure to Ruby. I’ve
read some manuals and I found how to bind class methods to class, but I
still don’t understand how to bind structure fields and make them
accessible in Ruby.

myclass = rb_define_class(“Myclass”, 0);

typedef struct nya
{
char const* name;
int age;
} Nya;

Nya* p;
VALUE vnya;
p = (Nya*)(ALLOC(Nya));
p->name = “Masha”;
p->age = 24;
vnya = Data_Wrap_Struct(myclass, 0, free, p);
rb_eval_string(“def foo( a ) p a end”); // This function should print
structure object
rb_funcall(0, rb_intern(“foo”), 1, vnya); // Here I call the function
and pass the object into it

But Ruby function assumes this “a” as a pointer. It prints numeric value
of the pointer instead of it’s real content (like [“Masha”, 24]).
Obiously Ruby function can’t recognize this object - I didn’t set the
object’s properties names and types. But how can I do this -
unfortunately I couldn’t find it out.

lyn xy wrote in post #1048622:

But Ruby function assumes this “a” as a pointer. It prints numeric value
of the pointer instead of it’s real content (like [“Masha”, 24]).
Obiously Ruby function can’t recognize this object - I didn’t set the
object’s properties names and types. But how can I do this -
unfortunately I couldn’t find it out.

Hi,

You need to define some method to print, such as “to_s”:

static VALUE myclass_to_s(VALUE self)
{
Nya* p;
Data_Get_Struct(self, Nya, p);
char s[256];
sprintf(s, “[%s, %d]”, p->name, p->age);
return rb_str_new2(s);
}
rb_define_method(myclass, “to_s”, myclass_to_s, 0);

(I am sorry that I didn’t try to compile it, so probably there’s some
typo.)

Regards,

Bill

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs