From: Chris Uzdavinis Date: 2001-11-17T00:48:36+09:00 Subject: [ruby-talk:25448] Re: embedding C++ Matthias Lampert writes: > Hi! > > One Question: Does anybody here have experience embedding > existing C++ classes into Ruby? Building a Ruby wrapper around > them and compiling everything with g++ does not do the trick, > does it? Others have mentioned swig, and we've been using that successfully too. However, I've also been working with non-swig C++ wrappers and have also had some success. There are some important issues to remember if you're writing code by hand. The biggest problem that needs to always be on your mind is when a Ruby exception is thrown. Since Ruby exceptions use longjmp, the stack is not unwound like C++ programmers expect. Local variables will NOT have their destructors invoked. Therefore you must always be very careful to protect your objects. There are a few ways to do this. One slowish way is to heap-allocate all your C++ objects and keep track of them in a global structure. You can stuff these objects into Ruby objects and let the Ruby garbage collector take care of the memory for you if you'd like. (But you still need to keep track of those ruby objects somewhere so you can mark them for the garbage collector while you're still using them.) Another thing you can do is create local scopes around local variables in such a way that they always go out of scope before any ruby function that can possibly "throw" is called. This is a variation of the design rule of "don't allow ANY stack-based variables to exist who need a destructor invoked to exist when you call ruby functions." A final way to accomplish this may be to use setjmp yourself in each of your C++ functions, however I have not experimented at all with this approach and it sounds like a high-overhead solution. I've been thinking about writing up the issues I've encountered, but I still don't have a good enough solution to where I'm convinced it's worth writing about. -- Chris