Olivier Lalonde
Olivier Lalonde

Reputation: 19908

Extending Ruby with C++?

Is there any way to pass Ruby objects to a C++ application ? I have never done that kind of thing before and was wondering if that would be possible. Would it require to modify the Ruby core code ?

Upvotes: 1

Views: 1611

Answers (4)

Bernard Banta
Bernard Banta

Reputation: 755

You can build Ruby extensions in C++ using Rice, take a look at http://www.ibm.com/developerworks/library/os-extendruby/

Upvotes: 0

faran
faran

Reputation: 3773

The Programming Ruby book has some details on accessing Ruby from C. I am not sure how current the documentation is though. This blog post describes the Ruby C API as well.

Upvotes: 1

psyho
psyho

Reputation: 7212

Extending Ruby with C++ is not a problem. Basically the only thing you need to remember when writing your extension is to declare an init method of your extension as extern "C", like so:

extern "C" void Init_your_extension() { // ... }

I recently had to expose a C++ function to my ruby code, you can find the code here if you want (its just basic stuff, so I think it will be good to get you started): http://github.com/psyho/aspell_edit_dist

Upvotes: 2

greyfade
greyfade

Reputation: 25647

Yes, and no, respectively.

Ruby is written in C. C++ is, by design, C-compatible.

All objects in Ruby are held by a VALUE object (which is a union type), which can be passed around quite easily.

Any directions you find for extending Ruby with C apply in C++ with little modification. Alternatively, you can use something like SWIG to simplify writing your extensions.

Upvotes: 5

Related Questions