开发者

C++ setTimout function?

开发者 https://www.devze.com 2022-12-27 06:44 出处:网络
What\'s the cheapest way for a JavaScript like setTimeout-function in C++? I would need this: 5000 miliseconds from now, start function xy (no parameters, no return value).

What's the cheapest way for a JavaScript like setTimeout-function in C++?

I would need this: 5000 miliseconds from now, start function xy (no parameters, no return value).

The reason for this is I need to initialize COM for text to speech, but when I do it on dll attach, it crashes.

It works fine however if I do not call CoInitialize from dllmain.

I just need to call CoInitialize and CoCreateInstance, and th开发者_如何学Goen use the instance in other functions. I can catch the uninitialized instance by checking for NULL, but I need to initialize COM - without crashing.


Calling CoInitialize() from DllMain() is a bad thing to do; there are LOTS of restrictions on what you can do from DllMain(); see here: http://blogs.msdn.com/larryosterman/archive/2004/04/23/118979.aspx

Even if it DID work reliably then initialising COM from within DllMain() isn't an especially nice thing to do as COM is initialised per thread and you don't know what the application itself wants to do with regards to COM apartments for the thread that you want to initialise COM for... This means that you might initialise COM in one way and then the application might need to initialise it in another way and might fail because of what your DLL had done...

You COULD spin up a thread in DllMain() as long as you are careful (see here http://blogs.msdn.com/oldnewthing/archive/2007/09/04/4731478.aspx) and then initialise COM on that thread and do all your COM related work on that thread. You would need to marshal whatever data you need to use COM with from whatever thread you're called on to your own COM thread and make the COM call from there...

And then there's the question of whether the instance of the COM object that you create (could you reliably do what you want to do) would be usable from the thread that was calling into your DLL to make the call... You do understand how you'd have to marshal the interface pointer if required, etc?

Alternatively you should expose YOUR functionality via COM and then have the application load your DLL as a COM DLL and everything will work just fine. You can specify the apartment type that you need and the app is responsible for setting things up for you correctly.

So, in summary, you don't need the answer to your question.


When it is OK to stop the execution for 5 seconds entirely, you can use the Winapi Sleep function. Beware that the documentation of Sleep minds some possible problems with CoInitialize and Messages.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号