3

I'm implementing a DLL containing a shared ADO Connection by using the ConnectionObject property of TADOConnection and passing it across DLL boundaries into other instances of TADOConnection. I need to make sure COM is initialized, so I need to call CoInitialize / CoUninitialize. Currently it's in the context of a VCL main thread, but could be elsewhere in another thread, which of course requires its own instance of COM. I'm not currently implementing multi-threading.

Where is the appropriate place to call these; inside the DLL (during loading/unloading), outside the DLL (calling process), or both? Considering it's only one thread, shouldn't it be only one time outside the DLL in the original process?

I'm assuming the original calling thread should be solely responsible for this, since COM runs in the context of a thread. Of course calling them on both sides shouldn't hurt any, however it would also create multiple COM instances.

Long story short... Is it "safe to be safe" in this case? Or is it important to only keep one COM instance?

Community
  • 1
  • 1
Jerry Dodge
  • 26,858
  • 31
  • 155
  • 327
  • I basically answered my own question while typing it, I just needed confirmation of what I understood. – Jerry Dodge May 03 '15 at 23:45
  • *Of course calling them on both sides shouldn't hurt any, however it would also create multiple COM instances.* - But it hurts. You should only `CoInitialize` a thread you own. – acelent May 04 '15 at 10:03

1 Answers1

7

You should not be doing this in the DLL. Make it part of the contract between the DLL and the host that the host is responsible for initializing COM.

The DLL cannot be expected to initialize COM because the host may already have done so. And use a different threading model. Once COM has been initialized then future attempts to initialize will fail if they attempt to change the threading mode.

So, don't initialize COM in your DLL. Require the host to do so.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Yes, the different threading models slipped my mind - that would most definitely pose issues across both implementations of the shared connection. – Jerry Dodge May 03 '15 at 23:38
  • It's not really about DLL code, it's about thread ownership. If you start the thread, you may (and probably should) initialize COM. If you didn't, you may at most require the caller to have initialized COM in a specific way (e.g. single-threaded, multi-threaded, OLE). – acelent May 04 '15 at 10:13