Programming note: CoInitializeEx

This posting is of historical interest. It exists to help other programmers who may come across a similar problem.

With a one-line change we had got Cardbox working on Internet databases. Now the time had come to try it on local databases: that is, databases stored on the computer that is running Cardbox. This is worrying because it is more complex than the Internet case. With Internet databases, Cardbox communicates via TCP/IP with a remote server that is already running when Cardbox starts. With local databases, Cardbox has to launch a “hidden server” automatically and communicate with it using shared memory. This exercises many more components of Windows, including Microsoft’s dreaded COM/OLE – dreaded because it is an awkward implementation of an awkward design. You only have to look at how many versions of the OLE DLL files Microsoft have had to issue to see that even the inventor of the technology had difficulty coping with it.

We tried File > Open > My Computer, clicked on a database, and sure enough, Cardbox crashed.

Looking at the crash, we saw that a CoCreateInstance call that never fails under Windows had failed under Wine. We modified Cardbox so that it would report an error in this case, rather than crashing, and braced ourselves for the discovery that the COM/OLE implementation in basic Wine was so weak that Cardbox would never work.

That discovery never came. The bug turned out to be ours. The CoCreateInstance call is run in a separate thread, and it turned out that we had not called CoInitializeEx in that thread. For some reason Windows didn’t mind – probably because it automatically put the thread in the multi-threaded apartment, which is where we wanted it to be – but Wine (constructed independently from the Windows documentation) enforced the requirement. Putting


at the start of the thread procedure and


at the end removed the bug.

Now Cardbox could open local databases just as it could open Internet databases. It looked as if the whole thing was going to work after all.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: