# Accessing C structures in Ruby

**URL:** <https://www.ruby-forum.com/t/accessing-c-structures-in-ruby/50108>\
**Category:** Ruby\
**Created:** [December 13, 2005, 4:20am UTC](https://www.ruby-forum.com/t/accessing-c-structures-in-ruby/50108 "2005-12-13T04:20:57Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![joe-dumoulin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9dc877/32.png) [@joe-dumoulin](https://www.ruby-forum.com/u/joe-dumoulin)\
**Post date:** [December 13, 2005, 4:20am UTC](https://www.ruby-forum.com/t/accessing-c-structures-in-ruby/50108/1 "2005-12-13T04:20:57Z")

</div>

(I’ve already looked at Swig, btw. I’d like to do this one by hand.)

I have the following:

typedef struct {  
double x;  
double y;  
double z;  
} VelocityRecord;

typedef struct {  
double x;  
double y;  
double z;  
} PositionRecord;

typedef struct {  
int id;  
int type;  
PositionRecord position;  
VelocityRecord velocity;  
} Player;

Player Players[10];

The number of Players is fixed ahead of time. I want to be able to  
access that data from Ruby. Ideally, something like:

module Simulation  
attr\_accessor :players # Other stuff will be here  
class Player  
class VelocityRecord  
attr\_accessor :x, :y :z  
end  
class PositionRecord  
attr\_accessor :x, :y, :z  
end  
end  
end

---

<div class="post-metadata">

**Author:** ![joe-dumoulin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9dc877/32.png) [@joe-dumoulin](https://www.ruby-forum.com/u/joe-dumoulin)\
**Post date:** [December 13, 2005, 4:57am UTC](https://www.ruby-forum.com/t/accessing-c-structures-in-ruby/50108/2 "2005-12-13T04:57:04Z")

</div>

On 12/12/05, Joe Van D. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> typedef struct {  
> } Player;  
> class VelocityRecord  
> attr\_accessor :x, :y :z  
> end  
> class PositionRecord  
> attr\_accessor :x, :y, :z  
> end  
> end  
> end

Hm, on second thought, it’s probably a lot easier to do:

class Player  
attr\_reader :x\_position, :y\_position, :z\_position, :x\_velocity,  
:y\_velocity, :z\_velocity  
end

So, maybe something like this?

void Init\_Simulation()  
{  
rb\_define\_module(mSimulation, “Simulation”);  
rb\_define\_class\_under(cPlayer, “Player”);

rb\_define\_method(cPlayer, “x\_position”, get\_x\_position, 0);  
rb\_define\_method(cPlayer, “y\_position”, get\_y\_position, 0);  
rb\_define\_method(cPlayer, “z\_position”, get\_z\_position, 0);  
rb\_define\_method(cPlayer, “x\_velocity”, get\_x\_velocity, 0);  
rb\_define\_method(cPlayer, “y\_velocity”, get\_y\_velocity, 0);  
rb\_define\_method(cPlayer, “z\_velocity”, get\_z\_velocity, 0);  
}

---

<div class="post-metadata">

**Author:** ![joe-dumoulin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9dc877/32.png) [@joe-dumoulin](https://www.ruby-forum.com/u/joe-dumoulin)\
**Post date:** [December 13, 2005, 5:07am UTC](https://www.ruby-forum.com/t/accessing-c-structures-in-ruby/50108/3 "2005-12-13T05:07:07Z")

</div>

Joe Van D. wrote:

> (I’ve already looked at Swig, btw. I’d like to do this one by hand.)
> 
> I have the following:
> 
> typedef struct {  
> double x;  
> double y;  
> double z;  
> } VelocityRecord;
> 
> typedef struct {  
> double x;  
> double y;  
> double z;  
> } PositionRecord;
> 
> typedef struct {  
> int id;  
> int type;  
> PositionRecord position;  
> VelocityRecord velocity;  
> } Player;
> 
> Player Players[10];
> 
> The number of Players is fixed ahead of time. I want to be able to  
> access that data from Ruby. Ideally, something like:
> 
> module Simulation  
> attr\_accessor :players # Other stuff will be here  
> class Player  
> class VelocityRecord  
> attr\_accessor :x, :y :z  
> end  
> class PositionRecord  
> attr\_accessor :x, :y, :z  
> end  
> end  
> end

My typical recommendation is to just wrap a pointer to  
the struct and pass that around. Then, for each method  
just extract the pointer, access the correct field and  
generate a VALUE out of that (inside the function that  
corresponds to the method).

E

---

<div class="post-metadata">

**Author:** ![joe-dumoulin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9dc877/32.png) [@joe-dumoulin](https://www.ruby-forum.com/u/joe-dumoulin)\
**Post date:** [December 13, 2005, 6:00am UTC](https://www.ruby-forum.com/t/accessing-c-structures-in-ruby/50108/4 "2005-12-13T06:00:14Z")

</div>

On 12/12/05, Eero S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> > VelocityRecord velocity;  
> > class Player  
> > the struct and pass that around. Then, for each method  
> > just extract the pointer, access the correct field and  
> > generate a VALUE out of that (inside the function that  
> > corresponds to the method).

Can you share more details? Is that essentially what I’ve done in my  
later posts on this?

---

<div class="post-metadata">

**Author:** ![joe-dumoulin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9dc877/32.png) [@joe-dumoulin](https://www.ruby-forum.com/u/joe-dumoulin)\
**Post date:** [December 13, 2005, 5:33am UTC](https://www.ruby-forum.com/t/accessing-c-structures-in-ruby/50108/5 "2005-12-13T05:33:10Z")

</div>

On 12/12/05, Joe Van D. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> > VelocityRecord velocity;  
> > class Player
> 
> rb\_define\_class\_under(cPlayer, “Player”);
> 
> rb\_define\_method(cPlayer, “x\_position”, get\_x\_position, 0);  
> rb\_define\_method(cPlayer, “y\_position”, get\_y\_position, 0);  
> rb\_define\_method(cPlayer, “z\_position”, get\_z\_position, 0);  
> rb\_define\_method(cPlayer, “x\_velocity”, get\_x\_velocity, 0);  
> rb\_define\_method(cPlayer, “y\_velocity”, get\_y\_velocity, 0);  
> rb\_define\_method(cPlayer, “z\_velocity”, get\_z\_velocity, 0);  
> }

So, I have a bunch of functions that look like this now:

VALUE get\_player\_x\_pos(VALUE self)  
{  
Player\* p;  
Data\_Get\_Struct(self, Player, p);  
rb\_float\_new(p-\>position.x);  
}

That the way to go?

---

<div class="post-metadata">

**Author:** ![joe-dumoulin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9dc877/32.png) [@joe-dumoulin](https://www.ruby-forum.com/u/joe-dumoulin)\
**Post date:** [December 13, 2005, 6:15am UTC](https://www.ruby-forum.com/t/accessing-c-structures-in-ruby/50108/6 "2005-12-13T06:15:16Z")

</div>

On 12/12/05, Joe Van D. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> > > } VelocityRecord;  
> > > PositionRecord position;  
> > > attr\_accessor :players # Other stuff will be here  
> > > My typical recommendation is to just wrap a pointer to  
> > > the struct and pass that around. Then, for each method  
> > > just extract the pointer, access the correct field and  
> > > generate a VALUE out of that (inside the function that  
> > > corresponds to the method).
> 
> Can you share more details? Is that essentially what I’ve done in my  
> later posts on this?

Here’s what I have so far. Seems to work well:

#include “ruby.h”  
#include “simulation.h”

VALUE get\_frame\_count(VALUE self) { return INT2NUM(HIFEN2\_Count); }  
VALUE get\_mission\_time(VALUE self) { return INT2NUM(HIFEN2\_Mission); }  
VALUE get\_max\_players(VALUE self) { return INT2NUM(MAX\_PLAYERS); }

VALUE player\_new(VALUE self, VALUE rb\_i)  
{  
int i = NUM2INT(rb\_i);  
return Data\_Wrap\_Struct(self, NULL, NULL, &Players[i]);  
}

Player\* get\_player(VALUE self)  
{  
Player \*p;  
Data\_Get\_Struct(self, Player, p);  
return p;  
}

VALUE get\_player\_id(VALUE self) { return INT2NUM(get\_player(self)-\>id);  
}

VALUE get\_player\_x\_pos(VALUE self) { return  
rb\_float\_new(get\_player(self)-\>position.x); }  
VALUE get\_player\_y\_pos(VALUE self) { return  
rb\_float\_new(get\_player(self)-\>position.y); }  
VALUE get\_player\_z\_pos(VALUE self) { return  
rb\_float\_new(get\_player(self)-\>position.z); }

VALUE get\_player\_x\_vel(VALUE self) { return  
rb\_float\_new(get\_player(self)-\>velocity.x); }  
VALUE get\_player\_y\_vel(VALUE self) { return  
rb\_float\_new(get\_player(self)-\>velocity.y); }  
VALUE get\_player\_z\_vel(VALUE self) { return  
rb\_float\_new(get\_player(self)-\>velocity.z); }

VALUE cSimulation;  
VALUE cPlayer;

void Init\_Sim()  
{  
cSimulation = rb\_define\_class(“Simulation”, rb\_cObject);  
rb\_define\_method(cSimulation, “frame\_count”, get\_frame\_count, 0);  
rb\_define\_method(cSimulation, “mission\_time”, get\_mission\_time, 0);  
rb\_define\_method(cSimulation, “max\_players”, get\_max\_players, 0);

cPlayer = rb\_define\_class(“Player”, rb\_cObject);  
rb\_define\_singleton\_method(cPlayer, “new”, player\_new, 1);  
rb\_define\_method(cPlayer, “player\_id”, get\_player\_id, 0);

rb\_define\_method(cPlayer, “x\_position”, get\_player\_x\_pos, 0);  
rb\_define\_method(cPlayer, “y\_position”, get\_player\_y\_pos, 0);  
rb\_define\_method(cPlayer, “z\_position”, get\_player\_z\_pos, 0);

rb\_define\_method(cPlayer, “x\_velocity”, get\_player\_x\_vel, 0);  
rb\_define\_method(cPlayer, “y\_velocity”, get\_player\_y\_vel, 0);  
rb\_define\_method(cPlayer, “z\_velocity”, get\_player\_z\_vel, 0);  
}

---

<div class="post-metadata">

**Author:** ![joe-dumoulin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9dc877/32.png) [@joe-dumoulin](https://www.ruby-forum.com/u/joe-dumoulin)\
**Post date:** [December 13, 2005, 6:54am UTC](https://www.ruby-forum.com/t/accessing-c-structures-in-ruby/50108/7 "2005-12-13T06:54:20Z")

</div>

On 2005.12.13 14:14, Joe Van D. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> > > > double z;  
> > > > int type;  
> > > > module Simulation
> 
> return Data\_Wrap\_Struct(self, NULL, NULL, &Players[i]);
> 
> rb\_float\_new(get\_player(self)-\>velocity.y); }  
> rb\_define\_method(cSimulation, “mission\_time”, get\_mission\_time, 0);  
> rb\_define\_method(cPlayer, “x\_velocity”, get\_player\_x\_vel, 0);  
> rb\_define\_method(cPlayer, “y\_velocity”, get\_player\_y\_vel, 0);  
> rb\_define\_method(cPlayer, “z\_velocity”, get\_player\_z\_vel, 0);  
> }

Yep, that looks fine to me. There are certainly other ways but aside  
from some repetitiveness, this is easy and versatile (particularly if  
you need to pass data to C libraries as well). If you have lots and  
lots of functions like that, you could even do with a little #define.

E

---

<div class="post-metadata">

**Author:** ![joe-dumoulin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9dc877/32.png) [@joe-dumoulin](https://www.ruby-forum.com/u/joe-dumoulin)\
**Post date:** [December 13, 2005, 11:00am UTC](https://www.ruby-forum.com/t/accessing-c-structures-in-ruby/50108/8 "2005-12-13T11:00:48Z")

</div>

Eero S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Yep, that looks fine to me. There are certainly other ways but aside  
> from some repetitiveness, this is easy and versatile (particularly if  
> you need to pass data to C libraries as well). If you have lots and  
> lots of functions like that, you could even do with a little #define.

[CGenerator](http://redshift.sourceforge.net/cgen/) might be helpful (not used it  
myself, but this seems like a prime use case)

martin

---

<div class="post-metadata">

**Author:** ![joe-dumoulin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9dc877/32.png) [@joe-dumoulin](https://www.ruby-forum.com/u/joe-dumoulin)\
**Post date:** [December 13, 2005, 7:00pm UTC](https://www.ruby-forum.com/t/accessing-c-structures-in-ruby/50108/9 "2005-12-13T19:00:31Z")

</div>

Martin DeMello wrote:

> martin

I would have mentioned it but the OP wanted to do things the hard way 🙂

Cgen takes care of accessors (including type checking/conversion,  
marshalling, mark/free when accessors are typed to refer to objects),  
and also manages inheritance of structure members in parallel with the  
ruby inheritance hierarchy. It’s got a nice wrapper around  
rb\_parse\_args. It’s also good if you want to dynamically generate the  
extension in response to loaded code, user input, etc. I’ve been using  
it for over 4 years now. The docs need work, though…

An example (simplified from  
[Enscript Output](http://redshift.sourceforge.net/cgen/examples/complex.rb.html)):

require ‘cgen/cshadow’

class MyComplex \< Numeric  
include CShadow  
shadow\_attr\_accessor :re =\> “double re”, :im =\> “double im”  
end

MyComplex.commit

z = MyComplex.new  
z.re = 5  
z.im = 1.3  
p z

**END**

Output:

#\<MyComplex:0x2b04630 im=1.3, re=5.0\>

The full example also shows how to add methods written in C (but  
embedded in your ruby source) to do abs() and in-place multiplication.

Running this example generates a directory with the following contents,  
which is used to build the extension (all of this happens during the  
commit call):

C:\ruby\prj\cgen\examples\>ls -l MyComplex  
total 220  
-rw-rw-rw- 1 vjoel 0 45 2005-12-13 09:42 extconf.rb  
-rw-rw-rw- 1 vjoel 0 150 2005-12-13 09:42 make.log  
-rw-rw-rw- 1 vjoel 0 3619 2005-12-13 09:42 Makefile  
-rw-rw-rw- 1 vjoel 0 25 2005-12-13 09:39 MyComplex-i386-mswin32.def  
-rwxrwxrwx 1 vjoel 0 3589 2005-12-13 09:39 MyComplex.c  
-rw-rw-rw- 1 vjoel 0 589 2005-12-13 09:40 MyComplex.exp  
-rw-rw-rw- 1 vjoel 0 762 2005-12-13 09:39 MyComplex.h  
-rw-rw-rw- 1 vjoel 0 1976 2005-12-13 09:40 MyComplex.lib  
-rw-rw-rw- 1 vjoel 0 17259 2005-12-13 09:39 MyComplex.obj  
-rw-rw-rw- 1 vjoel 0 91136 2005-12-13 09:40 MyComplex.pdb  
-rw-rw-rw- 1 vjoel 0 20546 2005-12-13 09:40 MyComplex.so  
-rw-rw-rw- 1 vjoel 0 53248 2005-12-13 09:39 vc60.pdb

Cgen is careful not to repeat all this work the second time you run the  
same program–it writes files only if they have changed.

And just to give an idea of what functions it handles:

C:\ruby\prj\cgen\examples\MyComplex\>grep “^\w” MyComplex.c  
static void mark\_MyComplex\_Shadow(MyComplex\_Shadow \*shadow);  
static void free\_MyComplex\_Shadow(MyComplex\_Shadow \*shadow);  
VALUE module\_MyComplex;  
void Init\_MyComplex(void)  
static void mark\_MyComplex\_Shadow(MyComplex\_Shadow \*shadow)  
static void free\_MyComplex\_Shadow(MyComplex\_Shadow \*shadow)  
VALUE \_\_dump\_\_data\_module\_MyComplex\_method(VALUE self)  
VALUE \_\_load\_\_data\_module\_MyComplex\_method(VALUE self, VALUE from\_array)  
VALUE im\_module\_MyComplex\_method(VALUE self)  
VALUE im\_equals\_module\_MyComplex\_method(int argc, VALUE \*argv, VALUE  
self)  
VALUE re\_module\_MyComplex\_method(VALUE self)  
VALUE re\_equals\_module\_MyComplex\_method(int argc, VALUE \*argv, VALUE  
self)  
VALUE new\_module\_MyComplex\_singleton\_method(int argc, VALUE \*argv, VALUE  
self)  
VALUE alloc\_func\_module\_MyComplex(VALUE klass)

Here’s an example (sample.rb) showing the argument parsing wrapper:

lib2.define\_c\_singleton\_method(Point, :test).instance\_eval {  
c\_array\_args {  
required :arg0, :arg1  
optional :arg2, :arg3, :arg4  
typecheck :arg2 =\> Numeric, :arg3 =\> Numeric  
default :arg3 =\> “INT2NUM(7)”,  
:arg4 =\> “INT2NUM(NUM2INT(arg2) + NUM2INT(arg3))”  
rest :rest  
block :block  
}  
body %{  
rb\_funcall(block, #{declare\_symbol :call}, 6,  
arg0, arg1, arg2, arg3, arg4, rest);  
}  
}
