While building my Ruby <-> CLR shim, I came across a nasty issue with
respect to initializing the CLR in a delay-load scenario.
In existing versions of the CLR (< 2.0), COM is not guaranteed to be
initialized. Most of the time it isn't, which is why all of the existing
Ruby <-> CLR bridges can call CoInitializeEx via
Thread.ApartmentStatewithout potentially breaking something. However,
there are some (rare)
scenarios where the CLR will initialize COM prior to the Ruby bridge being
called, which will hose folks who were attempting to change the
ApartmentState in their Ruby scripts (or in their bridge).
The Whidbey (V2.0) version of the CLR forces all threads into the MTA by
default - this gets rid of the indeterminate behavior of earlier versions of
the CLR. This currently will hose anyone using any of the existing bridges,
unless you jump through some exotic hoops. Once I release the source for my
bridge, you'll see what those exotic hoops look like. If any of the existing
bridge maintainers want to know the specifics, please feel free to ask away.
Why would someone need to specify a COM threading model? If, for example you
want to create a Windows Forms application or an Avalon application, you'll
need to have your thread running in its own STA. But if I don't initialize
the CLR until after my Ruby program has already started running, I'm going
to run into some nasty corner cases. For example, what if someone called a
COM object via win32ole? By the time we get to my shim, COM will have been
initialized already and there's not a lot I can do other than fail when I
attempt to initialize COM again.
What would be better is to declare my COM threading requirements at startup
time for my Ruby program. Now, I really don't know Ruby all that well, so I
was wondering if folks would have some ideas about *how* I can declare my
threading requirements at startup time? In a C# program, I can do this:
[STAThread]
public static void Main() { ... }
The CLR will guarantee that the thread that calls into Main() will live in
its own STA if it sees a [STAThread] attribute on the Main() method.
Now, I don't really know Ruby all that well - I've only been using this
language for a few months. I was wondering if the community might have some
suggestions about how I might approach this problem. Perhaps some kind of
platform-specific runtime initialization file? For example, if you start a
foo.rb, that the Ruby runtime looks for the presence of a foo.rb.config file
to grab some startup configuration?
BTW, I'm going to be attending RubyConf this year, so if anyone wants to get
together to talk about Ruby <-> CLR integration, I'd be more than happy to
talk to you. I'm staying over for OOPSLA as well, so there should be ample
time to hack out a good solution to this problem
Thanks,
-John