I'm embedding Ruby in C and I need to pass a struct created in C to a Ruby script, where I want to work with struct values. I have successfully done this with struct declaration rb_struct_define
and initialization rb_struct_new
, but I'm unable to pass a struct which is defined in C-style (struct Address {...}
).
I got some advice that this can be done with use of Data_Wrap_struct
, but I'm unable to get it working.
My example code is here: https://gist.github.com/1641269
Whatever you pass to a Ruby method needs to be a Ruby object, you can't directly pass a C struct object.
What you can do is create a wrapper object for your struct that will provide Ruby code access to its members. Unfortunately, as far as I'm aware, there's no way to automatically do this based on the members of the struct. You'll have to write the C code to define the appropriate methods, which might get a bit tedious if your struct has a lot of members.
The Data_Wrap_Struct
macro is what you use to wrap the C struct in a Ruby object. You can then use Data_Get_Struct
in the implementations of the methods to unwrap the struct and get at the data.
Here's an example that should hopefully point you in the right direction.