What's the best way to embed Ruby as a scripting language in C++? Using ruby.h? SWIG? Something else? What I need is to expose some C++ objects to Ruby and have the Ruby interpreter evaluate scripts that access these objects. I don't care about extending Ruby or accessing it in C++.
I've found this article on embedding Ruby in C++, and while it's very useful, it's kinda old and I was wondering if there are any other resources on the subject (or open source implementations of similar engines).
Writing A Ruby Method From C A VALUE is a Ruby object. Now we need to attach this function to a Ruby class or module. You can create a new class or use an existing one. You can use the rb_define_method method to attach the C function to this module.
eRuby stands for embedded Ruby. It's a tool that embeds fragments of Ruby code in other files such as HTML files similar to ASP, JSP and PHP. eRuby allows Ruby code to be embedded within (delimited by) a pair of <% and %> delimiters.
Ruby is much much simpler than C++—it will spoil you rotten. Ruby is dynamically typed, rather than statically typed—the runtime does as much as possible at run-time. For example, you don't need to know what modules your Ruby program will “link to” (that is, load and use) or what methods it will call ahead of time.
Embedding Ruby requires one header ruby.h, which includes a platform-specific header ruby/config.h. You will probably need to tell your compiler about the include paths for these headers. You will also need to link with the Ruby lib. On my machine, my minimal compiler options are
Including the Ruby interpreter in your C/C++ program is pretty simple. Just include the header, call a startup function in main before you use the API, and a cleanup function after you’re done:
A VALUE is a Ruby object. Now we need to attach this function to a Ruby class or module. You can create a new class or use an existing one. You can use the rb_define_method method to attach the C function to this module. Now run make again to compile the extension, and try it like this:
As with C, in Ruby,… You may program procedurally if you like (but it will still be object-oriented behind the scenes). Most of the operators are the same (including the compound assignment and also bitwise operators). Though, Ruby doesn’t have ++ or --.
Rice is looking very promising.
Ruby provides a very helpful README.EXT file. It has lots of information about how to extend Ruby, and convert between C & Ruby types.
There is also this excerpt from the pick axe book which pretty much covers the same thing.
In my case, when I added Ruby scripting to my application I decided against using swig, because my needs were very simple, and I didn't want to add yet another build dependency.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With