Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

double calls to CoInitialize()

Tags:

com

winapi

Let's say my application calls CoInitialize when it starts and CoUninitialize before it exists.

Assuming I have a 3rd party component that's used by my application and does a similar thing, will this cause some kind of failure?

is it okay to call CoInitialize when that call has already been submitted? will the second call fail? or will it just "let it pass" as it's already called.

like image 317
JasonGenX Avatar asked Oct 19 '11 16:10

JasonGenX


2 Answers

CoInitialize will return S_FALSE if it has already been initialized in the calling thread. However, for both invocations that return S_OK and S_FALSE there needs to be a CoUninitialize call. The number of calls to this functions get counted, and only when the number of CoUninitialize equals that of CoInitialize it will actually uninitialize things.

So in conclusion, a second call is harmless, and there are no problems with calling this pair of functions more than once.

like image 110
K-ballo Avatar answered Oct 13 '22 00:10

K-ballo


It is pretty fundamentally wrong, CoInitialize() must be called by the code that owns the thread. Which is never the 3rd party component if it acts like an in-process server and doesn't start its own threads.

And sure, this can and will go wrong when it doesn't agree about the apartment type. Which is something it cannot guarantee, an STA is the usual choice and that requires pumping a message loop. The component won't do that, it's the host's job. And if the apartment type is a mismatch then it needs to marshal the interface pointer. Which it won't do when it relies on its apartment type of choice.

like image 7
Hans Passant Avatar answered Oct 12 '22 23:10

Hans Passant