From: Bill Kelly Date: 2010-02-05T13:12:41+09:00 Subject: Re: embedding ruby Josep Pujol wrote: > > I would like to know if the problem with embedding ruby is that there > are global variables and also because of the stack. > > If this is the case, can I assume that it is safe to use the ruby engine > if I initialize it in the main process, before any thread is launched in > my C++ application (so the stack is in the lower position) and I use > mutex to prevent more than one run at any time (for the global > variables)? We embed ruby 1.8.x in a C++ app on Windows / OS X. In our case, we run Ruby in a separate thread. Only trick was that the stack size of threads other than the main thread may be small by default. And we use boost threads. So I had to modify boost to create the thread with a large enough stack: // boost/libs/thread/src/thread/cpp #if defined(BOOST_HAS_PTHREADS) const size_t THREAD_STACK_SIZE_BYTES = 8 * 1024 * 1024; pthread_attr_t tattr; int res = 0; res = pthread_attr_init(&tattr); if (res != 0) throw thread_resource_error(); res = pthread_attr_setstacksize(&tattr, THREAD_STACK_SIZE_BYTES); if (res != 0) throw thread_resource_error(); res = pthread_create(&m_thread, &tattr, &thread_proxy, ¶m); (void) pthread_attr_destroy(&tattr); if (res != 0) throw thread_resource_error(); When Ruby code wants to call into the C++ side of the app, it's easy, we just wrap whatever functionality from the app in a Ruby class, as one would do with any ruby 'C' extension. In the other direction, when an arbitrary C++ thread wants to talk to Ruby, it's a little more complicated. I've set up a queueing approach, where a C++ thread can create a "RubyContext" object, and throw eval's at it. Like: RubyContext r; std::string result = r.eval("...some_ruby_code..."); It works out pretty well. I haven't tried embedding ruby 1.9.x yet. Regards, Bill