double calls to CoInitialize()

2020-03-18 17:40发布

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.

标签: winapi com
2条回答
Animai°情兽
2楼-- · 2020-03-18 17:43

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.

查看更多
叛逆
3楼-- · 2020-03-18 18:09

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.

查看更多
登录 后发表回答