Sunday, June 6, 2010

SWIG Ruby constants

This is my further adventures in the use of SWIG for Ruby 1.9

I defined constants in interface.i for SWIG

#define constant1 10
#define constant1 20

and I got the ruby module created. However how do I use the constants? Turns out that SWIG creates the constants in a funny (though still usable) way. Assuming you call your module 'm', you can see the relevant methods in irb by executing M.methods. The most important ones are

M.constants <= returns an array of the constants
M.const_get(symbol) <= returns actual value

For example

irb>M.const_get :constant1
10

There is another method M.const_set(symbol,x) which is useful if you are extending the module with more constants. If you just call

irb> M.const_set :constant1 2

this returns an error, as :constant1 is probably declared final (or its equivalent).