On 1/11/07, vincent.fourmond / 9online.fr <vincent.fourmond / 9online.fr> wrote: > ----- 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. This is seems to me as the best approach - you could create extension that you'd require, and that would define those constants, but it will be unnecessarily complicated. Just write your header to be easily parsable and you're done.