From: gwtmp01@... Date: 2007-01-11T23:03:22+09:00 Subject: Re: Sharing constants between C and Ruby code On Jan 11, 2007, at 8:23 AM, Nathaniel Trellice wrote: > What I was thinking of doing was writing a Ruby class (in C) which has > the constants as class constants. This way, compiling the class will > pull in the #defines from the C header file, and they'll be available > within Ruby from my class. But, being new to ruby, I was hoping to > avoid > having to figure out how to write a Ruby class in C at this stage > of my > ruby development! I don't think that approach would buy you much. You would still have to maintain (by hand) a C file that mapped the C constants (from the .h file) into Ruby constants. I'm not a Ruby's internal programmer but I imagine you would have to have something like: rb_constant_set( klass, 'MY_CONSTANT', MY_CONSTANT) for every single constant. Note: I made up the function name and API, but you would have to explicitly bind the string 'MY_CONSTANT' to the value represented by the MY_CONSTANT macro via some sort of function call. I can't imagine that maintaining that C file by hand is any easier than the simple parsing suggestion that has already been described to generate a pure Ruby class. Alternatively, you could describe your constants via something like YAML and write (in Ruby!) code to generate a C header file for the constants and Ruby class for your use in the Ruby side of things. Even easier, something like: class Constants A = 100 B = 200 C = A + B def self.to_h constants.sort.inject("") { |t,c| t << "#define #{c} #{const_get(c)}\n" } end end Now you can maintain this class directly and have it generate your C .h file via: open("constants.h", "w") { |f| f.write Constants.to_h } Anyway, I think there are lots of ways to handle your situation without having to dive into writing Ruby extensions and/or classes in C. Gary Wright