From: vincent.fourmond@9online.fr Date: 2007-01-11T21:22:21+09:00 Subject: Re: Sharing constants between C and Ruby code ----- Original Message -----
From: Nathaniel Trellice
Date: Thursday, January 11, 2007 1:02 pm
Subject: Sharing constants between C and Ruby code
To: ruby-talk@ruby-lang.org (ruby-talk ML)

> Hello,
>
> I'm new to ruby, but fairly experienced in C. I am using Ruby on Rails
> to chat to a postgres database. I have some C functions that I can run
> in the database backend. I would like to use constants defined in C
> header files, e.g "#define MY_CONSTANT 100" within ruby code. I
> know I
> can similarly define a constant in ruby, i.e. "MY_CONSTANT=100", but
> given that I have quite a few of these, and synchronising the two
> filescould become tricky, is there some (preferably simple) clever
> way/hackthat I can define constants in a single file and use them
> both in C and
> in Ruby?

I think the best way is the following: have all you C defines in a separate .h file (and only those). Write a small ruby script taking all the lines in your header through something like (untested):

open(file) do |f|
for line in f
if line =~ /#define\s+(\w+)\s+(\S+)/
puts "#{$1} = #[$2}"
end
end
end

Use this to create a .rb file, and have it regenerated through a Makefile.

Cheers,

Vince