From: Stefano Crocco Date: 2007-01-23T01:18:41+09:00 Subject: Re: ebedded: calling a C function from script. Alle 16:35, luned� 22 gennaio 2007, Shea Martin ha scritto: > I have my embedded interpreter running my scipt. Now I would like my > script to call function in my C++ program. > > i.e., > > int getSomeValue() > { > return 5; > } > > void setSomeValue( int value ) > { > _value = value; > } > > How would I call these functions from my ruby script? > > ~S If I understand correctly what you mean, I think you need to create a ruby method wrapping that function. If you want to do that at kernel-level, that is not inside a class, you should do the following (in your C code) (NOTE: all this is untested. I've tried a little project which mixed ruby and C some time ago, but soon abandoned it. What I'm telling comes from my memory of that attempt and its source code): 1: define a static C function which wraps your own. It must accept at least one argument of type VALUE (the first one is self) and return a VALUE (return Qnil if you don't need the return value). For instance, a wrapper around your getSomeValue() could be something like static VALUE _getSomeValue(VALUE self){ //INT2NUM converts from a C int to a ruby number (FixNum or BigNum) return INT2NUM(getSomeValue()); } 2: Create a ruby method which calls _getSomeValue. To do this, use the rb_define_global_function function: rb_define_global_function("get_some_value", _getSomeValue, 1); Here the first argument is the name of the ruby method, _getSomeValue is a pointer to the C function which implements the method and 1 is the number of arguments of the C function. After calling rb_define_global_function, you'll be able to call "get_some_value" from your script: puts get_some_value => 5 If you need more information on this topic, you can refer to the Pickaxe book, in the chapter called (at least in the online edition) "Extending ruby". Besides, you may find useful the ruby C api (http://www.ruby-doc.org/doxygen/current/) and, of course, ruby source code. Moreover, today on the mailing list was announced a tutorial on writing ruby extensions. It's at http://nanoblog.ath.cx/index.rb?module=readmore&id=8 I haven't read it, so I don't know if it can be useful to you (there are differences between writing an extension and embedding the interpreter) I hope this helps Stefano